// HOS — secondary pages (Shop / Collections / Product / About / Contact)

/* ───────────── Shared ───────────── */
function PageHero({ eyebrow, title, subtitle, crumbs, tone = 'blush', tall = false }) {
  const bg = tone === 'champagne' ? 'bg-champagne/60' : tone === 'ivory' ? 'bg-ivory grain' : 'bg-blush';
  return (
    <section className={`relative ${bg} overflow-hidden`}>
      <div className="pointer-events-none absolute -top-32 -right-32 w-[440px] h-[440px] rounded-full opacity-50"
           style={{background:'radial-gradient(closest-side, rgba(248,228,231,1), transparent 70%)'}}/>
      <div className={`relative max-w-[1440px] mx-auto px-6 md:px-10 ${tall ? 'pt-14 pb-16 md:pt-20 md:pb-24' : 'pt-12 pb-12 md:pt-16 md:pb-16'}`}>
        {crumbs && (
          <div className="reveal flex items-center gap-2 font-sans text-[11px] tracking-widest-2 uppercase text-deep/55 mb-5">
            {crumbs.map((c, i) => (
              <React.Fragment key={i}>
                {i > 0 && <span>/</span>}
                {c.href ? <a href={c.href} className="hover:text-rose transition-colors">{c.label}</a> : <span className="text-deep">{c.label}</span>}
              </React.Fragment>
            ))}
          </div>
        )}
        <div className="reveal reveal-delay-1"><Eyebrow>{eyebrow}</Eyebrow></div>
        <h1 className="reveal reveal-delay-2 font-display text-deep mt-4 leading-[0.92]" style={{fontSize:'clamp(40px, 5.6vw, 88px)'}}>
          {title}
        </h1>
        {subtitle && (
          <p className="reveal reveal-delay-3 mt-5 max-w-[540px] font-sans text-[15px] leading-[1.7] text-deep/70">
            {subtitle}
          </p>
        )}
      </div>
    </section>
  );
}

