import { useEffect, useState } from 'react'
import { Outlet, Link, useNavigate, useLocation } from 'react-router-dom'
import { motion, AnimatePresence, useReducedMotion } from 'framer-motion'
import {
  Flower2, MapPin, ShoppingCart, Heart, User, Search, Star, Phone,
  Clock, ChevronRight,
} from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { useShop } from '../store/shop'
import { getCart } from '../api/client'
import { BRAND } from './brand'
import { SocialLinks } from './components/social'
import { PaymentBadges } from './components/payments'
import LanguageSwitcher from '../i18n/LanguageSwitcher'

const NAV = [
  { to: '/home', key: 'home' },
  { to: '/category', key: 'shopAll' },
  { to: '/category?occasion=ROMANCE', key: 'loveRomance' },
  { to: '/category?occasion=BIRTHDAY', key: 'birthday' },
  { to: '/category?occasion=SYMPATHY', key: 'sympathy' },
  { to: '/daily-standard', key: 'todaysBouquet', accent: true },
  { to: '/subscription', key: 'subscriptions' },
  { to: '/events', key: 'offers' },
]

export default function ShopLayout() {
  const { t } = useTranslation()
  const { zip, storeName, custToken, cartCount, setCartCount } = useShop()
  const nav = useNavigate()
  const loc = useLocation()
  const reduce = useReducedMotion()
  const [q, setQ] = useState('')

  useEffect(() => {
    if (!custToken) { setCartCount(0); return }
    getCart().then((c: any[]) => setCartCount((c || []).reduce((s, i) => s + (i.quantity || 1), 0))).catch(() => {})
  }, [custToken])

  const doSearch = (e: React.FormEvent) => { e.preventDefault(); if (q.trim()) nav(`/search?q=${encodeURIComponent(q.trim())}`) }

  return (
    <div className="min-h-screen bg-cream text-[#43343a] flex flex-col">
      {/* ── 상단 안내 바 ── */}
      <div className="bg-sage-700 text-cream/95 text-[12px] tracking-wide">
        <div className="max-w-6xl mx-auto px-4 h-9 flex items-center justify-center sm:justify-between gap-3">
          <span className="hidden sm:flex items-center gap-1.5">
            <Flower2 size={13} /> {BRAND.tagline}
          </span>
          <span className="flex items-center gap-3">
            <span className="flex items-center gap-1">
              <Star size={12} className="text-gold" fill="currentColor" /> {BRAND.rating}★ · {t('shop.topbar.reviews', { n: BRAND.reviewCount.toLocaleString() })}
            </span>
            <a href={`tel:${BRAND.phoneTel}`} className="hidden sm:flex items-center gap-1 hover:text-white">
              <Phone size={12} /> {BRAND.phone}
            </a>
          </span>
        </div>
      </div>

      {/* ── 헤더 ── */}
      <header className="sticky top-0 z-30 bg-cream/90 backdrop-blur-md border-b border-blush-100">
        <div className="max-w-6xl mx-auto px-4 h-[72px] flex items-center gap-4">
          <Link to="/home" className="flex items-center gap-2.5 shrink-0">
            <motion.span
              animate={reduce ? undefined : { rotate: [0, 8, -6, 0] }}
              transition={{ duration: 7, repeat: Infinity, ease: 'easeInOut' }}
            >
              <Flower2 className="text-blush-500" size={28} />
            </motion.span>
            <span className="leading-none">
              <span className="block font-serif text-[20px] font-bold text-blush-900 tracking-tight">Montvale</span>
              <span className="block font-display text-[12px] tracking-[0.35em] text-sage-600 uppercase -mt-0.5">Florist</span>
            </span>
          </Link>

          <form onSubmit={doSearch} className="flex-1 max-w-md hidden md:flex items-center bg-white border border-blush-100 rounded-full px-4 py-2.5 shadow-soft">
            <Search size={16} className="text-blush-400" />
            <input value={q} onChange={e => setQ(e.target.value)} placeholder={t('common.searchPlaceholder')}
              className="flex-1 bg-transparent ml-2 text-sm outline-none placeholder:text-blush-300" />
          </form>

          <div className="flex items-center gap-1.5 sm:gap-3 ml-auto">
            <LanguageSwitcher variant="shop" />
            <Link to="/" className="hidden sm:flex items-center gap-1 text-sm text-sage-700 hover:text-blush-500 transition-colors">
              <MapPin size={15} /> {zip ? `${zip}` : t('shop.header.zip')}
            </Link>
            <Link to="/wishlist" aria-label={t('shop.header.wishlist')} className="p-1.5 text-blush-700 hover:text-blush-500 transition-colors"><Heart size={20} /></Link>
            <Link to="/cart" className="relative p-1.5 text-blush-700 hover:text-blush-500 transition-colors">
              <ShoppingCart size={20} />
              <AnimatePresence>
                {cartCount > 0 && (
                  <motion.span
                    key={cartCount}
                    initial={reduce ? false : { scale: 0 }} animate={{ scale: 1 }} exit={{ scale: 0 }}
                    className="absolute -top-1 -right-1 bg-blush-500 text-white text-[10px] rounded-full min-w-[18px] h-[18px] px-1 flex items-center justify-center">
                    {cartCount}
                  </motion.span>
                )}
              </AnimatePresence>
            </Link>
            <Link to={custToken ? '/mypage' : '/account'} className="p-1.5 text-blush-700 hover:text-blush-500 transition-colors"><User size={20} /></Link>
          </div>
        </div>

        {/* ── 내비게이션 ── */}
        <nav className="border-t border-blush-50 bg-white/60">
          <div className="max-w-6xl mx-auto px-4 h-11 flex items-center gap-7 text-[13px] overflow-x-auto thin-scroll">
            {NAV.map(n => {
              const active = loc.pathname + loc.search === n.to || (n.to === '/home' && loc.pathname === '/home')
              return (
                <Link key={n.to} to={n.to}
                  className={`relative whitespace-nowrap py-1 transition-colors ${
                    n.accent ? 'text-sage-700 font-medium' : 'text-[#6b5258] hover:text-blush-500'
                  } ${active ? 'text-blush-600' : ''}`}>
                  {t(`shop.nav.${n.key}`)}
                  {active && <motion.span layoutId="nav-underline" className="absolute -bottom-[1px] left-0 right-0 h-[2px] bg-blush-500 rounded-full" />}
                </Link>
              )
            })}
          </div>
        </nav>
      </header>

      <main className="flex-1">
        <Outlet />
      </main>

      {/* ── 푸터 ── */}
      <footer className="mt-16 bg-sage-800 text-cream/85">
        <div className="botanical-divider py-6 opacity-50"><Flower2 size={16} /></div>
        <div className="max-w-6xl mx-auto px-4 pb-10 grid md:grid-cols-4 gap-8">
          <div className="md:col-span-1">
            <div className="font-serif text-xl font-bold text-white mb-1">Montvale Florist</div>
            <p className="font-display text-[13px] tracking-[0.3em] uppercase text-sage-300 mb-3">{t('shop.footer.since', { year: BRAND.founded })}</p>
            <p className="text-[13px] leading-relaxed text-cream/70">{BRAND.tagline}</p>
            <SocialLinks size={18} className="mt-4 text-cream/80" iconClass="hover:text-white" />
          </div>

          <div>
            <div className="font-semibold text-white mb-3 text-sm">{t('shop.footer.visitUs')}</div>
            <p className="text-[13px] flex items-start gap-1.5 text-cream/75 mb-1.5"><MapPin size={14} className="mt-0.5 shrink-0" /> {BRAND.address}</p>
            <a href={`tel:${BRAND.phoneTel}`} className="text-[13px] flex items-center gap-1.5 text-cream/75 hover:text-white mb-1.5"><Phone size={14} /> {BRAND.phone}</a>
            <p className="text-[13px] text-cream/60">{BRAND.email}</p>
          </div>

          <div>
            <div className="font-semibold text-white mb-3 text-sm flex items-center gap-1.5"><Clock size={14} /> {t('shop.footer.hours')}</div>
            {BRAND.hours.map(h => (
              <div key={h.day} className="text-[13px] text-cream/75 mb-1">
                <span className="inline-block w-20">{h.day}</span> {h.open}
              </div>
            ))}
          </div>

          <div>
            <div className="font-semibold text-white mb-3 text-sm">{t('shop.footer.customerCare')}</div>
            <Link to="/cs" className="flex items-center gap-1 text-[13px] text-cream/75 hover:text-white mb-1.5"><ChevronRight size={13} /> {t('shop.footer.contactAiHelp')}</Link>
            <Link to="/orders" className="flex items-center gap-1 text-[13px] text-cream/75 hover:text-white mb-1.5"><ChevronRight size={13} /> {t('shop.footer.orderStatus')}</Link>
            <Link to="/subscription" className="flex items-center gap-1 text-[13px] text-cream/75 hover:text-white mb-1.5"><ChevronRight size={13} /> {t('shop.footer.subscriptions')}</Link>
            <Link to="/app" className="flex items-center gap-1 text-[13px] text-gold hover:text-white mb-3 font-medium"><ChevronRight size={13} /> {t('shop.footer.getApp')}</Link>
            <div className="text-[11px] text-cream/50 mb-1.5">{t('shop.footer.weAccept')}</div>
            <PaymentBadges items={BRAND.payments} />
          </div>
        </div>
        <div className="border-t border-cream/10">
          <div className="max-w-6xl mx-auto px-4 py-4 flex flex-col sm:flex-row items-center justify-between gap-2 text-[11px] text-cream/50">
            <span>© 2026 Montvale Florist · {BRAND.address}</span>
            <span className="flex flex-wrap gap-3">
              {BRAND.policies.map(p => <span key={p} className="hover:text-cream/80">{p}</span>)}
            </span>
          </div>
        </div>
      </footer>
    </div>
  )
}
