import { useQuery } from '@tanstack/react-query'
import { Link } from 'react-router-dom'
import { motion, AnimatePresence, useScroll, useTransform, useReducedMotion } from 'framer-motion'
import { useRef, useState, useEffect, useCallback } from 'react'
import { Sparkles, Flower2, Leaf, Star, ArrowRight, Truck, HandHeart, ShieldCheck, ChevronLeft, ChevronRight } from 'lucide-react'
import { aiRecommend, getProducts } from '../api/client'
import ProductCard from './components/ProductCard'
import { Reveal, StaggerGrid, StaggerItem, PetalLayer, Pressable } from './components/motion'
import { useShop } from '../store/shop'
import { BRAND, HERO_SLIDES } from './brand'

const PROMISE_ICON = [HandHeart, Flower2, ShieldCheck]
const SLIDE_INTERVAL = 6000 // 6초 자동 전환

function HeroCarousel() {
  const { storeName } = useShop()
  const reduce = useReducedMotion()
  const heroRef = useRef<HTMLDivElement>(null)
  const { scrollYProgress } = useScroll({ target: heroRef, offset: ['start start', 'end start'] })
  const heroY = useTransform(scrollYProgress, [0, 1], ['0%', reduce ? '0%' : '28%'])
  const heroScale = useTransform(scrollYProgress, [0, 1], [1, reduce ? 1 : 1.12])
  const heroFade = useTransform(scrollYProgress, [0, 0.8], [1, reduce ? 1 : 0.2])

  const [idx, setIdx] = useState(0)
  const [dir, setDir] = useState(1)
  const count = HERO_SLIDES.length

  const go = useCallback((next: number) => {
    setDir(next > idx || (idx === count - 1 && next === 0) ? 1 : -1)
    setIdx(((next % count) + count) % count)
  }, [idx, count])

  // 자동 회전 — prefers-reduced-motion 시 첫 슬라이드 고정
  useEffect(() => {
    if (reduce) return
    const t = setInterval(() => {
      setDir(1)
      setIdx(i => (i + 1) % count)
    }, SLIDE_INTERVAL)
    return () => clearInterval(t)
  }, [reduce, count])

  const slide = HERO_SLIDES[idx]

  return (
    <section ref={heroRef} className="relative overflow-hidden min-h-[78vh] flex items-center">
      {/* 배경 이미지 크로스페이드 (패럴랙스) */}
      <motion.div style={{ y: heroY, scale: heroScale }} className="absolute inset-0 z-0">
        <AnimatePresence initial={false}>
          <motion.img
            key={slide.img}
            src={slide.img}
            alt=""
            className="absolute inset-0 w-full h-full object-cover"
            initial={{ opacity: 0, scale: reduce ? 1 : 1.06 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: reduce ? 0 : 1.1, ease: [0.22, 1, 0.36, 1] }}
          />
        </AnimatePresence>
        <div className="absolute inset-0 bg-gradient-to-r from-blush-900/70 via-blush-900/40 to-transparent" />
        <div className="absolute inset-0 bg-gradient-to-t from-sage-900/40 to-transparent" />
      </motion.div>

      <PetalLayer count={16} className="z-[1]" />

      {/* 텍스트 슬라이드 — 헤드라인/문구/CTA 전환 */}
      <motion.div style={{ opacity: heroFade }} className="relative z-10 max-w-6xl mx-auto px-4 w-full py-20">
        <AnimatePresence mode="wait" custom={dir}>
          <motion.div
            key={idx}
            className="max-w-xl"
            custom={dir}
            initial={reduce ? false : { opacity: 0, x: dir * 36 }}
            animate={{ opacity: 1, x: 0 }}
            exit={reduce ? { opacity: 0 } : { opacity: 0, x: dir * -36 }}
            transition={{ duration: 0.7, ease: [0.22, 1, 0.36, 1] }}
          >
            <div className="inline-flex items-center gap-2 text-cream/90 text-[12px] tracking-[0.25em] uppercase mb-5">
              <span className="h-px w-8 bg-gold" /> {slide.eyebrow}
            </div>
            <h1 className="font-serif text-5xl md:text-6xl font-bold text-white leading-[1.05] mb-5 whitespace-pre-line drop-shadow-sm">
              {slide.headline}
            </h1>
            <p className="text-cream/90 text-lg leading-relaxed mb-8 max-w-md font-light">
              {slide.subtext}
              {storeName ? ` Same-day from ${storeName}.` : ''}
            </p>
            <div className="flex flex-wrap gap-3">
              <Link to={slide.to}>
                <Pressable className="inline-flex items-center gap-2 bg-white text-blush-700 font-semibold px-7 py-3.5 rounded-full shadow-bloom hover:bg-cream">
                  {slide.cta} <ArrowRight size={17} />
                </Pressable>
              </Link>
              <Link to="/daily-standard">
                <Pressable className="inline-flex items-center gap-2 border border-white/70 text-white px-7 py-3.5 rounded-full hover:bg-white/10">
                  <Leaf size={16} /> Today's Bouquet
                </Pressable>
              </Link>
            </div>
            <div className="flex items-center gap-2 mt-7 text-cream/85 text-sm">
              <span className="flex text-gold">{[1, 2, 3, 4, 5].map(i => <Star key={i} size={15} fill="currentColor" />)}</span>
              <span className="font-medium">{BRAND.rating}</span>
              <span className="text-cream/60">· {BRAND.reviewCount.toLocaleString()} happy customers</span>
            </div>
          </motion.div>
        </AnimatePresence>
      </motion.div>

      {/* 좌우 화살표 */}
      <button
        aria-label="Previous slide"
        onClick={() => go(idx - 1)}
        className="absolute left-3 md:left-5 top-1/2 -translate-y-1/2 z-20 w-11 h-11 rounded-full bg-white/15 hover:bg-white/30 backdrop-blur-sm text-white flex items-center justify-center transition-colors"
      >
        <ChevronLeft size={22} />
      </button>
      <button
        aria-label="Next slide"
        onClick={() => go(idx + 1)}
        className="absolute right-3 md:right-5 top-1/2 -translate-y-1/2 z-20 w-11 h-11 rounded-full bg-white/15 hover:bg-white/30 backdrop-blur-sm text-white flex items-center justify-center transition-colors"
      >
        <ChevronRight size={22} />
      </button>

      {/* 인디케이터 (점) */}
      <div className="absolute bottom-7 left-1/2 -translate-x-1/2 z-20 flex items-center gap-2.5">
        {HERO_SLIDES.map((_, i) => (
          <button
            key={i}
            aria-label={`Go to slide ${i + 1}`}
            onClick={() => go(i)}
            className={`h-2.5 rounded-full transition-all duration-300 ${i === idx ? 'w-8 bg-white' : 'w-2.5 bg-white/45 hover:bg-white/70'}`}
          />
        ))}
      </div>

      {/* sway 보태니컬 장식 */}
      <motion.div
        aria-hidden
        className="absolute -bottom-6 right-6 z-[2] text-white/20 hidden md:block pointer-events-none"
        animate={reduce ? undefined : { rotate: [0, 5, -4, 0], y: [0, -8, 0] }}
        transition={{ duration: 9, repeat: Infinity, ease: 'easeInOut' }}
      >
        <Flower2 size={130} strokeWidth={1} />
      </motion.div>
    </section>
  )
}

