// Page sections for HOS

/* ───────────── Announcement bar (marquee) ───────────── */
function Announcement() {
  const { t } = useLang();
  const messages = [
    t('New · Summer Édition is now online', 'Nouveau · l’Édition Été est en ligne'),
    t('Become a member — early access to drops',  'Devenez membre — accès anticipé aux drops'),
    t('Follow @houseofsheylas',                   'Suivez @houseofsheylas'),
    t('Discover the Summer lookbook',       'Découvrez le lookbook Été'),
  ];
  const row = [...messages, ...messages]; // duplicate for seamless marquee
  return (
    <div className="bg-blush text-deep overflow-hidden">
      <div className="flex animate-marquee whitespace-nowrap py-2.5">
        {row.map((m, i) => (
          <span key={i} className="font-sans text-[11px] tracking-widest-2 uppercase flex items-center gap-6 px-6">
            {m}
            <Diamond />
          </span>
        ))}
      </div>
    </div>
  );
}

/* ───────────── Nav ───────────── */
function SearchOverlay({ onClose }) {
  const { t } = useLang();
  const { siteData } = useSiteData();
  const products = siteData.products;
  const [q, setQ] = useState('');
  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current?.focus();
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  const results = q.trim().length >= 2
    ? products.filter(p => p.name.toLowerCase().includes(q.toLowerCase()) || (p.category || '').toLowerCase().includes(q.toLowerCase())).slice(0, 8)
    : [];

  return (
    <div className="fixed inset-0 z-[90] flex flex-col">
      <div className="absolute inset-0 bg-deep/50 animate-fade-in" onClick={onClose}/>
      <div className="relative z-10 bg-ivory border-b border-deep/10 px-6 md:px-10 py-5 flex items-center gap-4 animate-slide-in-down">
        <I.search className="w-5 h-5 text-deep/50 flex-none"/>
        <input
          ref={inputRef}
          value={q}
          onChange={e => setQ(e.target.value)}
          placeholder={t('Search pieces…','Rechercher des pièces…')}
          className="flex-1 bg-transparent font-serif text-deep text-[22px] outline-none placeholder:text-deep/35"
        />
        <button onClick={onClose} className="text-deep/55 hover:text-rose transition-colors">
          <I.close className="w-5 h-5"/>
        </button>
      </div>
      {results.length > 0 && (
        <div className="relative z-10 bg-ivory max-h-[60vh] overflow-y-auto">
          <ul className="max-w-[1440px] mx-auto px-6 md:px-10 divide-y divide-deep/8">
            {results.map(p => (
              <li key={p.id}>
                <a href={`#product/${p.id}`} onClick={onClose}
                   className="flex items-center gap-5 py-4 hover:bg-blush-2/30 transition-colors -mx-6 px-6 md:-mx-10 md:px-10">
                  <div className="w-12 h-14 bg-blush-2 overflow-hidden flex-none rounded-sm">
                    {p.img && <img src={p.img} alt={p.name} className="w-full h-full object-cover"/>}
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="font-serif text-deep text-[17px] leading-tight truncate">{p.name}</div>
                    <div className="font-sans text-[11px] tracking-wider-2 text-deep/50 capitalize mt-0.5">{p.category}</div>
                  </div>
                  <div className="font-sans text-[14px] text-deep tracking-wider-2 flex-none"><Price amount={p.price} overrides={p.priceOverrides}/></div>
                </a>
              </li>
            ))}
          </ul>
        </div>
      )}
      {q.trim().length >= 2 && results.length === 0 && (
        <div className="relative z-10 bg-ivory px-6 py-8 max-w-[1440px] mx-auto">
          <p className="font-serif text-deep/50 text-[18px]">{t('No results for','Aucun résultat pour')} &ldquo;{q}&rdquo;</p>
        </div>
      )}
    </div>
  );
}

function Nav({ onOpenMenu, route = 'home' }) {
  const cart = useCart();
  const { t } = useLang();
  const [scrolled, setScrolled] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => { window.removeEventListener('scroll', onScroll); };
  }, []);

  // Light (ivory) treatment ONLY while sitting transparently over the dark video hero on home.
  // The real route is passed from App so this stays correct under pathname-based navigation.
  const head = String(route).split('/')[0];
  const overHero = head === 'home' || head === '';
  const light = overHero && !scrolled;
  const ink = light ? 'text-ivory' : 'text-deep';
  const hov = light ? 'hover:text-blush' : 'hover:text-rose';

  return (
    <header
      className={`sticky top-0 z-40 transition-all duration-500
        ${scrolled ? 'bg-ivory/85 backdrop-blur-xl shadow-soft' : 'bg-transparent'}`}
    >
      <div className="max-w-[1440px] mx-auto px-6 md:px-10 grid grid-cols-3 items-center"
           style={{ paddingTop: scrolled ? 14 : 22, paddingBottom: scrolled ? 14 : 22, transition: 'padding .4s ease' }}>
        {/* Left: Menu button */}
        <div className="flex items-center">
          <button onClick={onOpenMenu}
                  className={`group inline-flex items-center gap-3 ${ink} ${hov} transition-colors -ml-1 py-1`}
                  aria-label={t('Open menu','Ouvrir le menu')}>
            <span className="flex flex-col gap-[5px]">
              <span className="block w-6 h-px bg-current transition-transform duration-300 group-hover:translate-x-1"></span>
              <span className="block w-4 h-px bg-current transition-transform duration-300 group-hover:translate-x-2"></span>
            </span>
            <span className="hidden sm:inline font-sans text-[12px] tracking-widest-2 uppercase">
              {t('Menu','Menu')}
            </span>
          </button>
        </div>

        {/* Logo center */}
        <div className="flex justify-center">
          <a href="#home" className="block text-center">
            <span className={`block font-display ${ink} transition-all duration-500 ${scrolled ? 'text-[24px]' : 'text-[30px]'} tracking-[.18em] leading-none`}>HOS</span>
            <span className={`block font-sans ${ink} text-[8px] tracking-widest-2 mt-1 text-center transition-colors duration-500 ${light ? 'opacity-80' : 'opacity-100'}`}>HOUSE&nbsp;OF&nbsp;SHEYLAS</span>
          </a>
        </div>

        {/* Right: icons */}
        <div className="flex items-center justify-end gap-3.5 md:gap-5">
          <CurrencySwitcher tone={light ? 'ivory' : 'deep'} className="hidden sm:inline-flex mr-1"/>
          <LangSwitcher tone={light ? 'ivory' : 'deep'} className="hidden sm:inline-flex mr-1"/>
          <button aria-label={t('Search','Rechercher')} onClick={() => setSearchOpen(true)} className={`${ink} ${hov} transition-colors`}><I.search className="w-[20px] h-[20px]"/></button>
          {searchOpen && <SearchOverlay onClose={() => setSearchOpen(false)}/>}
          <a href="#order" aria-label={t('Track order','Suivi commande')} className={`${ink} ${hov} transition-colors hidden sm:inline-flex`}><I.user className="w-[20px] h-[20px]"/></a>
          <button aria-label={t('Cart','Panier')} onClick={() => cart.setOpen(true)} className={`relative ${ink} ${hov} transition-colors`}>
            <I.bag className="w-[20px] h-[20px]"/>
            {cart.count > 0 && (
              <span className="absolute -top-1.5 -right-2 bg-rose text-ivory text-[10px] font-sans font-medium w-4 h-4 rounded-full flex items-center justify-center animate-scale-in">
                {cart.count}
              </span>
            )}
          </button>
        </div>
      </div>
    </header>
  );
}