/* ───────────── SHOP / PLP ───────────── */
const CAT_FR_PAGE = { dresses:'Robes', sets:'Ensembles', tops:'Hauts', bottoms:'Bas', accessories:'Accessoires' };
function ShopPage({ subPath }) {
  const { t, lang } = useLang();
  const { siteData } = useSiteData();
  const liveProducts = siteData.products.length > 0 ? siteData.products : ALL_PRODUCTS;
  // Determine filter from URL: shop, shop/new, shop/bestsellers, shop/<category>
  const filterKey = subPath || 'all';
  const titleMap = {
    all:         { eyebrow: t('Shop everything','Tout voir'),     title: t('The full edit','Le vestiaire complet'),    sub: t('Every piece from House of Sheylas — curated, considered, and made to be worn for years.','Toutes les pièces House of Sheylas — sélectionnées, pensées et faites pour durer.') },
    new:         { eyebrow: t('Just landed','Tout juste arrivé'), title: t('New arrivals','Nouveautés'),                sub: t('The latest arrivals — freshly added to the edit.','Les dernières arrivées — tout juste ajoutées à la sélection.') },
    bestsellers: { eyebrow: t('Always in rotation','Toujours en rotation'), title: t('Best sellers','Meilleures ventes'), sub: 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.') },
    dresses:     { eyebrow: t('Edit','Sélection'), title: t('Dresses','Robes'),         sub: t('From slip silks to flowing maxis — silhouettes designed to drape, move, and stay with you.','Du satin léger aux maxis fluides — des silhouettes pensées pour draper, bouger et durer.') },
    sets:        { eyebrow: t('Edit','Sélection'), title: t('Sets','Ensembles'),         sub: t('Effortless coordinates — wear together or apart.','Coordonnés sans effort — ensemble ou séparément.') },
    tops:        { eyebrow: t('Edit','Sélection'), title: t('Tops','Hauts'),             sub: t('Soft blouses, knits, and tailoring — the foundations of a quietly elegant wardrobe.','Blouses douces, mailles et tailoring — les fondations d’un vestiaire discrètement élégant.') },
    bottoms:     { eyebrow: t('Edit','Sélection'), title: t('Bottoms','Bas'),            sub: t('Tailored trousers, flowing skirts, and softly worn denims.','Pantalons cintrés, jupes fluides et denims doucement portés.') },
    accessories: { eyebrow: t('Edit','Sélection'), title: t('Accessories','Accessoires'),sub: t('The finishing touches — small, sentimental, made to last.','Les touches finales — petites, sentimentales, faites pour durer.') },
  };
  // Resolve the page heading — known filters use the curated copy above; any other
  // category (including ones created in the admin) falls back to its own name/description.
  const catMatch = (siteData.categories || []).find((c) => c.id === filterKey);
  const meta = titleMap[filterKey] || (catMatch ? {
    eyebrow: t('Edit', 'Sélection'),
    title: lang === 'fr' ? (CAT_FR_PAGE[catMatch.id] || catMatch.name) : catMatch.name,
    sub: catMatch.description || t('Browse the edit.', 'Parcourez la sélection.'),
  } : titleMap.all);

  // Filter products — uses live Supabase data once loaded
  const products = useMemo(() => {
    if (filterKey === 'all') return liveProducts;
    if (filterKey === 'new') return liveProducts.filter(p => p.isNew);
    if (filterKey === 'bestsellers') return liveProducts.filter(p => p.isBest);
    return liveProducts.filter(p => p.category === filterKey);
  }, [filterKey, liveProducts]);

  // Filter controls
  const [sort, setSort]       = useState('featured');
  const [colorF, setColorF]   = useState(null);
  const [sizeF, setSizeF]     = useState(null);
  const [priceMax, setPriceMax] = useState(null); // null = no cap (show all prices)
  const [view, setView]       = useState('grid'); // grid | dense
  const [filtersOpen, setFiltersOpen] = useState(false);
  const activeFilters = (colorF ? 1 : 0) + (sizeF ? 1 : 0) + (priceMax != null ? 1 : 0);

  // Slider ceiling adapts to the real catalogue so high-priced pieces are never hidden.
  const priceCeiling = useMemo(() => {
    const top = Math.max(400, ...liveProducts.map(p => Math.ceil(Number(p.price) || 0)));
    return Math.ceil(top / 50) * 50;
  }, [liveProducts]);

  const sorted = useMemo(() => {
    let arr = [...products];
    if (colorF) arr = arr.filter(p => p.colors?.some(c => c.name === colorF));
    if (sizeF) arr = arr.filter(p => (p.sizes || SIZES).includes(sizeF));
    arr = arr.filter(p => priceMax == null || p.price <= priceMax);
    if (sort === 'price-asc')  arr.sort((a,b) => a.price - b.price);
    if (sort === 'price-desc') arr.sort((a,b) => b.price - a.price);
    if (sort === 'new')        arr.sort((a,b) => (b.isNew?1:0) - (a.isNew?1:0));
    return arr;
  }, [products, sort, colorF, sizeF, priceMax]);

  const allColors = useMemo(() => {
    const s = new Set();
    liveProducts.forEach(p => p.colors?.forEach(c => s.add(JSON.stringify(c))));
    return [...s].map(s => JSON.parse(s));
  }, [liveProducts]);

  // Quick filter chips — All / New / Best sellers, then every real category from the DB
  // (so a new admin category like "Swimwear" shows up here automatically).
  const chips = [
    { key:'all',         label: t('All','Tout'),                href:'#shop' },
    { key:'new',         label: t('New In','Nouveautés'),       href:'#shop/new' },
    { key:'bestsellers', label: t('Best Sellers','Meilleures ventes'), href:'#shop/bestsellers' },
    ...(siteData.categories || []).filter((c) => c && c.name).map((c) => ({
      key: c.id,
      label: lang === 'fr' ? (CAT_FR_PAGE[c.id] || c.name) : c.name,
      href: `#shop/${c.id}`,
    })),
  ];

  const catBreadcrumb = filterKey==='all' ? null : { label: meta.title };

  return (
    <>
      <PageHero
        eyebrow={meta.eyebrow}
        title={meta.title}
        subtitle={meta.sub}
        crumbs={[{label:t('Home','Accueil'), href:'#home'}, {label:t('Shop','Boutique'), href:'#shop'}, ...(catBreadcrumb ? [catBreadcrumb] : [])]}
        tone="blush"
      />

      {/* Sticky filter rail */}
      <div className="bg-ivory border-b border-deep/10 sticky top-[68px] z-20 backdrop-blur-md bg-ivory/80">
        <div className="max-w-[1440px] mx-auto px-6 md:px-10 py-5 flex flex-col lg:flex-row lg:items-center gap-5 lg:gap-8">
          {/* Chips */}
          <div className="flex items-center gap-2 overflow-x-auto -mx-2 px-2 flex-1">
            {chips.map(c => (
              <a key={c.key} href={c.href}
                 className={`whitespace-nowrap font-sans text-[11px] tracking-widest-2 uppercase px-4 py-2 rounded-full border transition-all
                   ${filterKey===c.key ? 'bg-deep text-ivory border-deep' : 'bg-transparent text-deep border-deep/20 hover:border-deep'}`}>
                {c.label}
              </a>
            ))}
          </div>

          {/* Sort + view */}
          <div className="flex items-center gap-4 lg:gap-6">
            <label className="font-sans text-[11px] tracking-widest-2 uppercase text-deep/60 hidden md:flex items-center gap-2">
              {t('Sort','Trier')}
              <select value={sort} onChange={e => setSort(e.target.value)}
                      className="bg-transparent border-b border-deep/20 py-1 font-sans text-[12px] text-deep tracking-wider-2 focus:outline-none focus:border-rose">
                <option value="featured">{t('Featured','Recommandé')}</option>
                <option value="new">{t('Newest','Nouveautés')}</option>
                <option value="price-asc">{t('Price: low → high','Prix : croissant')}</option>
                <option value="price-desc">{t('Price: high → low','Prix : décroissant')}</option>
              </select>
            </label>
            <div className="flex items-center border border-deep/15">
              <button onClick={() => setView('grid')}  className={`w-9 h-9 flex items-center justify-center ${view==='grid'?'bg-deep text-ivory':'text-deep'}`}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" className="w-4 h-4"><rect x="4" y="4" width="7" height="7"/><rect x="13" y="4" width="7" height="7"/><rect x="4" y="13" width="7" height="7"/><rect x="13" y="13" width="7" height="7"/></svg>
              </button>
              <button onClick={() => setView('dense')} className={`w-9 h-9 flex items-center justify-center ${view==='dense'?'bg-deep text-ivory':'text-deep'}`}>
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.4" className="w-4 h-4"><rect x="3" y="3" width="5" height="5"/><rect x="10" y="3" width="5" height="5"/><rect x="17" y="3" width="5" height="5"/><rect x="3" y="10" width="5" height="5"/><rect x="10" y="10" width="5" height="5"/><rect x="17" y="10" width="5" height="5"/><rect x="3" y="17" width="5" height="5"/><rect x="10" y="17" width="5" height="5"/><rect x="17" y="17" width="5" height="5"/></svg>
              </button>
            </div>
          </div>
        </div>
      </div>

      <section className="bg-ivory">
        <div className="max-w-[1440px] mx-auto px-6 md:px-10 py-10 md:py-14">
          {/* Toolbar: Filters button + result count */}
          <div className="flex items-center justify-between mb-8">
            <button onClick={() => setFiltersOpen(true)}
              className="inline-flex items-center gap-2.5 font-sans text-[11px] tracking-widest-2 uppercase text-deep border border-deep/20 rounded-full px-5 py-2.5 hover:border-deep hover:bg-deep hover:text-ivory transition-all">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="w-4 h-4"><path d="M3 5h18M6 12h12M10 19h4" strokeLinecap="round"/></svg>
              {t('Filters','Filtres')}{activeFilters > 0 && <span className="ml-1 inline-flex items-center justify-center min-w-[18px] h-[18px] rounded-full bg-rose text-ivory text-[10px]">{activeFilters}</span>}
            </button>
            <span className="font-sans text-[11px] tracking-widest-2 uppercase text-deep/50">
              {sorted.length} {t('pieces','pièces')}
            </span>
          </div>

          {/* Grid */}
          {sorted.length === 0 ? (
            <div className="py-24 text-center">
              <div className="font-display text-deep text-[42px] leading-none">{t('No matches','Aucun résultat')}</div>
              <p className="font-sans text-[14px] text-deep/60 mt-3">{t('Adjust your filters to see more pieces.','Modifiez vos filtres pour voir plus de pièces.')}</p>
            </div>
          ) : (
            <div className={`grid gap-x-5 gap-y-12 md:gap-x-7 md:gap-y-16 grid-cols-2 ${view==='dense' ? 'lg:grid-cols-5 md:grid-cols-4' : 'md:grid-cols-3 lg:grid-cols-4'}`}>
              {sorted.map((p, i) => <ProductCard key={p.id} p={p} idx={i}/>)}
            </div>
          )}
        </div>

        {/* Filter drawer (slides in from the right, all breakpoints) */}
        {filtersOpen && (
          <div className="fixed inset-0 z-[90]">
            <div className="absolute inset-0 bg-deep/40 animate-fade-in" onClick={() => setFiltersOpen(false)}/>
            <aside className="absolute right-0 top-0 bottom-0 w-full sm:w-[380px] 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">
                <h3 className="font-display text-deep text-[26px] leading-none">{t('Filters','Filtres')}</h3>
                <button onClick={() => setFiltersOpen(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>
              <div className="flex-1 overflow-y-auto px-6 py-2">
                {/* Color */}
                <div className="border-b border-deep/[0.07] py-6">
                  <div className="flex items-baseline justify-between mb-4">
                    <h4 className="font-sans text-[11px] tracking-widest-2 uppercase text-deep/60">{t('Color','Couleur')}</h4>
                    <span className="font-serif italic text-deep/70 text-[14px]">{colorF || t('All','Toutes')}</span>
                  </div>
                  <div className="flex flex-wrap gap-3">
                    {allColors.map(c => (
                      <button key={c.name} onClick={() => setColorF(colorF === c.name ? null : c.name)} title={c.name}
                        className={`w-9 h-9 rounded-full transition-all duration-300 border ${colorF === c.name ? 'ring-2 ring-offset-2 ring-offset-ivory ring-deep scale-110 border-transparent' : 'border-deep/10 hover:scale-110'}`}
                        style={swatchStyle(c)}/>
                    ))}
                  </div>
                </div>
                {/* Price */}
                <div className="border-b border-deep/[0.07] py-6">
                  <h4 className="font-sans text-[11px] tracking-widest-2 uppercase text-deep/60 mb-3">{t('Max price','Prix max')}</h4>
                  <div className="font-display text-deep text-[28px] mb-3 leading-none">${priceMax ?? priceCeiling}</div>
                  <input type="range" min="0" max={priceCeiling} step="10" value={priceMax ?? priceCeiling} onChange={e => setPriceMax(+e.target.value)} className="w-full accent-rose"/>
                  <div className="flex justify-between font-sans text-[10px] tracking-widest-2 uppercase text-deep/45 mt-2"><span>$0</span><span>${priceCeiling}</span></div>
                </div>
                {/* Size */}
                <div className="py-6">
                  <h4 className="font-sans text-[11px] tracking-widest-2 uppercase text-deep/60 mb-4">{t('Size','Taille')}</h4>
                  <div className="flex flex-wrap gap-2">
                    {SIZES.map(s => (
                      <button key={s} onClick={() => setSizeF(sizeF === s ? null : s)}
                        className={`font-sans text-[12px] tracking-wider-2 border rounded-full px-3.5 py-1.5 transition-colors ${sizeF === s ? 'bg-deep text-ivory border-deep' : 'text-deep/75 border-deep/15 hover:bg-deep hover:text-ivory hover:border-deep'}`}>{s}</button>
                    ))}
                  </div>
                </div>
              </div>
              <div className="px-6 py-4 border-t border-deep/10 flex items-center gap-3">
                <button onClick={() => { setColorF(null); setSizeF(null); setPriceMax(null); setSort('featured'); }}
                  className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/55 hover:text-rose transition-colors">{t('Reset','Réinitialiser')}</button>
                <button onClick={() => setFiltersOpen(false)} className="flex-1 bg-deep text-ivory font-sans uppercase tracking-widest-2 text-[11px] py-3.5 hover:bg-rose transition-colors">
                  {t('Show','Voir')} {sorted.length} {t('pieces','pièces')}
                </button>
              </div>
            </aside>
          </div>
        )}
      </section>

      <Newsletter />
    </>
  );
}

/* ───────────── COLLECTIONS ───────────── */
function CollectionsPage() {
  const { t, lang } = useLang();
  const SEASON_FR = { 'SS 2026':'PE 2026', 'AW 2026':'AH 2026', 'Resort':'Croisière', 'Capsule':'Capsule' };
  const COL_FR = { 'spring-bloom':'Édition Été', 'summer-edit':'Édition Été', 'soft-noir':'Noir doux', 'champagne':'Heure du Champagne', 'atelier':'Édition sélectionnée' };
  return (
    <>
      <PageHero
        eyebrow={t('Lookbook','Lookbook')}
        title={lang==='fr' ? <>Collections <em className="font-serif font-light italic">&amp; éditions</em></> : <>Collections <em className="font-serif font-light italic">&amp; édits</em></>}
        subtitle={t('Each collection is a curated edit — selected and styled with intention.','Chaque collection est une sélection — choisie et stylée avec intention.')}
        crumbs={[{label:t('Home','Accueil'), href:'#home'}, {label:t('Collections','Collections')}]}
        tone="champagne"
      />

      {/* Featured collection — large editorial */}
      <section className="bg-ivory">
        <div className="max-w-[1440px] mx-auto px-6 md:px-10 py-16 md:py-24">
          <div className="grid lg:grid-cols-12 gap-10 items-center">
            <div className="reveal lg:col-span-7 relative aspect-[4/5] lg:aspect-[5/6] overflow-hidden bg-blush rounded-sm shadow-card">
              <img src={IMG('photo-1490481651871-ab68de25d43d', 1400)} alt="" className="absolute inset-0 w-full h-full object-cover img-zoom"/>
              <div className="absolute inset-x-6 bottom-6 flex items-end justify-between text-ivory">
                <div>
                  <div className="font-sans text-[10px] tracking-widest-2 uppercase opacity-80">{t('Featured · SS 2026','En vedette · PE 2026')}</div>
                  <div className="font-display text-[64px] md:text-[88px] leading-none">{t('Summer Edit','Édition Été')}</div>
                </div>
                <a href="#collections" className="hidden md:flex items-center gap-2 font-sans text-[11px] tracking-widest-2 uppercase border-b border-ivory pb-1">
                  {t('Discover','Découvrir')} <I.arrowR className="w-4 h-4"/>
                </a>
              </div>
            </div>
            <div className="lg:col-span-5">
              <div className="reveal"><Eyebrow>{t('Chapter 01','Chapitre 01')}</Eyebrow></div>
              <h2 className="reveal reveal-delay-1 font-display text-deep mt-5 leading-[0.95]" style={{fontSize:'clamp(34px, 4.4vw, 64px)'}}>
                {t('A garden in','Un jardin en')} <em className="italic font-serif font-light">{t('silk.','soie.')}</em>
              </h2>
              <p className="reveal reveal-delay-2 mt-6 font-sans text-[16px] leading-[1.75] text-deep/70">
                {t(
                  'A selection inspired by Parisian flower markets at dawn — feather-light silks, embroidered detail, and soft tailoring, hand-picked for the season.',
                  'Une sélection inspirée des marchés aux fleurs parisiens à l’aube — soies légères, détails brodés et tailoring doux, choisis pour la saison.'
                )}
              </p>
              <div className="reveal reveal-delay-3 mt-8 grid grid-cols-3 gap-6 max-w-[420px]">
                {[
                  ['32', t('Pieces','Pièces')],
                  ['08', t('Looks','Looks')],
                  ['100%', t('Silk &amp; linen','Soie &amp; lin')]
                ].map(([k,v]) => (
                  <div key={k}>
                    <div className="font-display text-deep text-[32px] leading-none">{k}</div>
                    <div className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/55 mt-2" dangerouslySetInnerHTML={{__html:v}}></div>
                  </div>
                ))}
              </div>
              <div className="reveal reveal-delay-4 mt-9">
                <Button as="a" href="#shop/new" variant="primary" size="lg">{t('Shop the collection','Voir la collection')} <I.arrowR className="w-4 h-4"/></Button>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* Other collections grid */}
      <section className="bg-champagne/40">
        <div className="max-w-[1440px] mx-auto px-6 md:px-10 py-14 md:py-20">
          <div className="flex flex-col md:flex-row md:items-end md:justify-between gap-6 mb-12">
            <div>
              <div className="reveal"><Eyebrow>{t('Édits','Éditions')}</Eyebrow></div>
              <h2 className="reveal reveal-delay-1 font-display text-deep mt-5 leading-[0.95]" style={{fontSize:'clamp(34px, 4.4vw, 64px)'}}>
                {t('More collections','Autres collections')}
              </h2>
            </div>
            <p className="reveal reveal-delay-2 max-w-[420px] font-sans text-[15px] text-deep/65 leading-relaxed">
              {t(
                'Explore past chapters and capsules — many pieces remain available in limited quantities.',
                'Explorez les chapitres et capsules passés — de nombreuses pièces restent disponibles en quantités limitées.'
              )}
            </p>
          </div>

          <div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8">
            {COLLECTIONS.map((c, i) => (
              <a key={c.id} href={`#shop`} className={`reveal reveal-delay-${i+1} group block`}>
                <div className="relative overflow-hidden aspect-[4/5] bg-blush rounded-sm shadow-card">
                  <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-t from-deep/60 via-deep/0 to-transparent"/>
                  <div className="absolute top-5 left-5 font-sans text-[10px] tracking-widest-2 uppercase text-ivory/80 flex items-center gap-2">
                    <span className="w-2 h-2 rounded-full" style={{background:c.accent}}/>
                    {lang === 'fr' ? (SEASON_FR[c.season] || c.season) : c.season}
                  </div>
                  <div className="absolute inset-x-5 bottom-5 flex items-end justify-between text-ivory">
                    <div>
                      <div className="font-display text-[34px] leading-none">{lang==='fr' ? (COL_FR[c.id] || c.name) : c.name}</div>
                      <div className="font-sans text-[11px] tracking-widest-2 uppercase opacity-80 mt-2">{c.pieces} {t('pieces','pièces')}</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>
            ))}
          </div>
        </div>
      </section>
    </>
  );
}

/* ───────────── PRODUCT DETAIL ───────────── */
const COPY_FR = {
  description: 'Coupée dans une soie satinée légère, cette pièce drape sans effort grâce à une silhouette en biais qui suit vos mouvements. Bretelles réglables et encolure dégagée — élégante pour le soir comme superposée à une maille.',
  fabric: '100 % soie de mûrier · Nettoyage à sec uniquement',
  fit: 'Taille normale · Mannequin 1,75 m portant un S',
  shipping: 'Livraison internationale · Calculée à la caisse',
};
function ProductPage({ productId }) {
  const { siteData } = useSiteData();
  const liveProducts = siteData.products.length > 0 ? siteData.products : ALL_PRODUCTS;
  const p = liveProducts.find(x => x.id === productId || x.slug === productId) || liveProducts[0];
  const cart = useCart();
  const { t, lang } = useLang();
  const { fmt, priceOf, fmtRaw } = useCurrency();
  const COPY_L = lang === 'fr' ? COPY_FR : COPY;
  const soldOut = p.stock === 0 || p.stock === '0';
  // Real product images only — no more random hero/story photos.
  const gallery = (Array.isArray(p.gallery) && p.gallery.length ? p.gallery : [p.img]).filter(Boolean).slice(0, 6);
  // Real sizes from the product's variants, falling back to the standard run.
  const sizeOptions = (Array.isArray(p.sizes) && p.sizes.length) ? p.sizes : SIZES;

  const [size, setSize] = useState(sizeOptions[0]);
  const [colorIx, setColorIx] = useState(0);
  const [qty, setQty] = useState(1);
  // Selected-variant pricing: a variant's own price/overrides win, else the product's.
  const selColor = (Array.isArray(p.colors) && p.colors[colorIx]) ? p.colors[colorIx] : {};
  const priceBase = (selColor.price !== undefined && selColor.price !== null && selColor.price !== '') ? Number(selColor.price) : p.price;
  const priceOv = (selColor.priceOverrides && Object.keys(selColor.priceOverrides).length) ? selColor.priceOverrides : p.priceOverrides;
  const [tab, setTab] = useState('description');
  const [mainImg, setMainImg] = useState(p.img);
  const [guideOpen, setGuideOpen] = useState(false);

  useEffect(() => { setMainImg(p.img); setColorIx(0); setSize(sizeOptions[0]); setQty(1); }, [productId]);

  // "You may also love" — admin-chosen pairings first (p.related), then same-category fill.
  const related = useMemo(() => {
    const picks = (Array.isArray(p.related) ? p.related : [])
      .map((ref) => liveProducts.find((x) => x.slug === ref || x.id === ref))
      .filter(Boolean);
    const ids = new Set(picks.map((x) => x.id));
    const fill = liveProducts.filter((x) => x.category === p.category && x.id !== p.id && !ids.has(x.id));
    return [...picks, ...fill].filter((x) => x.id !== p.id).slice(0, 4);
  }, [p, liveProducts]);

  // Real description + universal, professional product info (no placeholder silk-satin copy).
  const productDesc = p.description || t('A considered piece, selected for the House of Sheylas edit.', 'Une pièce choisie avec soin pour la sélection House of Sheylas.');
  const TAB_LABELS = {
    description: t('Details','Détails'),
    fabric:      t('Fabric & care','Tissu & entretien'),
    fit:         t('Fit','Coupe'),
    shipping:    t('Shipping','Livraison'),
  };
  const TAB_CONTENT = {
    description: productDesc,
    fabric:  p.material || t('Cool, gentle wash or dry clean. Reshape and lay flat to dry. Cool iron if needed.','Lavage doux à froid ou nettoyage à sec. Remettre en forme et sécher à plat. Repasser à froid si besoin.'),
    fit:     p.fit || t('True to size. Between sizes? Size up for a relaxed fit.','Taille normale. Entre deux tailles ? Prenez la taille au-dessus pour un tombé ample.'),
    shipping: t('Worldwide shipping, calculated at checkout. Ships within 1–2 business days. Easy 14-day returns.','Livraison mondiale, calculée au paiement. Expédition sous 1 à 2 jours ouvrés. Retours faciles sous 14 jours.'),
  };
  const catLabel = lang === 'fr' ? (CAT_FR_PAGE[p.category] || p.category) : p.category;

  return (
    <>
      <section className="bg-ivory">
        <div className="max-w-[1440px] mx-auto px-6 md:px-10 pt-10 md:pt-14 pb-16 md:pb-24">
          <div className="reveal flex items-center gap-2 font-sans text-[11px] tracking-widest-2 uppercase text-deep/55 mb-8">
            <a href="#home"   className="hover:text-rose transition-colors">{t('Home','Accueil')}</a><span>/</span>
            <a href="#shop"   className="hover:text-rose transition-colors">{t('Shop','Boutique')}</a><span>/</span>
            <a href={`#shop/${p.category}`} className="hover:text-rose transition-colors">{catLabel}</a><span>/</span>
            <span className="text-deep">{p.name}</span>
          </div>

          <div className="grid lg:grid-cols-12 gap-10 lg:gap-16">
            {/* Gallery */}
            <div className="lg:col-span-7 flex gap-4">
              <div className="hidden md:flex flex-col gap-3 w-20 flex-none">
                {gallery.map((g, i) => (
                  <button key={i} onClick={() => setMainImg(g)}
                          className={`relative aspect-[3/4] overflow-hidden bg-blush-2 rounded-sm transition-all ${mainImg === g ? 'ring-2 ring-deep' : 'opacity-70 hover:opacity-100'}`}>
                    <img src={g} alt="" className="absolute inset-0 w-full h-full object-cover"/>
                  </button>
                ))}
              </div>
              <div className="reveal flex-1 relative aspect-[3/4] overflow-hidden bg-blush rounded-sm shadow-card">
                <img src={mainImg} alt={p.name} className={`absolute inset-0 w-full h-full object-cover img-zoom ${soldOut ? 'grayscale-[0.35]' : ''}`}/>
                {soldOut ? (
                  <span className="absolute top-4 left-4 bg-deep text-ivory text-[10px] tracking-widest-2 uppercase px-3 py-1.5">{t('Sold out','Épuisé')}</span>
                ) : p.badge ? (
                  <span className="absolute top-4 left-4 bg-deep text-ivory text-[10px] tracking-widest-2 uppercase px-3 py-1.5">{lang==='fr' ? (TAG_FR[p.badge] || p.badge) : p.badge}</span>
                ) : p.tag ? (
                  <span className="absolute top-4 left-4 bg-ivory/95 text-deep text-[10px] tracking-widest-2 uppercase px-3 py-1.5">{lang==='fr' ? (TAG_FR[p.tag] || p.tag) : p.tag}</span>
                ) : null}
              </div>
              {/* Mobile thumbs */}
              <div className="md:hidden flex gap-2 absolute bottom-2 left-2 right-2">
                {gallery.map((g, i) => (
                  <button key={i} onClick={() => setMainImg(g)} className={`flex-1 h-14 bg-ivory/90 rounded-sm overflow-hidden ${mainImg===g?'ring-2 ring-deep':''}`}>
                    <img src={g} alt="" className="w-full h-full object-cover"/>
                  </button>
                ))}
              </div>
            </div>

            {/* Details */}
            <div className="lg:col-span-5 lg:sticky lg:top-[100px] self-start">
              <div className="reveal flex items-center gap-2 mb-4">
                <span className="font-sans text-[10px] tracking-widest-2 uppercase text-rose">{catLabel}</span>
                <span className="text-deep/30">·</span>
                <span className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/55">{t('Summer Édition','Édition Été')}</span>
              </div>
              <h1 className="reveal reveal-delay-1 font-display text-deep leading-[0.95]" style={{fontSize:'clamp(38px, 4.4vw, 64px)'}}>{p.name}</h1>
              <div className="reveal reveal-delay-2 mt-3 flex items-center gap-4">
                <span className="font-serif text-deep text-[28px]"><Price amount={priceBase} overrides={priceOv}/></span>
                {p.reviews > 0 && (
                  <div className="flex items-center gap-1 text-rose">
                    {[0,1,2,3,4].map(i => <I.star key={i} className="w-3.5 h-3.5"/>)}
                    <span className="ml-1.5 font-sans text-[12px] text-deep/55 tracking-wider-2">({p.reviews})</span>
                  </div>
                )}
              </div>

              <p className="reveal reveal-delay-3 mt-7 font-sans text-[15px] leading-[1.75] text-deep/75 max-w-[460px]">
                {productDesc}
              </p>

              {/* Color */}
              {p.colors && (
                <div className="reveal reveal-delay-4 mt-9">
                  <div className="flex items-center justify-between mb-3">
                    <h4 className="font-sans text-[11px] tracking-widest-2 uppercase text-deep/60">{t('Color','Couleur')}</h4>
                    <span className="font-serif italic text-deep text-[15px]">{p.colors[colorIx].name}</span>
                  </div>
                  <div className="flex gap-3">
                    {p.colors.map((c, i) => (
                      <button key={i} onClick={() => { setColorIx(i); if (c.image) setMainImg(c.image); }}
                              title={c.name}
                              className={`w-10 h-10 rounded-full transition-all ${colorIx === i ? 'ring-2 ring-offset-2 ring-offset-ivory ring-deep' : 'opacity-70 hover:opacity-100'}`}
                              style={swatchStyle(c)}/>
                    ))}
                  </div>
                </div>
              )}

              {/* Size */}
              <div className="reveal reveal-delay-5 mt-8">
                <div className="flex items-center justify-between mb-3">
                  <h4 className="font-sans text-[11px] tracking-widest-2 uppercase text-deep/60">{t('Size','Taille')}</h4>
                  <button type="button" onClick={() => setGuideOpen(true)} className="ulink font-sans text-[11px] tracking-widest-2 uppercase text-deep/65">{t('Size guide','Guide des tailles')}</button>
                </div>
                <div className="flex gap-2 flex-wrap">
                  {sizeOptions.map(s => (
                    <button key={s} onClick={() => setSize(s)}
                            className={`w-12 h-12 font-sans text-[13px] tracking-wider-2 transition-all
                              ${size === s ? 'bg-deep text-ivory' : 'border border-deep/20 text-deep hover:border-deep'}`}>
                      {s}
                    </button>
                  ))}
                </div>
              </div>

              {/* Qty + add */}
              <div className="reveal reveal-delay-6 mt-8 flex items-stretch gap-3">
                <div className="inline-flex items-center border border-deep/20">
                  <button onClick={() => setQty(Math.max(1, qty-1))} className="w-12 h-14 flex items-center justify-center hover:bg-blush transition-colors"><I.minus className="w-4 h-4"/></button>
                  <span className="w-10 text-center font-sans text-[14px]">{qty}</span>
                  <button onClick={() => setQty(qty+1)} className="w-12 h-14 flex items-center justify-center hover:bg-blush transition-colors"><I.plus className="w-4 h-4"/></button>
                </div>
                <button disabled={soldOut} onClick={() => {
                  if (soldOut) return;
                  for (let i = 0; i < qty; i++) cart.add({id:p.id, name:p.name, price:priceBase, overrides:priceOv, img:p.img, color:p.colors?.[colorIx]?.name, size});
                  cart.setOpen(true);
                }} className={`btn-sweep flex-1 font-sans uppercase tracking-widest-2 text-[12px] py-4 transition-colors flex items-center justify-center gap-2 ${soldOut ? 'bg-deep/40 text-ivory/80 cursor-not-allowed' : 'bg-deep text-ivory hover:bg-rose'}`}>
                  {soldOut ? t('Sold out','Épuisé') : <>{t('Add to bag','Ajouter au panier')} — {fmtRaw(priceOf(priceBase, priceOv) * qty)}</>}
                </button>
                <button onClick={() => cart.toggleWish(p.id)}
                        className={`w-14 h-14 flex items-center justify-center border transition-all
                          ${cart.wishlist.has(p.id) ? 'bg-rose text-ivory border-rose' : 'border-deep/20 text-deep hover:border-deep'}`}>
                  <I.heart filled={cart.wishlist.has(p.id)} className="w-5 h-5"/>
                </button>
              </div>

              {/* Trust strip */}
              <div className="reveal reveal-delay-7 mt-8 border-t border-deep/10 pt-6 grid grid-cols-3 gap-4">
                {[
                  ['✿', t('Hand-picked','Sélection soignée')],
                  ['✦', t('Curated edit','Édit sélectionné')],
                  ['◆', t('Limited stock','Stock limité')],
                ].map(([icon, label]) => (
                  <div key={label} className="text-center">
                    <div className="font-display text-rose text-[20px] leading-none mb-1.5">{icon}</div>
                    <div className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/65">{label}</div>
                  </div>
                ))}
              </div>

              {/* Tabs */}
              <div className="mt-10 border-t border-deep/10 pt-6">
                <div className="flex gap-6 mb-4">
                  {Object.keys(TAB_LABELS).map(k => (
                    <button key={k} onClick={() => setTab(k)}
                            className={`font-sans text-[11px] tracking-widest-2 uppercase pb-2 border-b transition-all
                              ${tab === k ? 'text-deep border-deep' : 'text-deep/50 border-transparent hover:text-deep'}`}>
                      {TAB_LABELS[k]}
                    </button>
                  ))}
                </div>
                <p className="font-sans text-[14px] leading-[1.75] text-deep/70 animate-fade-in" key={tab + lang}>
                  {TAB_CONTENT[tab]}
                </p>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* You may also love */}
      {related.length > 0 && (
        <section className="bg-champagne/40">
          <div className="max-w-[1440px] mx-auto px-6 md:px-10 py-20 md:py-24">
            <div className="flex flex-col items-center text-center mb-12">
              <div className="reveal"><Eyebrow>{t('Pair it with','À associer avec')}</Eyebrow></div>
              <h2 className="reveal reveal-delay-1 font-display text-deep mt-5 leading-[0.95]" style={{fontSize:'clamp(30px, 3.8vw, 52px)'}}>{t('You may also love','Vous aimerez aussi')}</h2>
            </div>
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-x-5 gap-y-12 md:gap-x-7">
              {related.map((rp, i) => <ProductCard key={rp.id} p={rp} idx={i} reveal={false}/>)}
            </div>
          </div>
        </section>
      )}

      {/* Universal size guide */}
      {guideOpen && (
        <div onClick={() => setGuideOpen(false)} style={{ position:'fixed', inset:0, zIndex:300, background:'rgba(74,45,51,0.5)', display:'flex', alignItems:'center', justifyContent:'center', padding:'1rem' }}>
          <div onClick={(e) => e.stopPropagation()} style={{ background:'#FFF8F5', maxWidth:540, width:'100%', borderRadius:6, padding:'1.75rem', boxShadow:'0 24px 70px rgba(74,45,51,0.3)' }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
              <div>
                <div style={{ fontSize:11, letterSpacing:'0.2em', textTransform:'uppercase', color:'rgba(74,45,51,0.55)' }}>{t('Size guide','Guide des tailles')}</div>
                <h3 style={{ fontFamily:'Italiana, serif', fontSize:24, color:'#4A2D33', margin:'4px 0 0' }}>{t('Find your fit','Trouvez votre taille')}</h3>
              </div>
              <button onClick={() => setGuideOpen(false)} style={{ background:'none', border:'none', fontSize:24, lineHeight:1, cursor:'pointer', color:'rgba(74,45,51,0.5)' }}>×</button>
            </div>
            <p style={{ fontSize:13, color:'rgba(74,45,51,0.65)', margin:'8px 0 16px' }}>{t('Measurements in centimetres. If you are between sizes, we recommend sizing up.','Mesures en centimètres. Entre deux tailles, nous conseillons la taille au-dessus.')}</p>
            <table style={{ width:'100%', borderCollapse:'collapse', fontSize:13, color:'#4A2D33' }}>
              <thead>
                <tr style={{ textAlign:'left', borderBottom:'1px solid rgba(74,45,51,0.2)' }}>
                  <th style={{ padding:'8px 6px' }}>{t('Size','Taille')}</th>
                  <th style={{ padding:'8px 6px' }}>{t('Bust','Poitrine')}</th>
                  <th style={{ padding:'8px 6px' }}>{t('Waist','Taille')}</th>
                  <th style={{ padding:'8px 6px' }}>{t('Hips','Hanches')}</th>
                </tr>
              </thead>
              <tbody>
                {[
                  ['XS','78–82','60–64','86–90'],
                  ['S','82–86','64–68','90–94'],
                  ['M','86–90','68–72','94–98'],
                  ['L','90–95','72–78','98–103'],
                  ['XL','95–100','78–84','103–109'],
                ].map((row) => (
                  <tr key={row[0]} style={{ borderBottom:'1px solid rgba(74,45,51,0.08)' }}>
                    <td style={{ padding:'9px 6px', fontWeight:600 }}>{row[0]}</td>
                    <td style={{ padding:'9px 6px' }}>{row[1]}</td>
                    <td style={{ padding:'9px 6px' }}>{row[2]}</td>
                    <td style={{ padding:'9px 6px' }}>{row[3]}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            <p style={{ fontSize:11, color:'rgba(74,45,51,0.5)', marginTop:14 }}>{t('A general guide — fit can vary slightly by piece.','Un guide général — la coupe peut varier légèrement selon la pièce.')}</p>
          </div>
        </div>
      )}
    </>
  );
}

/* ───────────── ABOUT ───────────── */
function AboutPage() {
  const { t, lang } = useLang();
  const ROLE_FR = { Studio: 'Studio', Operations: 'Opérations', Office: 'Bureau', Atelier: 'Atelier' };
  const NOTE_FR = {
    'Where it all began — 2025.': 'Là où tout a commencé — 2025.',
    'Serving our North American community.': 'Au service de notre communauté nord-américaine.',
    'Part of our team, behind the scenes.': 'Une partie de notre équipe, en coulisses.',
  };
  const trRole = (r) => (lang === 'fr' ? (ROLE_FR[r] || r) : r);
  const trNote = (n) => (lang === 'fr' ? (NOTE_FR[n] || n) : n);
  const VALUES = [
    { id: '01', title: t('Curated selection', 'Sélection pointue'), description: t('Every piece is hand-picked. We edit so you don’t have to.', 'Chaque pièce est choisie à la main. Nous sélectionnons pour vous.') },
    { id: '02', title: t('Elevated quality', 'Qualité élevée'), description: t('Silk, linen, cashmere — fabrics that breathe, drape, and live with you.', 'Soie, lin, cachemire — des matières qui respirent, drapent et vous accompagnent.') },
    { id: '03', title: t('Feminine by design', 'Féminin par essence'), description: t('Soft silhouettes and refined details, chosen for how they make you feel.', 'Des silhouettes douces et des détails raffinés, choisis pour ce qu’ils vous inspirent.') },
    { id: '04', title: t('A quiet ethos', 'Une approche discrète'), description: t('No trends, no noise. We select for the woman, not the season.', 'Pas de tendances, pas de bruit. Nous sélectionnons pour la femme, pas pour la saison.') },
  ];
  return (
    <>
      <PageHero
        eyebrow={t('The boutique', 'La boutique')}
        title={
          <>
            {t('Quietly made,', 'Pensée avec soin,')}
            <br />
            <em className="italic font-serif font-light">{t('always intentional.', 'toujours avec intention.')}</em>
          </>
        }
        subtitle={t(
          'House of Sheylas is an independent womenswear boutique — a curated edit of feminine, elevated pieces selected for women who dress for themselves.',
          'House of Sheylas est une boutique de mode féminine indépendante — une sélection de pièces féminines et raffinées, choisies pour les femmes qui s’habillent pour elles.'
        )}
        crumbs={[{ label: t('Home', 'Accueil'), href: '#home' }, { label: t('About', 'À propos') }]}
        tone="ivory"
        tall
      />

      <section className="bg-ivory">
        <div className="max-w-[1440px] mx-auto px-6 md:px-10 py-14 md:py-20">
          <div className="text-center mb-12">
            <div className="reveal"><Eyebrow>{t('What we believe', 'Ce que nous croyons')}</Eyebrow></div>
            <h2 className="reveal reveal-delay-1 font-display text-deep mt-5 leading-[0.95]" style={{ fontSize: 'clamp(32px, 4.2vw, 60px)' }}>
              {t('Our values', 'Nos valeurs')}
            </h2>
          </div>
          <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-8 lg:gap-10">
            {VALUES.map((value, index) => (
              <div key={value.id} className={`reveal reveal-delay-${index + 1}`}>
                <div className="font-display text-rose text-[42px] leading-none">{value.id}</div>
                <div className="h-px w-12 bg-deep/20 my-5" />
                <h3 className="font-serif text-deep text-[24px] leading-tight">{value.title}</h3>
                <p className="font-sans text-[14px] leading-[1.75] text-deep/65 mt-3">{value.description}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      <section className="bg-blush relative overflow-hidden">
        <div
          className="pointer-events-none absolute -top-32 -right-32 w-[520px] h-[520px] rounded-full opacity-50"
          style={{ background: 'radial-gradient(closest-side, #F8E4E7, transparent 70%)' }}
        />
        <div className="relative max-w-[1440px] mx-auto px-6 md:px-10 py-14 md:py-20">
          <div className="text-center mb-12">
            <div className="reveal"><Eyebrow>{t('Where we are', 'Nos présences')}</Eyebrow></div>
            <h2 className="reveal reveal-delay-1 font-display text-deep mt-5 leading-[0.95]" style={{ fontSize: 'clamp(32px, 4.2vw, 60px)' }}>
              {t('Three places,', 'Trois lieux,')} <em className="italic font-serif font-light">{t('one team.', 'une équipe.')}</em>
            </h2>
          </div>
          <div className="grid md:grid-cols-3 gap-6 md:gap-8 max-w-[1000px] mx-auto">
            {LOCATIONS.map((place, index) => (
              <div key={place.city} className={`reveal reveal-delay-${index + 1} bg-ivory rounded-sm p-8 md:p-10 shadow-soft`}>
                <div className="font-sans text-[10px] tracking-widest-2 uppercase text-rose">{trRole(place.role)}</div>
                <div className="font-display text-deep text-[48px] leading-none mt-3">{place.city}</div>
                <div className="h-px w-10 bg-deep/15 my-5" />
                <p className="font-sans text-[14px] leading-relaxed text-deep/65">{trNote(place.note)}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      <Newsletter />
    </>
  );
}

/* ───────────── CONTACT ───────────── */
function ContactPage() {
  const { t } = useLang();
  const [form, setForm] = useState({ name:'', email:'', subject:'general', message:'' });
  const [state, setState] = useState('idle'); // idle | sending | sent | error
  const [touched, setTouched] = useState({});

  const valid = {
    name:    form.name.trim().length >= 2,
    email:   /^\S+@\S+\.\S+$/.test(form.email),
    message: form.message.trim().length >= 8,
  };
  const allValid = Object.values(valid).every(Boolean);

  const submit = async (e) => {
    e.preventDefault();
    setTouched({ name:true, email:true, message:true });
    if (!allValid) return setState('error');
    setState('sending');
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: form.name, email: form.email, subject: form.subject, message: form.message }),
      });
      const data = await res.json();
      if (data.ok) {
        setState('sent');
      } else {
        setState('error');
      }
    } catch {
      setState('error');
    }
  };

  const onField = (id, v) => setForm({...form, [id]: v});
  const onBlur  = (id) => setTouched({...touched, [id]: true});
  const fieldCls = (id) => `lux-input ${touched[id] && !valid[id] ? '!border-rose' : ''}`;

  return (
    <>
      <PageHero
        eyebrow={CONTACT_CONTENT.eyebrow}
        title={<>{CONTACT_CONTENT.title} <em className="italic font-serif font-light">{CONTACT_CONTENT.accent}</em></>}
        subtitle={CONTACT_CONTENT.subtitle}
        crumbs={[{label:t('Home','Accueil'), href:'#home'}, {label:t('Contact','Contact')}]}
        tone="champagne"
      />

      <section className="bg-ivory">
        <div className="max-w-[1440px] mx-auto px-6 md:px-10 py-16 md:py-24 grid lg:grid-cols-12 gap-12">
          {/* Form */}
          <div className="lg:col-span-7">
            <div className="reveal"><Eyebrow>{t('Send us a note','Écrivez-nous')}</Eyebrow></div>
            <h2 className="reveal reveal-delay-1 font-display text-deep mt-5 leading-[0.95]" style={{fontSize:'clamp(30px, 3.8vw, 52px)'}}>
              {t('Write to us','Écrivez-nous')}
            </h2>

            {state === 'sent' ? (
              <div className="reveal reveal-delay-2 mt-10 bg-blush p-10 rounded-sm text-center animate-scale-in">
                <div className="w-14 h-14 rounded-full bg-rose flex items-center justify-center mx-auto mb-5">
                  <I.check className="w-7 h-7 text-ivory"/>
                </div>
                <div className="font-display text-deep text-[36px] leading-tight">{t('Thank you,','Merci,')} {form.name.split(' ')[0]}.</div>
                <p className="font-sans text-[14px] text-deep/65 mt-3 max-w-[420px] mx-auto">
                  {t('Your message is on its way to our team. We’ll be in touch shortly at','Votre message est en route vers notre équipe. Nous reviendrons vers vous sous peu à')} <span className="text-deep">{form.email}</span>.
                </p>
                <div className="mt-7">
                  <Button variant="ghost" onClick={() => { setForm({name:'', email:'', subject:'general', message:''}); setTouched({}); setState('idle'); }}>
                    {t('Send another message','Envoyer un autre message')}
                  </Button>
                </div>
              </div>
            ) : (
              <form onSubmit={submit} className="reveal reveal-delay-2 mt-10 grid grid-cols-1 md:grid-cols-2 gap-x-8 gap-y-8 max-w-[640px]">
                <label className="block">
                  <span className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/60">{t('Your name','Votre nom')}</span>
                  <input value={form.name} onChange={e => onField('name', e.target.value)} onBlur={() => onBlur('name')} className={fieldCls('name')}/>
                  {touched.name && !valid.name && <span className="block font-sans text-[11px] text-rose mt-1">{t('Required.','Champ 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 => onField('email', e.target.value)} onBlur={() => onBlur('email')} className={fieldCls('email')}/>
                  {touched.email && !valid.email && <span className="block font-sans text-[11px] text-rose mt-1">{t('Please enter a valid email.','Veuillez saisir un email valide.')}</span>}
                </label>
                <div className="md:col-span-2">
                  <span className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/60">{t('Subject','Sujet')}</span>
                  <div className="flex flex-wrap gap-2 mt-3">
                    {[
                      ...CONTACT_CONTENT.topics,
                    ].map((topic) => (
                      <button key={topic.id} type="button" onClick={() => setForm({...form, subject:topic.id})}
                              className={`font-sans text-[11px] tracking-widest-2 uppercase px-4 py-2 rounded-full border transition-all
                                ${form.subject === topic.id ? 'bg-deep text-ivory border-deep' : 'bg-transparent text-deep border-deep/20 hover:border-deep'}`}>
                        {topic.label}
                      </button>
                    ))}
                  </div>
                </div>
                <label className="block md:col-span-2">
                  <span className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/60">{t('Message','Message')}</span>
                  <textarea value={form.message} onChange={e => onField('message', e.target.value)} onBlur={() => onBlur('message')} rows={4} className={fieldCls('message')}/>
                  {touched.message && !valid.message && <span className="block font-sans text-[11px] text-rose mt-1">{t('Please share a few words.','Quelques mots, s’il vous plaît.')}</span>}
                </label>
                <div className="md:col-span-2 flex items-center justify-between gap-4 pt-3">
                  <span className="font-sans text-[11px] text-deep/55 tracking-wider-2">{CONTACT_CONTENT.responseTime}</span>
                  <Button variant="primary" type="submit" disabled={state==='sending'}>
                    {state === 'sending' ? t('Sending…','Envoi…') : <>{t('Send message','Envoyer')} <I.arrowR className="w-4 h-4"/></>}
                  </Button>
                </div>
              </form>
            )}
          </div>

          {/* Info column */}
          <div className="lg:col-span-5 lg:pl-8">
            <div className="reveal bg-blush rounded-sm p-8 md:p-10 shadow-soft">
              <div className="font-display text-deep text-[34px] leading-tight">{t('Where to find us','Où nous trouver')}</div>
              <div className="space-y-7 mt-7">
                {LOCATIONS.map((location) => (
                  <div key={location.city} className="border-t border-deep/15 pt-5 first:border-t-0 first:pt-0">
                    <div className="font-serif text-deep text-[22px]">{location.city}</div>
                    <div className="font-sans text-[11px] tracking-widest-2 uppercase text-deep/55 mt-1">{location.role}</div>
                    <div className="font-sans text-[14px] text-deep/70 mt-2">{location.note}</div>
                  </div>
                ))}
              </div>
              <div className="border-t border-deep/15 mt-7 pt-6 space-y-2">
                <div className="font-sans text-[14px] text-deep/80"><span className="text-deep/55">{t('Care','Service')} · </span>{SITE_SETTINGS.supportEmail}</div>
                <div className="font-sans text-[14px] text-deep/80"><span className="text-deep/55">{t('Press','Presse')} · </span>{SITE_SETTINGS.pressEmail}</div>
              </div>
            </div>

            {/* FAQ */}
            <div className="reveal reveal-delay-2 mt-10">
              <h3 className="font-display text-deep text-[28px] leading-tight">{t('Quick answers','Réponses rapides')}</h3>
              <div className="mt-5 divide-y divide-deep/10">
                {CONTACT_CONTENT.faqs.map((faq, index) => <FAQItem key={`${faq.q}-${index}`} q={faq.q} a={faq.a} />)}
              </div>
            </div>
          </div>
        </div>
      </section>
    </>
  );
}

function FAQItem({ q, a }) {
  const [open, setOpen] = useState(false);
  return (
    <div className="py-4">
      <button onClick={() => setOpen(!open)} className="w-full flex items-center justify-between gap-4 text-left group">
        <span className="font-serif text-deep text-[18px] leading-tight group-hover:text-rose transition-colors">{q}</span>
        <span className={`w-7 h-7 rounded-full border border-deep/20 flex items-center justify-center transition-transform duration-300 ${open ? 'rotate-45 bg-deep text-ivory border-deep' : 'text-deep'}`}>
          <I.plus className="w-3.5 h-3.5"/>
        </span>
      </button>
      <div className={`grid transition-all duration-500 ${open ? 'grid-rows-[1fr] opacity-100 mt-3' : 'grid-rows-[0fr] opacity-0'}`}>
        <div className="overflow-hidden">
          <p className="font-sans text-[14px] leading-[1.75] text-deep/70 pr-8">{a}</p>
        </div>
      </div>
    </div>
  );
}

/* ───────────── ORDER TRACKING ───────────── */
function OrderTrackingPage({ prefillOrder }) {
  const { t } = useLang();
  const [orderNum, setOrderNum] = useState(prefillOrder || '');
  const [email,    setEmail]    = useState('');
  const [state,    setState]    = useState('idle'); // idle | loading | found | error
  const [order,    setOrder]    = useState(null);
  const [errorMsg, setErrorMsg] = useState('');

  const STEPS = ['pending', 'paid', 'shipped', 'fulfilled'];
  const STEP_LABELS = {
    pending:   t('Order received',       'Commande reçue'),
    paid:      t('Payment confirmed',    'Paiement confirmé'),
    shipped:   t('Shipped',              'Expédiée'),
    fulfilled: t('Delivered',            'Livrée'),
  };

  const search = async (e) => {
    e.preventDefault();
    if (!orderNum.trim() || !email.trim()) return;
    setState('loading');
    try {
      const res  = await fetch(`/api/orders/${encodeURIComponent(orderNum.trim())}?email=${encodeURIComponent(email.trim())}`);
      const data = await res.json();
      if (data.ok) { setOrder(data.order); setState('found'); }
      else         { setErrorMsg(data.error || t('Order not found.','Commande introuvable.')); setState('error'); }
    } catch {
      setErrorMsg(t('Network error — please try again.','Erreur réseau — veuillez réessayer.'));
      setState('error');
    }
  };

  const stepIndex = order ? STEPS.indexOf(order.status) : -1;

  return (
    <>
      <PageHero
        eyebrow={t('Order tracking','Suivi de commande')}
        title={t('Track your order','Suivez votre commande')}
        subtitle={t('Enter your order number and email to see delivery status.','Saisissez votre numéro de commande et votre email pour voir le statut de livraison.')}
        crumbs={[{ label:t('Home','Accueil'), href:'#home' }, { label:t('Track','Suivi') }]}
        tone="champagne"
      />

      <section className="bg-ivory">
        <div className="max-w-[1440px] mx-auto px-6 md:px-10 py-16 md:py-24">
          <div className="max-w-[560px] mx-auto">
            {state !== 'found' && (
              <form onSubmit={search} className="space-y-6">
                <label className="block">
                  <span className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/60">{t('Order number','Numéro de commande')}</span>
                  <input value={orderNum} onChange={e => setOrderNum(e.target.value)} className="lux-input" placeholder="HOS-123456"/>
                </label>
                <label className="block">
                  <span className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/60">{t('Email used at checkout','Email utilisé lors de la commande')}</span>
                  <input type="email" value={email} onChange={e => setEmail(e.target.value)} className="lux-input" placeholder="sophie@example.com"/>
                </label>
                {state === 'error' && (
                  <div className="font-sans text-[13px] text-rose">{errorMsg}</div>
                )}
                <Button type="submit" variant="primary" className="w-full" disabled={state === 'loading'}>
                  {state === 'loading' ? t('Searching…','Recherche…') : <>{t('Track order','Suivre la commande')} <I.arrowR className="w-4 h-4"/></>}
                </Button>
              </form>
            )}

            {state === 'found' && order && (
              <div className="space-y-8 animate-fade-in">
                <div className="flex items-center justify-between">
                  <div>
                    <div className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/55">{t('Order','Commande')}</div>
                    <div className="font-display text-deep text-[32px] leading-tight">{order.order_number}</div>
                  </div>
                  <Button variant="ghost" onClick={() => { setState('idle'); setOrder(null); }}>
                    {t('New search','Nouvelle recherche')}
                  </Button>
                </div>

                {/* Status timeline */}
                <div className="bg-blush/40 px-6 py-6">
                  <div className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/55 mb-5">{t('Delivery status','Statut de livraison')}</div>
                  <ol className="space-y-4">
                    {STEPS.map((step, i) => {
                      const done = i <= stepIndex;
                      return (
                        <li key={step} className="flex items-center gap-4">
                          <span className={`w-7 h-7 rounded-full flex items-center justify-center flex-none font-sans text-[11px] transition-colors
                            ${done ? 'bg-rose text-ivory' : 'bg-deep/10 text-deep/40'}`}>
                            {done ? '✓' : i + 1}
                          </span>
                          <span className={`font-sans text-[13px] tracking-wider-2 ${done ? 'text-deep' : 'text-deep/40'}`}>
                            {STEP_LABELS[step]}
                          </span>
                        </li>
                      );
                    })}
                  </ol>
                </div>

                {/* Items */}
                {order.order_items?.length > 0 && (
                  <div>
                    <div className="font-sans text-[10px] tracking-widest-2 uppercase text-deep/55 mb-4">{t('Items','Articles')}</div>
                    <ul className="divide-y divide-deep/10">
                      {order.order_items.map(item => (
                        <li key={item.id} className="py-3 flex items-center justify-between gap-3">
                          <div>
                            <div className="font-serif text-deep text-[15px]">{item.product_name}</div>
                            {(item.variant_color || item.variant_size) && (
                              <div className="font-sans text-[11px] text-deep/55 mt-0.5 uppercase tracking-wider-2">
                                {[item.variant_color, item.variant_size].filter(Boolean).join(' · ')}
                              </div>
                            )}
                          </div>
                          <div className="font-sans text-[13px] text-deep tracking-wider-2 flex-none">
                            × {item.quantity} — {item.total} {order.currency || ''}
                          </div>
                        </li>
                      ))}
                    </ul>
                    <div className="flex justify-between mt-4 pt-4 border-t border-deep/10">
                      <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">{order.total} {order.currency || ''}</span>
                    </div>
                  </div>
                )}

                <div className="font-sans text-[12px] text-deep/55 leading-relaxed">
                  {t('Questions? Contact us at','Des questions ? Contactez-nous à')}{' '}
                  <a href="#contact" className="text-rose hover:underline">{t('our support page','notre page support')}</a>.
                </div>
              </div>
            )}
          </div>
        </div>
      </section>
    </>
  );
}

/* ───────────── 404 ───────────── */
function NotFoundPage() {
  const { t } = useLang();
  return (
    <section className="bg-blush min-h-[70vh] flex items-center justify-center text-center px-6 py-24">
      <div>
        <div className="font-display text-deep text-[120px] md:text-[200px] leading-none">404</div>
        <p className="font-serif italic text-deep/65 text-[22px] mt-3">{t('This page seems to have wandered off.','Cette page semble s’être égarée.')}</p>
        <div className="mt-8"><Button as="a" href="#home" variant="primary">{t('Return home','Retour à l’accueil')}</Button></div>
      </div>
    </section>
  );
}

Object.assign(window, {
  PageHero, ShopPage, CollectionsPage, ProductPage, AboutPage, ContactPage, NotFoundPage, OrderTrackingPage,
});