export default function Home() {
  const { data: recs } = useQuery({ queryKey: ['ai-rec'], queryFn: () => aiRecommend('', '', 8) })
  const { data: bestData } = useQuery({ queryKey: ['best'], queryFn: () => getProducts({ sort: 'sales', size: 8 }) })
  const { data: featData } = useQuery({ queryKey: ['feat'], queryFn: () => getProducts({ sort: 'rating', size: 12 }) })
  const best = bestData?.items || []
  const featured = featData?.items || []

  return (
    <div>
      {/* ── 풀블리드 회전 히어로 캐러셀 (3슬라이드) ── */}
      <HeroCarousel />

      {/* ── 브랜드 약속 (3대 헌신) ── */}
      <section className="bg-ivory border-b border-blush-100">
        <div className="max-w-6xl mx-auto px-4 py-10 grid md:grid-cols-3 gap-6">
          {BRAND.promise.map((pr, i) => {
            const Icon = PROMISE_ICON[i]
            return (
              <Reveal key={pr.title} delay={i * 0.1} className="flex items-start gap-3">
                <span className="shrink-0 w-11 h-11 rounded-full bg-blush-50 text-blush-500 flex items-center justify-center"><Icon size={20} /></span>
                <div>
                  <div className="font-serif text-lg text-blush-900">{pr.title}</div>
                  <p className="text-sm text-[#6b5258] leading-relaxed mt-0.5">{pr.desc}</p>
                </div>
              </Reveal>
            )
          })}
        </div>
      </section>

      <div className="max-w-6xl mx-auto px-4 py-14 space-y-20">
        {/* ── AI 추천 부케 ── */}
        <section>
          <Reveal className="flex items-end justify-between mb-7">
            <div>
              <div className="flex items-center gap-2 text-sage-600 text-[12px] tracking-[0.2em] uppercase mb-2">
                <Sparkles size={15} /> Curated by GUARDiA AI · On-premise
              </div>
              <h2 className="font-serif text-3xl text-blush-900">Picked Just for You</h2>
            </div>
            <Link to="/category" className="hidden sm:flex items-center gap-1 text-sm text-blush-500 hover:text-blush-700">View all <ArrowRight size={15} /></Link>
          </Reveal>
          <StaggerGrid className="grid grid-cols-2 md:grid-cols-4 gap-5">
            {(recs || []).slice(0, 8).map((p: any) => (
              <StaggerItem key={p.id}><ProductCard p={p} /></StaggerItem>
            ))}
            {!(recs || []).length && <div className="col-span-4 text-blush-300 text-sm py-12 text-center">Curating fresh picks…</div>}
          </StaggerGrid>
        </section>

        <div className="botanical-divider"><Flower2 size={18} /></div>

        {/* ── Daily Standard 프로모 (Farmgirl) ── */}
        <Reveal>
          <section className="relative overflow-hidden rounded-4xl bg-gradient-to-br from-sage-700 to-sage-800 text-white">
            <PetalLayer count={8} />
            <div className="relative z-10 p-8 md:p-12 flex flex-col md:flex-row items-center justify-between gap-6">
              <div className="max-w-lg">
                <div className="flex items-center gap-2 text-sage-200 text-[12px] tracking-[0.2em] uppercase mb-3"><Leaf size={15} /> Farmgirl-style daily</div>
                <h3 className="font-serif text-3xl md:text-4xl font-bold mb-3">Today's Designer Bouquet</h3>
                <p className="text-cream/85 leading-relaxed">Made fresh each morning with whatever's most beautiful in the cooler — hand-designed by our florists and curated by GUARDiA AI. Limited daily stock.</p>
              </div>
              <Link to="/daily-standard">
                <Pressable className="inline-flex items-center gap-2 bg-white text-sage-800 font-semibold px-7 py-3.5 rounded-full shadow-bloom">
                  See today's bouquet <ArrowRight size={16} />
                </Pressable>
              </Link>
            </div>
          </section>
        </Reveal>

        {/* ── 베스트셀러 ── */}
        <section>
          <Reveal className="flex items-end justify-between mb-7">
            <div>
              <div className="flex items-center gap-2 text-sage-600 text-[12px] tracking-[0.2em] uppercase mb-2"><Star size={14} /> Most loved</div>
              <h2 className="font-serif text-3xl text-blush-900">Bestsellers</h2>
            </div>
            <Link to="/category?sort=sales" className="hidden sm:flex items-center gap-1 text-sm text-blush-500 hover:text-blush-700">View all <ArrowRight size={15} /></Link>
          </Reveal>
          <StaggerGrid className="grid grid-cols-2 md:grid-cols-4 gap-5">
            {best.map((p: any) => <StaggerItem key={p.id}><ProductCard p={p} /></StaggerItem>)}
          </StaggerGrid>
        </section>

        {/* ── 잡지형 컬렉션 배너 ── */}
        <Reveal>
          <section className="grid md:grid-cols-3 gap-5">
            {[
              { to: '/category?occasion=ROMANCE', label: 'Love & Romance', sub: 'Roses that speak from the heart', img: featured[1]?.thumbnail },
              { to: '/category?occasion=SYMPATHY', label: 'Sympathy & Comfort', sub: 'Thoughtful tributes, gently delivered', img: featured[2]?.thumbnail },
              { to: '/subscription', label: 'Flower Subscriptions', sub: 'Fresh blooms, week after week', img: featured[3]?.thumbnail },
            ].map((c, i) => (
              <Link key={c.to} to={c.to} className="group relative rounded-3xl overflow-hidden zoom-frame aspect-[5/4] block shadow-soft">
                {c.img ? <img src={c.img} alt="" loading="lazy" className="w-full h-full object-cover group-hover:scale-110" />
                  : <div className="w-full h-full bg-gradient-to-br from-blush-100 to-sage-100" />}
                <div className="absolute inset-0 bg-gradient-to-t from-blush-900/75 via-blush-900/20 to-transparent" />
                <div className="absolute bottom-0 left-0 p-6 text-white">
                  <div className="font-serif text-xl font-semibold mb-0.5">{c.label}</div>
                  <p className="text-cream/85 text-sm">{c.sub}</p>
                  <span className="inline-flex items-center gap-1 text-[13px] text-gold mt-2 group-hover:gap-2 transition-all">Explore <ArrowRight size={14} /></span>
                </div>
              </Link>
            ))}
          </section>
        </Reveal>

        {/* ── 로컬 신뢰 배너 ── */}
        <Reveal>
          <section className="rounded-4xl bg-blush-50 border border-blush-100 p-8 md:p-10 text-center">
            <div className="flex justify-center mb-4"><span className="w-12 h-12 rounded-full bg-white text-blush-500 flex items-center justify-center shadow-soft"><Truck size={22} /></span></div>
            <h3 className="font-serif text-2xl text-blush-900 mb-2">Your Local Florist Since {BRAND.founded}</h3>
            <p className="text-[#6b5258] max-w-xl mx-auto leading-relaxed text-[15px]">{BRAND.about}</p>
            <div className="flex flex-wrap items-center justify-center gap-2 mt-5 text-[12px] text-sage-700">
              <span className="bg-white rounded-full px-3 py-1.5 shadow-soft">Same-Day Delivery</span>
              <span className="bg-white rounded-full px-3 py-1.5 shadow-soft">Hand-Delivered</span>
              <span className="bg-white rounded-full px-3 py-1.5 shadow-soft">100% Satisfaction</span>
              <span className="bg-white rounded-full px-3 py-1.5 shadow-soft">No-Contact Available</span>
            </div>
          </section>
        </Reveal>
      </div>
    </div>
  )
}