/* ───────────── Hero ─────────────
   Cinematic full-bleed video. French editorial: a woman in a flowing gown
   walking through a glass garden pergola. Nav floats over it in ivory.
*/
function Hero() {
  const { t, lang } = useLang();
  const { siteData } = useSiteData();
  const v = HERO_VIDEOS[0];
  // Homepage CMS: read editable hero content (bilingual) with the original copy as fallback.
  const hp = (siteData.homepage && siteData.homepage.hero) || {};
  const hv = (field, en, fr) => {
    const node = hp[field];
    if (node && typeof node === 'object') return node[lang] || node.en || t(en, fr);
    if (typeof node === 'string' && node.trim()) return node;
    return t(en, fr);
  };
  const videoSrc = (typeof hp.videoUrl === 'string' && hp.videoUrl.trim()) ? hp.videoUrl : '/uploads/hero.mp4';
  return (
    <>
      <section id="top" className="relative -mt-[88px] h-[92svh] min-h-[660px] w-full overflow-hidden bg-deep">
        {/* Background video — House of Sheylas brand film (single source, no foreign poster flash) */}
        <video key={videoSrc} className="hero-video" autoPlay muted loop playsInline preload="auto" aria-hidden="true" style={{ background:'#4A2D33' }}>
          <source src={videoSrc} type="video/mp4"/>
        </video>
        <div className="hero-tint"></div>
        <div className="hero-scrim"></div>
        {/* faint film grain */}
        <div className="pointer-events-none absolute inset-0 opacity-[.10] mix-blend-overlay"
             style={{background:'radial-gradient(rgba(255,255,255,.6) 1px, transparent 1px)', backgroundSize:'3px 3px'}}></div>

        {/* Content */}
        <div className="relative h-full max-w-[1440px] mx-auto px-6 md:px-10 flex flex-col">
          {/* Meta row, clearing the nav */}
          <div className="pt-[116px] flex items-start justify-between">
            <div className="hero-rise font-sans text-[10px] tracking-widest-2 uppercase text-ivory/70" style={{animationDelay:'.55s'}}>
              {hv('metaLeft', 'Boutique · Paris · Est. 2025', 'Boutique · Paris · Depuis 2025')}
            </div>
            <div className="hidden md:block hero-rise font-sans text-[10px] tracking-widest-2 uppercase text-ivory/70 [writing-mode:vertical-rl] rotate-180" style={{animationDelay:'.75s'}}>
              {hv('metaRight', 'N°08 · Summer', 'N°08 · Été')}
            </div>
          </div>

          {/* Bottom editorial block */}
          <div className="mt-auto pb-14 md:pb-16 grid lg:grid-cols-12 gap-8 lg:gap-10 items-end">
            <div className="lg:col-span-8 max-w-[820px]">
              <div className="hero-rise" style={{animationDelay:'.15s'}}>
                <Eyebrow tone="ivory">{hv('eyebrow', 'Summer · Édition 2026', 'Édition Été 2026')}</Eyebrow>
              </div>
              <h1 className="hero-rise font-display text-ivory mt-5 leading-[1.02]"
                  style={{fontSize:'clamp(40px, 5vw, 82px)', animationDelay:'.3s', textShadow:'0 2px 40px rgba(36,18,22,0.45)'}}>
                {hv('titleLine', 'Soft elegance', 'Élégance douce')}
                <br/>
                <span className="font-serif font-light italic">{hv('titleAccent', 'for every woman.', 'pour chaque femme.')}</span>
              </h1>
              <p className="hero-rise mt-7 max-w-[470px] font-sans text-[15px] md:text-[16px] leading-[1.75] text-ivory/85" style={{animationDelay:'.5s'}}>
                {hv('description',
                  'A curated edit of feminine pieces — selected to make you feel confident, graceful and unforgettable.',
                  'Une sélection de pièces féminines — choisies pour vous sentir confiante, gracieuse et inoubliable.'
                )}
              </p>
              <div className="hero-cta-row hero-rise mt-9 flex flex-wrap items-center gap-3" style={{animationDelay:'.65s'}}>
                <Button as="a" href={hp.ctaPrimaryHref || '#shop/new'} variant="ivory" size="lg">
                  {hv('ctaPrimaryLabel', 'Shop new collection', 'Voir la collection')} <I.arrowR className="w-4 h-4"/>
                </Button>
                <Button as="a" href={hp.ctaSecondaryHref || '#collections'} variant="ghostLight" size="lg">{hv('ctaSecondaryLabel', 'View lookbook', 'Voir le lookbook')}</Button>
              </div>
            </div>

            {/* Floating featured product — glass card */}
            <div className="hero-feature-card hidden" aria-hidden="true" style={{animationDelay:'.85s'}}>
              <a href="#product/na1" className="group w-[262px] bg-ivory/10 backdrop-blur-md border border-ivory/25 p-3 hover:bg-ivory/[0.16] transition-colors duration-500 rounded-sm">
                <div className="relative overflow-hidden aspect-[4/5] bg-deep/20 rounded-sm">
                  <img src={NEW_ARRIVALS[0].img} alt="Aurelie Silk Slip Dress" className="absolute inset-0 w-full h-full object-cover img-zoom"/>
                  <span className="absolute top-2.5 left-2.5 bg-ivory/90 text-deep text-[9px] tracking-widest-2 uppercase px-2 py-1">{t('Featured','En vedette')}</span>
                </div>
                <div className="pt-3.5 flex items-end justify-between gap-2">
                  <div className="min-w-0">
                    <div className="font-serif text-ivory text-[16px] leading-tight truncate">Aurelie Silk Slip</div>
                    <div className="font-sans text-[12px] text-ivory/70 tracking-wider-2 mt-1.5">$248</div>
                  </div>
                  <span className="w-9 h-9 rounded-full border border-ivory/40 text-ivory flex items-center justify-center group-hover:bg-ivory group-hover:text-deep transition-all duration-500 flex-none">
                    <I.arrowR className="w-4 h-4"/>
                  </span>
                </div>
              </a>
            </div>
          </div>
        </div>

        {/* Scroll cue */}
        <div className="absolute bottom-5 left-1/2 -translate-x-1/2 hidden md:flex flex-col items-center gap-2 z-10 hero-rise" style={{animationDelay:'1s'}}>
          <span className="font-sans text-[9px] tracking-widest-2 uppercase text-ivory/55">{t('Scroll','Défiler')}</span>
          <span className="flex w-5 h-8 rounded-full border border-ivory/40 items-start justify-center pt-1.5">
            <span className="scroll-dot block w-1 h-1.5 rounded-full bg-ivory/90"></span>
          </span>
        </div>
      </section>

      {/* Press strip — light band easing from the dark hero */}
      <div className="bg-ivory border-b border-deep/10">
        <div className="max-w-[1440px] mx-auto px-6 md:px-10 py-5 flex flex-wrap items-center justify-center gap-x-8 md:gap-x-12 gap-y-3">
          <span className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/50 w-full md:w-auto text-center md:text-left">{t('As featured in', 'Vu dans')}</span>
          {PRESS.slice(0, 5).map(p => (
            <span key={p.name} className="font-display text-deep/65 hover:text-rose transition-colors"
                  style={{fontSize: p.size || 18, letterSpacing: p.tracking || '.12em', fontStyle: p.italic ? 'italic' : 'normal'}}>{p.name}</span>
          ))}
        </div>
      </div>
    </>
  );
}

const PRESS = [
  { name: 'VOGUE',           size: 18, tracking: '.32em' },
  { name: 'ELLE',            size: 22, tracking: '.36em' },
  { name: "HARPER'S BAZAAR", size: 15, tracking: '.22em' },
  { name: 'Vanity Fair',     size: 17, italic: true, tracking: '.06em' },
  { name: 'PORTER',          size: 18, tracking: '.32em' },
];

function Sparkle({ className = '', ...rest }) {
  return (
    <svg viewBox="0 0 24 24" className={className} fill="currentColor" {...rest}>
      <path d="M12 0 L13.6 9 L24 12 L13.6 15 L12 24 L10.4 15 L0 12 L10.4 9 Z"/>
    </svg>
  );
}

/* ClipWord — animated word reveal via clip-path mask + translate */
function ClipWord({ children, delay = 0, className = '', style = {}, as: As = 'span' }) {
  const ref = useRef(null);
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(([e]) => {
      if (e.isIntersecting) {
        setTimeout(() => setShown(true), delay);
        io.unobserve(el);
      }
    }, { threshold: .2 });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return (
    <As ref={ref} className={`inline-block overflow-hidden align-baseline ${className}`} style={style}>
      <span className="inline-block transition-transform duration-[1100ms]"
            style={{
              transform: shown ? 'translateY(0)' : 'translateY(110%)',
              transitionTimingFunction: 'cubic-bezier(.2,.65,.2,1)'
            }}>
        {children}
      </span>
    </As>
  );
}

/* ───────────── Categories ───────────── */
const CAT_FR = { dresses:'Robes', sets:'Ensembles', tops:'Hauts', accessories:'Accessoires', bottoms:'Bas' };
// Horizontal scroll carousel with arrow controls — reused by Categories / arrivals / best sellers.
function Carousel({ children, itemWidth = 'w-[78%] sm:w-[300px]' }) {
  const trackRef = useRef(null);
  const scroll = (dir) => {
    const el = trackRef.current;
    if (!el) return;
    el.scrollBy({ left: dir * (el.clientWidth * 0.85), behavior: 'smooth' });
  };
  return (
    <div className="relative">
      <button type="button" aria-label="Previous" onClick={() => scroll(-1)}
        className="hidden md:flex absolute -left-4 top-[40%] z-10 w-11 h-11 rounded-full bg-ivory shadow-card items-center justify-center text-deep hover:bg-deep hover:text-ivory transition-colors">
        <I.arrowR className="w-4 h-4 rotate-180"/>
      </button>
      <button type="button" aria-label="Next" onClick={() => scroll(1)}
        className="hidden md:flex absolute -right-4 top-[40%] z-10 w-11 h-11 rounded-full bg-ivory shadow-card items-center justify-center text-deep hover:bg-deep hover:text-ivory transition-colors">
        <I.arrowR className="w-4 h-4"/>
      </button>
      <div ref={trackRef} className="flex gap-5 md:gap-7 overflow-x-auto snap-x snap-mandatory scroll-smooth pb-4 no-scrollbar">
        {React.Children.map(children, (child) => (
          <div className={`snap-start shrink-0 ${itemWidth}`}>{child}</div>
        ))}
      </div>
    </div>
  );
}

// Read an editable homepage section heading (bilingual) with a fallback.
function homepageSectionGetter(siteData, lang, t) {
  const sec = (siteData.homepage && siteData.homepage.sections) || {};
  return (field, en, fr) => {
    const n = sec[field];
    if (n && typeof n === 'object') return n[lang] || n.en || t(en, fr);
    return (typeof n === 'string' && n.trim()) ? n : t(en, fr);
  };
}

function Categories() {
  const { t, lang } = useLang();
  const { siteData } = useSiteData();
  const sv = homepageSectionGetter(siteData, lang, t);
  const categories = (siteData.categories || []).filter((c) => c && c.name);
  if (!categories.length) return null;
  return (
    <section className="bg-ivory relative grain">
      <div className="relative max-w-[1440px] mx-auto px-6 md:px-10 py-16 md:py-24">
        <div className="flex flex-col items-center text-center mb-12">
          <div className="reveal"><Eyebrow>{sv('categoriesEyebrow', 'Curated for her', 'Sélection pour elle')}</Eyebrow></div>
          <h2 className="reveal reveal-delay-1 font-display text-deep mt-5 leading-[0.95]" style={{fontSize:'clamp(34px, 4.4vw, 64px)'}}>
            {sv('categoriesTitle', 'Shop by category', 'Par catégorie')}
          </h2>
          <p className="reveal reveal-delay-2 mt-5 max-w-[520px] font-sans text-[15px] text-deep/65 leading-relaxed">
            {t(
              'From everyday softness to occasion-ready silhouettes — find the piece your wardrobe is missing.',
              'De la douceur du quotidien aux silhouettes pour les grandes occasions — trouvez la pièce qui manque à votre vestiaire.'
            )}
          </p>
        </div>

        <Carousel itemWidth="w-[62%] sm:w-[280px]">
          {categories.map((c) => (
            <a key={c.id} href={`#shop/${c.id}`} className="group block">
              <div className="relative overflow-hidden aspect-[3/4] bg-blush rounded-sm">
                {c.img
                  ? <img src={c.img} alt={c.name} className="absolute inset-0 w-full h-full object-cover img-zoom"/>
                  : <div className="absolute inset-0 bg-gradient-to-br from-blush to-champagne"/>}
                <div className="absolute inset-0 bg-gradient-to-t from-deep/55 via-deep/0 to-transparent"/>
                <div className="absolute inset-x-5 bottom-5 flex items-end justify-between text-ivory">
                  <div>
                    <h3 className="font-display text-[28px] md:text-[34px] leading-none tracking-wide">{lang==='fr' ? (CAT_FR[c.id] || c.name) : c.name}</h3>
                    <div className="font-sans text-[11px] tracking-widest-2 uppercase opacity-80 mt-2">{String(c.count || '').replace('pieces', lang==='fr' ? 'pièces' : 'pieces')}</div>
                  </div>
                  <span className="w-10 h-10 rounded-full bg-ivory/15 backdrop-blur-sm border border-ivory/30 flex items-center justify-center group-hover:bg-ivory group-hover:text-deep transition-all duration-500">
                    <I.arrowR className="w-4 h-4"/>
                  </span>
                </div>
              </div>
            </a>
          ))}
        </Carousel>
      </div>
    </section>
  );
}

/* ───────────── New arrivals ───────────── */
// Products flagged "New" (by badge or the API's isNew). Capped to 10 for the homepage.
function selectNew(products = []) {
  const newish = products.filter((p) => /new|just|nouvea|arriv/i.test(String(p.badge || p.tag || '')) || p.isNew);
  return (newish.length ? newish : products).slice(0, 10);
}

function NewArrivals() {
  const { t, lang } = useLang();
  const { siteData } = useSiteData();
  const sv = homepageSectionGetter(siteData, lang, t);
  const items = selectNew(siteData.products || []);
  if (!items.length) return null;
  return (
    <section className="bg-champagne/40 relative">
      <div className="max-w-[1440px] mx-auto px-6 md:px-10 py-16 md:py-24">
        <div className="flex flex-col md:flex-row md:items-end md:justify-between gap-6 mb-12">
          <div>
            <div className="reveal"><Eyebrow>{sv('newEyebrow', 'Just landed', 'Tout juste arrivé')}</Eyebrow></div>
            <h2 className="reveal reveal-delay-1 font-display text-deep mt-5 leading-[0.95]" style={{fontSize:'clamp(34px, 4.4vw, 64px)'}}>
              {sv('newTitle', 'New arrivals', 'Nouveautés')}
            </h2>
          </div>
          <a href="#shop/new" className="reveal reveal-delay-2 ulink font-sans text-[12px] tracking-widest-2 uppercase text-deep self-start md:self-end">
            {t('View all →', 'Voir tout →')}
          </a>
        </div>

        <Carousel>
          {items.map((p, i) => <ProductCard key={p.id} p={p} idx={i} reveal={false}/>)}
        </Carousel>
      </div>
    </section>
  );
}

/* ───────────── Brand story ───────────── */
// Read an editable homepage group field (bilingual {en,fr} or plain string) with a fallback.
function homepageGroupGetter(siteData, lang, t, group) {
  const g = (siteData.homepage && siteData.homepage[group]) || {};
  return {
    val: (field, en, fr) => {
      const n = g[field];
      if (n && typeof n === 'object') return n[lang] || n.en || t(en, fr);
      return (typeof n === 'string' && n.trim()) ? n : t(en, fr);
    },
    raw: (field, fallback) => {
      const n = g[field];
      return (typeof n === 'string' && n.trim()) ? n : fallback;
    },
  };
}

function BrandStory() {
  const { t, lang } = useLang();
  const { siteData } = useSiteData();
  const s = homepageGroupGetter(siteData, lang, t, 'story');
  const imgPrimary = s.raw('imagePrimary', STORY_IMG_1);
  const imgSecondary = s.raw('imageSecondary', STORY_IMG_2);
  return (
    <section className="bg-rose text-ivory relative overflow-hidden">
      {/* Texture */}
      <div className="pointer-events-none absolute inset-0 opacity-[.07]"
           style={{background:'radial-gradient(rgba(255,255,255,.6) 1px, transparent 1px)', backgroundSize:'4px 4px'}}/>
      <div className="pointer-events-none absolute -right-32 top-1/2 -translate-y-1/2 w-[700px] h-[700px] rounded-full"
           style={{background:'radial-gradient(closest-side, rgba(255,248,245,0.12), transparent 70%)'}}/>

      <div className="relative max-w-[1440px] mx-auto px-6 md:px-10 py-16 md:py-24 grid lg:grid-cols-12 gap-12 items-center">
        {/* Image collage */}
        <div className="lg:col-span-5 relative">
          <div className="reveal relative aspect-[4/5] bg-blush/20 max-w-[460px] overflow-hidden shadow-card rounded-sm">
            <img src={imgPrimary} alt="" className="absolute inset-0 w-full h-full object-cover"/>
          </div>
          <div className="reveal reveal-delay-2 hidden md:block absolute -right-4 -bottom-10 w-[200px] aspect-[3/4] overflow-hidden shadow-card rounded-sm">
            <img src={imgSecondary} alt="" className="absolute inset-0 w-full h-full object-cover"/>
          </div>
        </div>

        {/* Copy */}
        <div className="lg:col-span-7 lg:pl-10">
          <div className="reveal"><Eyebrow tone="ivory">{s.val('eyebrow', 'Our story', 'Notre histoire')}</Eyebrow></div>
          <h2 className="reveal reveal-delay-1 font-display mt-6 leading-[0.95]" style={{fontSize:'clamp(34px, 4.4vw, 64px)'}}>
            {s.val('titleLine1', 'For women who love', 'Pour les femmes qui aiment')}
            <br/><em className="font-serif font-light" style={{fontSize: '0.92em'}}>{s.val('titleLine2', 'elegance, confidence,', 'l’élégance, la confiance,')}</em>
            <br/>{s.val('titleLine3', 'and timeless femininity.', 'et la féminité intemporelle.')}
          </h2>
          <p className="reveal reveal-delay-2 mt-7 max-w-[520px] font-sans text-[16px] leading-[1.75] text-ivory/85">
            {s.val('body',
              'House of Sheylas is a curated boutique, bringing together feminine, elevated pieces — chosen with care for the women who wear them.',
              'House of Sheylas est une boutique qui rassemble des pièces féminines et raffinées — choisies avec soin pour les femmes qui les portent.'
            )}
          </p>
          <div className="reveal reveal-delay-3 mt-9 grid grid-cols-3 gap-6 max-w-[520px]">
            {[
              [t('Curated','Sélection'),       t('Hand-picked pieces', 'Pièces choisies')],
              [t('Edit','Édit'),               t('Refined & feminine', 'Raffinées & féminines')],
              [t('For her','Pour elle'),       t('Women who dress for themselves','Pour les femmes qui s’habillent pour elles')],
            ].map(([k,v]) => (
              <div key={k} className="border-l border-ivory/25 pl-4">
                <div className="font-display text-[24px] leading-tight">{k}</div>
                <div className="font-sans text-[11px] tracking-widest-2 uppercase text-ivory/60 mt-2">{v}</div>
              </div>
            ))}
          </div>
          <div className="reveal reveal-delay-4 mt-10">
            <Button as="a" href="#about" variant="ivory">{t('Discover the boutique', 'Découvrir la boutique')} <I.arrowR className="w-4 h-4"/></Button>
          </div>
        </div>
      </div>
    </section>
  );
}

/* ───────────── Best sellers ───────────── */
// Best sellers = ONLY products the admin badges as best-seller / hot / most-loved /
// restocked. Featured ("Hero") products are intentionally excluded so a New-badged hero
// piece doesn't leak in here. Capped to 10.
function selectBest(products = []) {
  return products
    .filter((p) => /best|most|loved|restock|réassort|seller|hot/i.test(String(p.badge || '')))
    .slice(0, 10);
}

function BestSellers() {
  const cart = useCart();
  const { t, lang } = useLang();
  const { siteData } = useSiteData();
  const sv = homepageSectionGetter(siteData, lang, t);
  const items = selectBest(siteData.products || []);
  if (!items.length) return null;
  return (
    <section className="bg-ivory relative">
      <div className="max-w-[1440px] mx-auto px-6 md:px-10 py-16 md:py-24">
        <div className="flex flex-col items-center text-center mb-12">
          <div className="reveal"><Eyebrow>{sv('bestEyebrow', 'Always in rotation', 'Toujours en rotation')}</Eyebrow></div>
          <h2 className="reveal reveal-delay-1 font-display text-deep mt-5 leading-[0.95]" style={{fontSize:'clamp(34px, 4.4vw, 64px)'}}>
            {sv('bestTitle', 'Best sellers', 'Meilleures ventes')}
          </h2>
          <p className="reveal reveal-delay-2 mt-5 max-w-[520px] font-sans text-[15px] text-deep/65 leading-relaxed">
            {t(
              'The pieces our community returns for — restocked, re-loved, and rarely in stock for long.',
              'Les pièces que notre communauté redemande — réassorties, ré-adorées, et rarement en stock longtemps.'
            )}
          </p>
        </div>

        <Carousel>
          {items.map((p, i) => (
            <article key={p.id} className="group relative">
              <a href={`#product/${p.id}`} className="relative overflow-hidden bg-blush-2 aspect-[3/4] rounded-sm block">
                <img src={p.img} alt={p.name} className="absolute inset-0 w-full h-full object-cover img-zoom"/>
                <span className="absolute top-3 left-3 bg-deep text-ivory text-[10px] tracking-widest-2 uppercase px-3 py-1.5">
                  {lang === 'fr' ? (TAG_FR[p.badge] || p.badge || 'Best-seller') : (p.badge || 'Best seller')}
                </span>
                <button
                  onClick={(e) => { e.preventDefault(); e.stopPropagation(); cart.toggleWish(p.id); }}
                  className={`absolute top-3 right-3 w-9 h-9 rounded-full flex items-center justify-center transition-all duration-300
                    ${cart.wishlist.has(p.id) ? 'bg-rose text-ivory' : 'bg-ivory/90 text-deep hover:bg-ivory'}`}
                >
                  <I.heart filled={cart.wishlist.has(p.id)} className="w-[18px] h-[18px]"/>
                </button>
                <div className="absolute inset-x-3 bottom-3 translate-y-[140%] group-hover:translate-y-0 transition-transform duration-500">
                  <button
                    onClick={(e) => { e.preventDefault(); e.stopPropagation(); cart.add({id:p.id, name:p.name, price:p.price, overrides:p.priceOverrides, img:p.img}); }}
                    className="w-full bg-deep text-ivory font-sans uppercase tracking-widest-2 text-[11px] py-3.5 hover:bg-rose transition-colors">
                    + {t('Add to bag', 'Ajouter au panier')}
                  </button>
                </div>
              </a>
              <div className="pt-4">
                <h3 className="font-serif text-[20px] leading-tight text-deep">
                  <a href={`#product/${p.id}`} className="hover:text-rose transition-colors">{p.name}</a>
                </h3>
                <div className="mt-1.5 flex items-center justify-between">
                  <span className="font-sans text-[13px] text-deep-2 tracking-wider-2"><Price amount={p.price} overrides={p.priceOverrides}/></span>
                  <div className="flex items-center gap-1 text-rose">
                    {[0,1,2,3,4].map(i => <I.star key={i} className="w-[12px] h-[12px]"/>)}
                    <span className="ml-1.5 font-sans text-[11px] text-deep/55 tracking-wider-2">({p.reviews})</span>
                  </div>
                </div>
              </div>
            </article>
          ))}
        </Carousel>
      </div>
    </section>
  );
}

/* ───────────── Instagram / lifestyle ───────────── */
function Instagram() {
  const { t, lang } = useLang();
  const { siteData } = useSiteData();
  const ig = homepageGroupGetter(siteData, lang, t, 'instagram');
  const cmsImages = (siteData.homepage && siteData.homepage.instagram && Array.isArray(siteData.homepage.instagram.images)) ? siteData.homepage.instagram.images : [];
  const images = [0, 1, 2, 3].map((i) => (cmsImages[i] && cmsImages[i].trim()) ? cmsImages[i] : INSTAGRAM[i]);
  const settings = siteData.settings || {};
  const igUrl = ig.raw('url', settings.instagramUrl || '#') || '#';
  return (
    <section className="bg-champagne/40">
      <div className="max-w-[1440px] mx-auto px-6 md:px-10 py-16 md:py-24">
        <div className="flex flex-col items-center text-center mb-12">
          <div className="reveal"><Eyebrow>{ig.raw('handle', '@houseofsheylas')}</Eyebrow></div>
          <h2 className="reveal reveal-delay-1 font-display text-deep mt-5 leading-[0.95]" style={{fontSize:'clamp(34px, 4.4vw, 64px)'}}>
            {ig.val('title', 'From our community', 'Notre communauté')}
          </h2>
          <p className="reveal reveal-delay-2 mt-5 max-w-[520px] font-sans text-[15px] text-deep/65 leading-relaxed">
            {ig.val('subtitle', 'Tag #houseofsheylas to be featured.', 'Tagguez #houseofsheylas pour être à l’honneur.')}
          </p>
        </div>

        <div className="grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-5">
          {images.map((src, i) => (
            <a key={i} href={igUrl} target={igUrl !== '#' ? '_blank' : undefined} rel="noopener noreferrer" className={`reveal reveal-delay-${i+1} group relative aspect-square overflow-hidden bg-blush-2 rounded-sm block`}>
              <img src={src} alt="" className="absolute inset-0 w-full h-full object-cover img-zoom"/>
              <div className="absolute inset-0 bg-deep/0 group-hover:bg-deep/40 transition-colors duration-500 flex items-center justify-center">
                <I.insta className="w-7 h-7 text-ivory opacity-0 group-hover:opacity-100 transition-opacity duration-500"/>
              </div>
            </a>
          ))}
        </div>

        <div className="text-center mt-12">
          <a href={igUrl} target={igUrl !== '#' ? '_blank' : undefined} rel="noopener noreferrer" className="ulink font-sans text-[12px] tracking-widest-2 uppercase text-deep">
            {ig.val('ctaLabel', 'Follow us on Instagram →', 'Suivez-nous sur Instagram →')}
          </a>
        </div>
      </div>
    </section>
  );
}

/* ───────────── Newsletter ───────────── */
function Newsletter() {
  const { t } = useLang();
  const [email, setEmail] = useState('');
  const [state, setState] = useState('idle'); // idle | loading | success | error
  const [touched, setTouched] = useState(false);

  const valid = /^\S+@\S+\.\S+$/.test(email);

  const onSubmit = async (e) => {
    e.preventDefault();
    setTouched(true);
    if (!valid) return setState('error');
    setState('loading');
    try {
      const res  = await fetch('/api/newsletter', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email }),
      });
      const data = await res.json();
      if (data.ok) {
        setState('success');
      } else if (data.error === 'already_subscribed') {
        setState('success'); // treat existing subscriber as success
      } else {
        setState('error');
      }
    } catch {
      setState('error');
    }
  };

  return (
    <section className="bg-deep text-ivory relative overflow-hidden">
      {/* Decorative motifs */}
      <div className="pointer-events-none absolute inset-0 opacity-[.06]"
           style={{background:'radial-gradient(rgba(255,248,245,.7) 1px, transparent 1px)', backgroundSize:'4px 4px'}}/>
      <div className="pointer-events-none absolute -left-32 -top-32 w-[460px] h-[460px] rounded-full"
           style={{background:'radial-gradient(closest-side, rgba(184,106,120,0.55), transparent 70%)'}}/>
      <div className="pointer-events-none absolute -right-32 -bottom-32 w-[460px] h-[460px] rounded-full"
           style={{background:'radial-gradient(closest-side, rgba(246,214,218,0.25), transparent 70%)'}}/>

      <div className="relative max-w-[860px] mx-auto px-6 md:px-10 py-16 md:py-24 text-center">
        <div className="reveal flex justify-center">
          <Diamond size={14}/>
        </div>
        <div className="reveal reveal-delay-1 mt-5"><Eyebrow tone="ivory">{t('Become a member', 'Devenir membre')}</Eyebrow></div>
        <h2 className="reveal reveal-delay-2 font-display mt-5 leading-[0.95]" style={{fontSize:'clamp(38px, 5vw, 76px)'}}>
          {t('Join', 'Rejoignez')} <em className="font-serif font-light italic">{t('us','-nous')}</em>
        </h2>
        <p className="reveal reveal-delay-3 mt-6 max-w-[520px] mx-auto font-sans text-[15px] text-ivory/75 leading-relaxed">
          {t(
            'Get early access to new drops, private sales, and styling inspiration delivered with care to your inbox.',
            'Accès anticipé aux nouvelles collections, ventes privées et inspirations de style — livré dans votre boîte mail avec soin.'
          )}
        </p>

        <form onSubmit={onSubmit} className="reveal reveal-delay-4 mt-12 max-w-[520px] mx-auto">
          {state !== 'success' ? (
            <>
              <div className={`flex items-center border-b transition-colors duration-300
                ${touched && !valid ? 'border-rose-2' : 'border-ivory/30 focus-within:border-ivory'}`}>
                <input
                  type="email"
                  value={email}
                  onChange={e => { setEmail(e.target.value); if (state==='error') setState('idle'); }}
                  placeholder={t('Enter your email address', 'Votre adresse email')}
                  className="lux-input"
                  style={{ color: '#FFF8F5', borderBottom: 'none' }}
                  aria-label={t('Email','Email')}
                  disabled={state==='loading'}
                />
                <button
                  type="submit"
                  disabled={state==='loading'}
                  className="font-sans uppercase tracking-widest-2 text-[12px] py-3 px-1 text-ivory hover:text-blush transition-colors disabled:opacity-40 inline-flex items-center gap-2 whitespace-nowrap"
                >
                  {state === 'loading' ? t('Sending…','Envoi…') : <>{t('Subscribe','S’inscrire')} <I.arrowR className="w-4 h-4"/></>}
                </button>
              </div>
              {touched && !valid && (
                <div className="mt-3 text-left font-sans text-[12px] text-blush animate-fade-in">{t('Please enter a valid email.','Veuillez saisir un email valide.')}</div>
              )}
              <p className="mt-6 font-sans text-[11px] tracking-wider-2 text-ivory/50">
                {t(
                  'By subscribing you agree to our privacy policy. Unsubscribe any time.',
                  'En vous inscrivant, vous acceptez notre politique de confidentialité. Désinscription à tout moment.'
                )}
              </p>
            </>
          ) : (
            <div className="animate-scale-in flex flex-col items-center py-4">
              <div className="w-14 h-14 rounded-full bg-rose flex items-center justify-center mb-5">
                <I.check className="w-7 h-7 text-ivory"/>
              </div>
              <div className="font-display text-[36px] leading-tight">{t('Welcome home.','Bienvenue chez vous.')}</div>
              <p className="font-sans text-[14px] text-ivory/70 mt-3 max-w-[400px]">
                {t('A 10% welcome code is on its way to','Un code de bienvenue de 10 % arrive bientôt à')} <span className="text-ivory">{email}</span>. {t('See you in your inbox.','À très vite dans votre boîte mail.')}
              </p>
            </div>
          )}
        </form>
      </div>
    </section>
  );
}

/* ───────────── Footer ───────────── */
function Footer() {
  const { t } = useLang();
  const { siteData } = useSiteData();
  const s = (siteData && siteData.settings) || SITE_SETTINGS;
  const socials = [
    [I.insta, s.instagramUrl],
    [I.tiktok, s.tiktokUrl],
    [I.facebook, s.facebookUrl],
  ].filter(([, href]) => href && String(href).trim());
  const cols = [
    {
      title: t('Shop', 'Boutique'),
      items: [
        [t('New In', 'Nouveautés'), '#shop/new'],
        [t('Dresses', 'Robes'), '#shop/dresses'],
        [t('Sets', 'Ensembles'), '#shop/sets'],
        [t('Tops', 'Hauts'), '#shop/tops'],
        [t('Accessories', 'Accessoires'), '#shop/accessories'],
        [t('Best Sellers', 'Meilleures ventes'), '#shop/bestsellers'],
      ],
    },
    {
      title: t('Care', 'Service'),
      items: SERVICES.map((service) => [service.title, service.href]),
    },
    {
      title: t('Boutique', 'La boutique'),
      items: [
        [t('Our Story', 'Notre histoire'), '#about'],
        [t('Collections', 'Collections'), '#collections'],
        [t('Contact', 'Contact'), '#contact'],
        [t('Admin', 'Admin'), '#admin'],
      ],
    },
  ];
  return (
    <footer className="bg-ivory text-deep relative">
      <div className="max-w-[1440px] mx-auto px-6 md:px-10 pt-16 pb-8">
        <div className="grid lg:grid-cols-12 gap-10">
          <div className="lg:col-span-4">
            <Logo size="lg" tone="deep" mark={false} />
            <div className="mt-4 font-sans text-[11px] tracking-widest-2 uppercase text-deep/70">
              {s.brandTagline || 'House of Sheylas'}
            </div>
            <p className="mt-5 max-w-[320px] font-sans text-[14px] leading-relaxed text-deep/70">
              {s.tagline}
            </p>
            <div className="mt-6 flex items-center gap-4 text-deep">
              {socials.map(([Icon, href], index) => (
                <a
                  key={index}
                  href={href}
                  target="_blank" rel="noopener noreferrer"
                  aria-label="social"
                  className="w-9 h-9 rounded-full border border-deep/15 flex items-center justify-center hover:bg-rose hover:text-ivory hover:border-rose transition-all"
                >
                  <Icon className="w-[16px] h-[16px]" />
                </a>
              ))}
            </div>
            <div className="mt-5">
              <LangSwitcher />
            </div>
          </div>

          <div className="lg:col-span-8 grid grid-cols-2 md:grid-cols-3 gap-8">
            {cols.map((column) => (
              <div key={column.title}>
                <h4 className="font-sans text-[11px] tracking-widest-2 uppercase text-deep/60 mb-4">
                  {column.title}
                </h4>
                <ul className="space-y-2.5">
                  {column.items.map(([label, href]) => (
                    <li key={`${column.title}-${label}`}>
                      <a href={href} className="font-serif text-[17px] text-deep hover:text-rose transition-colors">
                        {label}
                      </a>
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        </div>

        <div aria-hidden="true" className="select-none mt-12 mb-8 text-center">
          <span className="font-display text-rose/30 leading-none" style={{ fontSize: 'clamp(80px, 14vw, 200px)', letterSpacing: '.08em' }}>
            {s.brandMark || s.brandName || 'HOS'}
          </span>
        </div>

        <div className="flex flex-col md:flex-row items-center justify-between gap-4 pt-6 border-t border-deep/10">
          <div className="font-sans text-[11px] tracking-wider-2 text-deep/55">
            {SITE_SETTINGS.copyright}
          </div>
          <div className="flex items-center gap-3 opacity-70">
            {['VISA', 'MC', 'AMEX', 'PAYPAL', 'APPLE'].map((provider) => (
              <span key={provider} className="font-sans text-[10px] tracking-widest-2 text-deep/60 border border-deep/15 rounded-sm px-2 py-1">
                {provider}
              </span>
            ))}
          </div>
          <div className="flex items-center gap-5 font-sans text-[11px] tracking-wider-2 text-deep/55">
            <a href="#" className="hover:text-rose">{t('Privacy', 'Confidentialité')}</a>
            <a href="#" className="hover:text-rose">{t('Terms', 'Conditions')}</a>
            <a href="#" className="hover:text-rose">{t('Cookies', 'Cookies')}</a>
            <a href="#admin" className="hover:text-rose opacity-60 hover:opacity-100" title="Admin console">
              {t('Admin', 'Admin')}
            </a>
          </div>
        </div>
      </div>
    </footer>
  );
}

/* ───────────── Cart Drawer ───────────── */
/* ───────────── Checkout Drawer ───────────── */
function CheckoutDrawer({ onClose }) {
  const cart = useCart();
  const { t } = useLang();
  const { currency, base, rates, priceOf, fmtRaw } = useCurrency();
  // Subtotal in the visitor's currency, honouring any per-zone pinned prices per item.
  const cartSubtotal = cart.items.reduce((s, it) => s + priceOf(it.price, it.overrides) * it.qty, 0);
  const [step, setStep]         = useState('form'); // form | success | error
  const [loading, setLoading]   = useState(false);
  const [orderNumber, setOrderNumber] = useState('');
  const [errorMsg, setErrorMsg] = useState('');
  const [form, setForm] = useState({ name:'', email:'', phone:'', country:'FR', city:'', address:'', notes:'' });
  const [touched, setTouched]   = useState({});

  const set  = (k, v) => setForm(f => ({...f, [k]: v}));
  const blur = (k)    => setTouched(t => ({...t, [k]: true}));

  const valid = {
    name:    form.name.trim().length >= 2,
    email:   /^\S+@\S+\.\S+$/.test(form.email),
    phone:   form.phone.trim().length >= 6,
    city:    form.city.trim().length >= 2,
    address: form.address.trim().length >= 5,
  };
  const allValid = Object.values(valid).every(Boolean);
  const isCOD = form.country === 'TN';

  const submit = async (e) => {
    e.preventDefault();
    setTouched({ name:true, email:true, phone:true, city:true, address:true });
    if (!allValid) return;
    setLoading(true);
    try {
      // Best-effort bot-protection token (null if reCAPTCHA isn't available — never blocks).
      const recaptchaToken = (typeof window !== 'undefined' && window.getRecaptchaToken)
        ? await window.getRecaptchaToken('checkout') : null;
      const res = await fetch('/api/orders', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          currency,
          recaptchaToken,
          items: cart.items.map(it => ({ id:it.id, name:it.name, price: Math.round(effectivePrice(it.price, it.overrides, { currency, base, rates })), qty:it.qty, color:it.color, size:it.size })),
          customer: { name:form.name, email:form.email, phone:form.phone, country:form.country, city:form.city, address:form.address, notes:form.notes },
        }),
      });
      const data = await res.json();
      if (data.ok) {
        setOrderNumber(data.order?.order_number || '');
        const ids = cart.items.map(it => it.id);
        ids.forEach(id => cart.remove(id));
        setStep('success');
      } else {
        setErrorMsg(data.error || t('Something went wrong. Please try again.','Une erreur est survenue. Veuillez réessayer.'));
        setStep('error');
      }
    } catch {
      setErrorMsg(t('Network error — please check your connection.','Erreur réseau — vérifiez votre connexion.'));
      setStep('error');
    } finally {
      setLoading(false);
    }
  };

  const fc = (k) => `lux-input${touched[k] && !valid[k] ? ' !border-rose' : ''}`;

  useEffect(() => {
    document.body.classList.add('no-scroll');
    return () => document.body.classList.remove('no-scroll');
  }, []);

  return (
    <div className="fixed inset-0 z-[101]">
      <div className="absolute inset-0 bg-deep/40 animate-fade-in" onClick={onClose}/>
      <aside className="absolute right-0 top-0 bottom-0 w-full sm:w-[520px] bg-ivory shadow-lift flex flex-col animate-slide-in-right">
        <div className="flex items-center justify-between px-6 py-5 border-b border-deep/10">
          <div className="font-display text-deep text-[26px] tracking-wide">{t('Checkout','Commander')}</div>
          <button onClick={onClose} className="w-9 h-9 rounded-full hover:bg-blush flex items-center justify-center transition-colors">
            <I.close className="w-5 h-5 text-deep"/>
          </button>
        </div>

        <div className="flex-1 overflow-y-auto px-6 py-6">
          {step === 'form' && (
            <form onSubmit={submit} className="space-y-6">
              {/* Order summary */}
              <div className="bg-blush-2/50 border border-deep/8 px-4 py-4">
                <div className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/55 mb-3">{t('Your order','Votre commande')}</div>
                <ul className="space-y-2">
                  {cart.items.map(it => (
                    <li key={it.id} className="flex items-center justify-between gap-2">
                      <span className="font-sans text-[13px] text-deep/80 truncate">
                        {it.name}{it.color && <span className="text-deep/40"> · {it.color}</span>} × {it.qty}
                      </span>
                      <span className="font-sans text-[13px] text-deep flex-none">{fmtRaw(priceOf(it.price, it.overrides) * it.qty)}</span>
                    </li>
                  ))}
                </ul>
                <div className="border-t border-deep/10 mt-3 pt-3 flex justify-between">
                  <span className="font-sans text-[11px] tracking-widest-2 uppercase text-deep/55">{t('Total','Total')}</span>
                  <span className="font-display text-deep text-[22px] leading-none">{fmtRaw(cartSubtotal)}</span>
                </div>
              </div>

              {/* Customer fields */}
              <div>
                <div className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/55 mb-4">{t('Delivery details','Coordonnées')}</div>
                <div className="space-y-4">
                  <label className="block">
                    <span className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/60">{t('Full name','Nom complet')}</span>
                    <input value={form.name} onChange={e => set('name', e.target.value)} onBlur={() => blur('name')} className={fc('name')} placeholder="Sophie Bernard"/>
                    {touched.name && !valid.name && <span className="block font-sans text-[11px] text-rose mt-1">{t('Required.','Requis.')}</span>}
                  </label>
                  <label className="block">
                    <span className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/60">{t('Email','Email')}</span>
                    <input type="email" value={form.email} onChange={e => set('email', e.target.value)} onBlur={() => blur('email')} className={fc('email')} placeholder="sophie@example.com"/>
                    {touched.email && !valid.email && <span className="block font-sans text-[11px] text-rose mt-1">{t('Valid email required.','Email valide requis.')}</span>}
                  </label>
                  <label className="block">
                    <span className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/60">{t('Phone','Téléphone')}</span>
                    <input type="tel" value={form.phone} onChange={e => set('phone', e.target.value)} onBlur={() => blur('phone')} className={fc('phone')} placeholder="+33 6 12 34 56 78"/>
                    {touched.phone && !valid.phone && <span className="block font-sans text-[11px] text-rose mt-1">{t('Required.','Requis.')}</span>}
                  </label>
                  <label className="block">
                    <span className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/60">{t('Country','Pays')}</span>
                    <select value={form.country} onChange={e => set('country', e.target.value)} className="lux-input bg-transparent">
                      <option value="FR">France</option>
                      <option value="CA">Canada</option>
                      <option value="TN">Tunisia / Tunisie</option>
                      <option value="US">United States</option>
                      <option value="GB">United Kingdom</option>
                      <option value="Other">Other / Autre</option>
                    </select>
                  </label>
                  <label className="block">
                    <span className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/60">{t('City','Ville')}</span>
                    <input value={form.city} onChange={e => set('city', e.target.value)} onBlur={() => blur('city')} className={fc('city')} placeholder="Paris"/>
                    {touched.city && !valid.city && <span className="block font-sans text-[11px] text-rose mt-1">{t('Required.','Requis.')}</span>}
                  </label>
                  <label className="block">
                    <span className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/60">{t('Address','Adresse')}</span>
                    <input value={form.address} onChange={e => set('address', e.target.value)} onBlur={() => blur('address')} className={fc('address')} placeholder="12 Rue de Rivoli"/>
                    {touched.address && !valid.address && <span className="block font-sans text-[11px] text-rose mt-1">{t('Required.','Requis.')}</span>}
                  </label>
                  <label className="block">
                    <span className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/60">{t('Notes (optional)','Notes (optionnel)')}</span>
                    <textarea value={form.notes} onChange={e => set('notes', e.target.value)} className="lux-input resize-none" rows={2} placeholder={t('Gift message, special instructions…','Message cadeau, instructions spéciales…')}/>
                  </label>
                </div>
              </div>

              {/* Payment note */}
              <div className="bg-champagne/50 border border-deep/8 px-4 py-3 font-sans text-[12px] text-deep/70 leading-relaxed">
                {isCOD
                  ? t('Payment on delivery — our team will confirm your order within 24h.','Paiement à la livraison — notre équipe confirmera votre commande sous 24h.')
                  : t("We'll confirm your order and arrange payment within 24h.",'Nous confirmerons votre commande et organiserons le paiement sous 24h.')}
              </div>

              <Button type="submit" variant="primary" className="w-full" disabled={loading}>
                {loading
                  ? t('Placing order…','En cours…')
                  : <>{t('Place order','Passer la commande')} <I.arrowR className="w-4 h-4"/></>}
              </Button>
            </form>
          )}

          {step === 'success' && (
            <div className="flex flex-col items-center justify-center text-center py-16 px-4">
              <div className="w-16 h-16 rounded-full bg-rose flex items-center justify-center mb-6">
                <I.check className="w-8 h-8 text-ivory"/>
              </div>
              <div className="font-display text-deep text-[36px] leading-tight">{t('Order placed!','Commande passée !')}</div>
              {orderNumber && (
                <div className="font-sans text-[12px] tracking-widest-2 uppercase text-deep/55 mt-3">{orderNumber}</div>
              )}
              <p className="font-sans text-[14px] text-deep/60 mt-4 max-w-[300px] leading-relaxed">
                {t("We'll be in touch at","Nous vous contacterons à")} <strong className="text-deep">{form.email}</strong> {t('within 24 hours to confirm.','sous 24h pour confirmer.')}
              </p>
              <div className="mt-8">
                <Button variant="ghost" onClick={onClose}>{t('Continue shopping','Continuer mes achats')}</Button>
              </div>
            </div>
          )}

          {step === 'error' && (
            <div className="flex flex-col items-center justify-center text-center py-16 px-4">
              <div className="font-display text-deep text-[28px] leading-tight">{t('Something went wrong','Une erreur est survenue')}</div>
              <p className="font-sans text-[14px] text-deep/60 mt-3 max-w-[300px]">{errorMsg}</p>
              <div className="mt-8 flex gap-3">
                <Button variant="ghost" onClick={() => setStep('form')}>{t('Try again','Réessayer')}</Button>
                <Button variant="ghost" onClick={onClose}>{t('Cancel','Annuler')}</Button>
              </div>
            </div>
          )}
        </div>
      </aside>
    </div>
  );
}

/* ───────────── Cart Drawer ───────────── */
function CartDrawer() {
  const cart = useCart();
  const { t } = useLang();
  const { priceOf, fmtRaw } = useCurrency();
  const cartSubtotal = cart.items.reduce((s, it) => s + priceOf(it.price, it.overrides) * it.qty, 0);
  const [checkoutOpen, setCheckoutOpen] = useState(false);

  useEffect(() => {
    document.body.classList.toggle('no-scroll', cart.open);
  }, [cart.open]);

  const openCheckout = () => { cart.setOpen(false); setCheckoutOpen(true); };

  return (
    <>
      {cart.open && (
        <div className="fixed inset-0 z-[100]">
          <div className="absolute inset-0 bg-deep/40 animate-fade-in" onClick={() => cart.setOpen(false)}/>
          <aside className="absolute right-0 top-0 bottom-0 w-full sm:w-[440px] bg-ivory shadow-lift flex flex-col animate-slide-in-right">
            {/* Head */}
            <div className="flex items-center justify-between px-6 py-5 border-b border-deep/10">
              <div className="font-display text-deep text-[26px] tracking-wide">{t('Your bag','Votre panier')}</div>
              <button onClick={() => cart.setOpen(false)} className="w-9 h-9 rounded-full hover:bg-blush flex items-center justify-center transition-colors">
                <I.close className="w-5 h-5 text-deep"/>
              </button>
            </div>

            {/* Items */}
            <div className="flex-1 overflow-y-auto px-6 py-4">
              {cart.items.length === 0 ? (
                <div className="h-full flex flex-col items-center justify-center text-center pb-20">
                  <div className="w-20 h-20 rounded-full bg-blush flex items-center justify-center mb-6">
                    <I.bag className="w-9 h-9 text-rose"/>
                  </div>
                  <div className="font-display text-deep text-[28px] leading-tight">{t('Your bag awaits','Votre panier vous attend')}</div>
                  <p className="font-sans text-[14px] text-deep/60 mt-2 max-w-[260px]">
                    {t('Discover pieces made to be lived in — and loved for years.','Découvrez des pièces faites pour être portées — et aimées pour longtemps.')}
                  </p>
                  <div className="mt-7">
                    <Button variant="primary" onClick={() => cart.setOpen(false)}>{t('Start shopping','Commencer')}</Button>
                  </div>
                </div>
              ) : (
                <ul className="divide-y divide-deep/10">
                  {cart.items.map(it => (
                    <li key={it.id} className="py-4 flex gap-4 animate-fade-in">
                      <div className="w-20 h-24 bg-blush-2 overflow-hidden flex-none rounded-sm">
                        <img src={it.img} alt={it.name} className="w-full h-full object-cover"/>
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="font-serif text-deep text-[17px] leading-tight">{it.name}</div>
                        {it.color && <div className="font-sans text-[11px] tracking-wider-2 text-deep/55 mt-1 uppercase">{it.color}</div>}
                        <div className="mt-3 flex items-center justify-between">
                          <div className="inline-flex items-center border border-deep/15">
                            <button onClick={() => cart.setQty(it.id, it.qty - 1)} className="w-8 h-8 flex items-center justify-center hover:bg-blush transition-colors"><I.minus className="w-4 h-4"/></button>
                            <span className="w-8 text-center font-sans text-[13px]">{it.qty}</span>
                            <button onClick={() => cart.setQty(it.id, it.qty + 1)} className="w-8 h-8 flex items-center justify-center hover:bg-blush transition-colors"><I.plus className="w-4 h-4"/></button>
                          </div>
                          <div className="font-sans text-[14px] tracking-wider-2 text-deep">{fmtRaw(priceOf(it.price, it.overrides) * it.qty)}</div>
                        </div>
                      </div>
                      <button onClick={() => cart.remove(it.id)} className="text-deep/50 hover:text-rose transition-colors self-start" aria-label={t('Remove','Retirer')}>
                        <I.close className="w-4 h-4"/>
                      </button>
                    </li>
                  ))}
                </ul>
              )}
            </div>

            {/* Footer */}
            {cart.items.length > 0 && (
              <div className="px-6 py-5 border-t border-deep/10 bg-blush-2/50">
                <div className="flex items-center justify-between mb-4">
                  <span className="font-sans text-[11px] tracking-widest-2 uppercase text-deep/60">{t('Subtotal','Sous-total')}</span>
                  <span className="font-display text-deep text-[28px] leading-none">{fmtRaw(cartSubtotal)}</span>
                </div>
                <div className="font-sans text-[11px] text-deep/55 mb-4">
                  {t('Shipping & taxes calculated at checkout.','Livraison et taxes calculées à la caisse.')}
                </div>
                <Button variant="primary" className="w-full" onClick={openCheckout}>
                  {t('Checkout','Commander')} <I.arrowR className="w-4 h-4"/>
                </Button>
                <button onClick={() => cart.setOpen(false)} className="mt-3 w-full font-sans text-[11px] tracking-widest-2 uppercase text-deep/60 hover:text-rose py-2">
                  {t('Continue shopping','Continuer mes achats')}
                </button>
              </div>
            )}
          </aside>
        </div>
      )}
      {checkoutOpen && <CheckoutDrawer onClose={() => setCheckoutOpen(false)}/>}
    </>
  );
}

/* ───────────── Main Menu (side panel + live image) ───────────── */
function MainMenu({ open, onClose }) {
  const { t } = useLang();
  const { siteData } = useSiteData();
  const menuImgs = (siteData.homepage && siteData.homepage.menu) || {};
  // Resolve an editable bilingual caption (Settings → Menu preview), else the built-in default.
  const cap = (key, en, fr) => {
    const n = menuImgs[`${key}Caption`];
    if (n && typeof n === 'object') return n[lang] || n.en || t(en, fr);
    return (typeof n === 'string' && n.trim()) ? n : t(en, fr);
  };
  useEffect(() => { document.body.classList.toggle('no-scroll', open); }, [open]);

  // primary categories + sub-links, each with its own preview image (editable in Settings → homepage)
  const sections = [
    {
      title: t('Shop','Boutique'),
      href: '#shop',
      img:   menuImgs.shop || IMG('photo-1490481651871-ab68de25d43d', 900),
      caption: cap('shop', 'All pieces', 'Toutes les pièces'),
      sub: [
        { label: t('New In','Nouveautés'),         href: '#shop/new' },
        { label: t('Best Sellers','Meilleures ventes'), href: '#shop/bestsellers' },
        { label: t('Dresses','Robes'),             href: '#shop/dresses' },
        { label: t('Sets','Ensembles'),            href: '#shop/sets' },
        { label: t('Tops','Hauts'),                href: '#shop/tops' },
        { label: t('Accessories','Accessoires'),   href: '#shop/accessories' },
      ],
    },
    {
      title: t('Collections','Collections'),
      href: '#collections',
      img:   menuImgs.collections || IMG('photo-1539008835657-9e8e9680c956', 900),
      caption: cap('collections', 'Summer Edit · 2026', 'Édition Été · 2026'),
    },
    {
      title: t('About','À propos'),
      href: '#about',
      img:   menuImgs.about || IMG('photo-1518049362265-d5b2a6b00b37', 900),
      caption: cap('about', 'The boutique', 'La boutique'),
    },
    {
      title: t('Contact','Contact'),
      href: '#contact',
      img:   menuImgs.contact || IMG('photo-1483985988355-763728e1935b', 900),
      caption: cap('contact', 'Write to us', 'Écrivez-nous'),
    },
  ];

  const [hoveredIdx, setHoveredIdx] = useState(0);
  const [expanded,   setExpanded]   = useState(false); // expand "Shop" sub-list
  const current = sections[hoveredIdx];

  if (!open) return null;
  return (
    <div className="fixed inset-0 z-[100]">
      <div className="absolute inset-0 bg-deep/40 animate-fade-in" onClick={onClose}/>

      <aside className="absolute left-0 top-0 bottom-0 w-full md:w-[600px] lg:w-[720px] xl:w-[780px] flex animate-slide-in-left">
        {/* ── Left pane: links ── */}
        <div className="flex-1 bg-ivory flex flex-col relative overflow-y-auto">
          {/* Paper grain */}
          <div className="pointer-events-none absolute inset-0 opacity-[.5]"
               style={{background:'radial-gradient(rgba(74,45,51,0.04) 1px, transparent 1px)', backgroundSize:'3px 3px'}}/>

          {/* Header */}
          <div className="relative flex items-center justify-between px-6 md:px-8 py-4 border-b border-deep/10">
            <span className="font-sans text-[11px] tracking-widest-2 uppercase text-deep/55">{t('Menu','Menu')}</span>
            <button onClick={onClose} className="w-9 h-9 rounded-full hover:bg-blush flex items-center justify-center transition-colors text-deep" aria-label={t('Close','Fermer')}>
              <I.close className="w-[18px] h-[18px]"/>
            </button>
          </div>

          {/* Big links */}
          <nav className="relative flex-1 px-6 md:px-8 pt-7 pb-6 flex flex-col">
            {sections.map((s, i) => {
              const active = hoveredIdx === i;
              const isShop = i === 0;
              return (
                <div key={s.title} className="border-b border-deep/10 last:border-b-0">
                  <div className="flex items-center justify-between gap-3 py-2.5 group"
                       onMouseEnter={() => setHoveredIdx(i)}>
                    <a href={s.href}
                       onClick={onClose}
                       className={`font-display leading-[1.05] tracking-wide transition-all duration-300
                         ${active ? 'text-rose' : 'text-deep hover:text-rose'}`}
                       style={{fontSize:'clamp(28px, 3.2vw, 44px)'}}>
                      <span className="inline-flex items-center gap-3">
                        <span className={`inline-block transition-all duration-500 ${active ? 'w-6 md:w-9 opacity-100' : 'w-0 opacity-0'} overflow-hidden`}>
                          <span className="block h-px bg-rose"></span>
                        </span>
                        {s.title}
                      </span>
                    </a>
                    {isShop && (
                      <button onClick={() => { setExpanded(!expanded); setHoveredIdx(i); }}
                              className={`text-deep/60 hover:text-rose w-8 h-8 rounded-full border border-deep/15 flex items-center justify-center transition-all duration-300 ${expanded ? 'rotate-45 bg-deep text-ivory border-deep' : ''}`}
                              aria-label={t('Expand','Développer')}>
                        <I.plus className="w-3.5 h-3.5"/>
                      </button>
                    )}
                  </div>

                  {/* Sub-links — animated reveal */}
                  {isShop && s.sub && (
                    <div className={`grid transition-all duration-500 ${expanded ? 'grid-rows-[1fr] opacity-100 mb-3' : 'grid-rows-[0fr] opacity-0'}`}>
                      <div className="overflow-hidden">
                        <ul className="pl-1 pb-2 grid grid-cols-2 gap-x-4 gap-y-2">
                          {s.sub.map((sub, j) => (
                            <li key={sub.label}>
                              <a href={sub.href} onClick={onClose}
                                 className="inline-flex items-center gap-2 font-serif text-deep text-[17px] hover:text-rose transition-colors"
                                 style={{transitionDelay: expanded ? `${j*30}ms` : '0ms'}}>
                                <span className="w-1 h-1 rounded-full bg-rose"></span>
                                {sub.label}
                              </a>
                            </li>
                          ))}
                        </ul>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </nav>

          {/* Footer of left pane */}
          <div className="relative border-t border-deep/10 px-6 md:px-8 py-4 flex flex-wrap items-center justify-between gap-3">
            <div className="flex items-center gap-4 text-deep">
              <a href={SITE_SETTINGS.instagramUrl || '#'} target="_blank" rel="noopener noreferrer" aria-label="Instagram" className="hover:text-rose transition-colors"><I.insta className="w-[16px] h-[16px]"/></a>
              <a href={SITE_SETTINGS.tiktokUrl || '#'} target="_blank" rel="noopener noreferrer" aria-label="TikTok"    className="hover:text-rose transition-colors"><I.tiktok className="w-[16px] h-[16px]"/></a>
              <a href={SITE_SETTINGS.facebookUrl || '#'} target="_blank" rel="noopener noreferrer" aria-label="Facebook" className="hover:text-rose transition-colors"><I.facebook className="w-[16px] h-[16px]"/></a>
            </div>
            <div className="flex items-center gap-4">
              <LangSwitcher/>
              <CurrencySwitcher/>
            </div>
            <div className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/55 hidden sm:block">
              {SITE_SETTINGS.supportEmail}
            </div>
          </div>
        </div>

        {/* ── Right pane: live preview image (desktop only) ── */}
        <div className="hidden md:block w-[42%] lg:w-[46%] bg-blush relative overflow-hidden">
          {sections.map((s, i) => (
            <img key={s.title} src={s.img} alt={s.caption}
                 className={`absolute inset-0 w-full h-full object-cover transition-all duration-[900ms] ease-out
                   ${hoveredIdx === i ? 'opacity-100 scale-100' : 'opacity-0 scale-[1.04]'}`}
                 style={{transitionTimingFunction:'cubic-bezier(.2,.65,.2,1)'}}/>
          ))}
          <div className="absolute inset-0 bg-gradient-to-t from-deep/55 via-deep/0 to-transparent"/>

          {/* Caption */}
          <div className="absolute inset-x-0 bottom-0 p-6 md:p-7 text-ivory">
            <div className="font-sans text-[10px] tracking-widest-2 uppercase opacity-80">{current.caption}</div>
            <div className="font-display leading-[1.05] mt-1.5" style={{fontSize:'clamp(28px, 2.6vw, 40px)'}}>{current.title}</div>
            <a href={current.href} onClick={onClose}
               className="mt-4 inline-flex items-center gap-2 font-sans text-[10px] tracking-widest-2 uppercase border-b border-ivory pb-1 hover:gap-3 transition-all">
              {t('Explore','Découvrir')} <I.arrowR className="w-3.5 h-3.5"/>
            </a>
          </div>

          {/* Top right tag */}
          <div className="absolute top-5 right-5 font-sans text-[10px] tracking-widest-2 uppercase text-ivory/85">
            0{hoveredIdx + 1} / 0{sections.length}
          </div>
        </div>
      </aside>
    </div>
  );
}

Object.assign(window, {
  Announcement, Nav, Hero, Categories, NewArrivals, BrandStory,
  BestSellers, Instagram, Newsletter, Footer, CartDrawer, MainMenu,
});
