const TornPaperC = props => React.createElement(QDS().TornPaper, props);
function Header({ count, onCart }) {
  const [hidden, setHidden] = React.useState(false), [solid, setSolid] = React.useState(false), [menu, setMenu] = React.useState(false);
  React.useEffect(() => { let last = 0; const f = () => { const y = scrollY; setHidden(y > last && y > 400 && !menu); setSolid(y > 60); last = y; }; addEventListener('scroll', f, { passive: true }); return () => removeEventListener('scroll', f); }, [menu]);
  const nav = [['Boutique', 'boutique'], ['Univers', 'univers'], ['Notre histoire', 'histoire'], ['Nous rendre visite', 'visite']];
  const { Icon } = QDS();
  return <header className={'hdr' + (hidden ? ' hide' : '') + (solid ? ' solid' : '')}>
    <div className="hdr-in">
      <a onClick={() => scrollTo({ top: 0, behavior: 'smooth' })} className="hdr-logo" aria-label="Accueil"><AnimatedLogo></AnimatedLogo></a>
      <nav className="hdr-nav">{nav.map(([l, id], i) => <a key={id} onClick={() => go(id)} style={{ '--r': (i % 2 ? 3 : -3) + 'deg' }}>{l}</a>)}</nav>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <button className="cart-btn" onClick={onCart} aria-label="Panier"><Icon name="shopping-bag" size={18} color="var(--q-creme)"></Icon><span className="hide-sm">Panier</span><b key={count} className="cart-count">{count}</b></button>
        <button className="burger" onClick={() => setMenu(!menu)} aria-label="Menu"><Icon name={menu ? 'x' : 'menu'} size={22} color={KEY}></Icon></button>
      </div>
    </div>
    {menu && <div className="mob-menu">{nav.map(([l, id]) => <a key={id} onClick={() => { setMenu(false); go(id); }}>{l}</a>)}</div>}
  </header>;
}

function Shop({ liked, onLike, onOpen, onAdd }) {
  const { ProductCard } = QDS();
  const [cat, setCat] = React.useState('Tous');
  const cats = ['Tous', 'Bijoux', 'Accessoires', 'Vêtements'];
  const list = PRODUCTS.filter(p => cat === 'Tous' || p.cat === cat);
  return <section id="boutique" className="layer shop" data-screen-label="Boutique en ligne">
    <div className="wrap">
      <div className="shop-head">
        <div><Eyebrow>Boutique en ligne</Eyebrow><h2 className="h2 cream"><Words text="Nouveautés"></Words></h2><div className="script pink">Nouvelle Collection</div></div>
        <div className="filters" role="tablist">{cats.map(c => <button key={c} role="tab" aria-selected={cat === c} className={'pick' + (cat === c ? ' on' : '')} onClick={() => vt(() => ReactDOM.flushSync(() => setCat(c)))}>{c}</button>)}</div>
      </div>
      <div className="shop-grid">{list.map((p, i) => <div key={p.id} className="prod" style={{ viewTransitionName: 'p-' + p.id, '--i': i, '--tilt': ([-2, 1.5, -1, 2.2][i % 4]) + 'deg' }} data-reveal="">
        <Paper n={i % 2 ? 9 : 19} style={{ padding: '12px 12px 16px' }}>
          <div style={{ padding: '12px 12px 16px' }}>
            <ProductCard image={p.img} name={p.name} category={p.brand} price={euro(p.price)} oldPrice={p.old ? euro(p.old) : undefined} badge={p.badge} badgeVariant={p.bv} bg="var(--q-petal)" liked={!!liked[p.id]} onLike={() => onLike(p.id)} onClick={() => onOpen(p)}></ProductCard>
            <button className="quick-add" onClick={() => onAdd(p)}>Ajouter au panier</button>
          </div>
        </Paper>
      </div>)}</div>
    </div>
  </section>;
}

function QuickView({ p, onClose, onAdd }) {
  const { Button, IconButton, Badge } = QDS();
  if (!p) return null;
  return <div className="scrim" onClick={onClose}>
    <div className="qv" onClick={e => e.stopPropagation()}>
      <TornPaperC color="var(--q-creme)" seed={33} depth={12} padding="clamp(20px,3vw,34px)">
        <button className="x" onClick={onClose} aria-label="Fermer">×</button>
        <div className="qv-grid">
          <div className="qv-img"><img src={p.img} alt={p.name}></img></div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <Eyebrow color="var(--q-fuchsia)">{p.cat} · {p.brand}</Eyebrow>
            <h3 className="h2" style={{ color: KEY, margin: 0 }}>{p.name}</h3>
            <div style={{ font: '600 22px var(--font-sub)', color: KEY }}>{euro(p.price)} {p.old && <s style={{ opacity: .5, fontWeight: 400, fontSize: 16 }}>{euro(p.old)}</s>}</div>
            <p className="body">{p.desc}</p>
            <Button size="lg" iconRight="arrow-right" onClick={() => { onAdd(p); onClose(); }}>Ajouter au panier</Button>
            <p className="body" style={{ fontSize: 14, opacity: .8 }}>Retrait gratuit en boutique, 68 rue Mirebeau · Emballage cadeau offert</p>
          </div>
        </div>
      </TornPaperC>
    </div>
  </div>;
}

function CartDrawer({ open, items, onClose, setQty }) {
  const { Button } = QDS();
  const total = items.reduce((s, it) => s + it.p.price * it.q, 0);
  return <div className={'drawer-wrap' + (open ? ' open' : '')} onClick={onClose} aria-hidden={!open}>
    <aside className="drawer" onClick={e => e.stopPropagation()}>
      <div className="drawer-in">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><h3 className="h3" style={{ margin: 0 }}>Votre panier</h3><button className="x static" onClick={onClose} aria-label="Fermer">×</button></div>
        {!items.length && <div className="empty"><img src="assets/elements/01_fleur.svg" alt="" className="spin-slow" width="80"></img><p className="body">Votre panier est vide.</p></div>}
        <div className="lines">{items.map(it => <div key={it.p.id} className="line">
          <img src={it.p.img} alt=""></img>
          <div style={{ flex: 1 }}><div style={{ font: '400 18px/1.2 var(--font-display)', color: KEY }}>{it.p.name}</div><div className="u-k" style={{ marginTop: 4 }}>{it.p.brand}</div>
            <div className="qty"><button onClick={() => setQty(it.p.id, it.q - 1)}>−</button><span>{it.q}</span><button onClick={() => setQty(it.p.id, it.q + 1)}>+</button></div></div>
          <b style={{ color: KEY, font: '600 15px var(--font-sub)' }}>{euro(it.p.price * it.q)}</b>
        </div>)}</div>
        {!!items.length && <div className="sum">
          <div style={{ display: 'flex', justifyContent: 'space-between', font: '600 18px var(--font-sub)', color: KEY }}><span>Sous-total</span><span>{euro(total)}</span></div>
          <Button size="lg" fullWidth iconRight="arrow-right">Commander</Button>
          <p className="body" style={{ fontSize: 13, textAlign: 'center' }}>Paiement sécurisé · Retrait en boutique ou livraison</p>
        </div>}
      </div>
    </aside>
  </div>;
}

function JewelPanel({ jewel, onPick }) {
  const [open, setOpen] = React.useState(false);
  const models = (window.QJewel && window.QJewel.models) || [];
  return <div className={'jp' + (open ? ' open' : '')}>
    <button className="jp-btn" onClick={() => setOpen(!open)}><img src="assets/elements/02_etoile.svg" alt="" className="spin-slow" width="22"></img>Choisir le bijou 3D</button>
    <div className="jp-panel">
      <Paper n={10} style={{ padding: '26px 26px 28px' }}>
        <div style={{ padding: '22px 24px 26px' }}>
          <Eyebrow color="var(--q-fuchsia)">Bijou affiché sur le site</Eyebrow>
          <div className="jp-list">{models.map((m, i) => <button key={m.id} className={'jp-item' + (jewel === m.id ? ' on' : '')} onClick={() => onPick(m.id)}><span className="jp-n">0{i + 1}</span>{m.label}{jewel === m.id && <span className="jp-ok">Choisi</span>}</button>)}</div>
          <p className="body" style={{ fontSize: 13, margin: '12px 0 0' }}>Le choix est mémorisé et s'affiche dans l'accueil et le manifeste.</p>
        </div>
      </Paper>
    </div>
  </div>;
}

function Legal({ open, onClose }) {
  if (!open) return null;
  const rows = [['Éditeur du site', 'Entreprise AUBAILLY (EURL)'], ['Enseigne commerciale', 'QUINTESCENCE'], ['Siège social', '68 Rue Mirebeau, 18000 Bourges'], ['Capital social', '3 000,00 €'], ['Immatriculation', 'RCS Bourges n° 978 297 414'], ['SIRET', '978 297 414 00010'], ['TVA Intracommunautaire', 'FR17978297414'], ['Directrice de la publication', 'Morgane Aubailly (Gérante)'], ['Hébergeur', 'À renseigner']];
  return <div className="scrim" onClick={onClose}><div className="qv" style={{ maxWidth: 640 }} onClick={e => e.stopPropagation()}>
    <TornPaperC color="var(--q-creme)" seed={52} depth={12} padding="34px">
      <button className="x" onClick={onClose} aria-label="Fermer">×</button>
      <h3 className="h3">Mentions légales</h3>
      <dl className="legal">{rows.map(([k, v]) => <React.Fragment key={k}><dt>{k}</dt><dd>{v}</dd></React.Fragment>)}</dl>
    </TornPaperC>
  </div></div>;
}

function Intro({ onDone }) {
  const v = React.useRef(null);
  const [out, setOut] = React.useState(false), [playing, setPlaying] = React.useState(false), [muted, setMuted] = React.useState(true), [vol, setVol] = React.useState(1), [t, setT] = React.useState(0), [d, setD] = React.useState(0);
  const end = () => { if (out) return; setOut(true); setTimeout(onDone, 1000); };
  React.useEffect(() => { const el = v.current; if (!el) return; el.muted = true; el.play().then(() => setPlaying(true)).catch(() => setPlaying(false)); }, []);
  const toggle = () => { const el = v.current; if (el.paused) { el.play(); setPlaying(true); } else { el.pause(); setPlaying(false); } };
  const setMute = m => { const el = v.current; el.muted = m; setMuted(m); if (!m && el.paused) { el.play(); setPlaying(true); } };
  const fmt = s => Math.floor(s / 60) + ':' + String(Math.floor(s % 60)).padStart(2, '0');
  const seek = e => { const r = e.currentTarget.getBoundingClientRect(); v.current.currentTime = ((e.clientX - r.left) / r.width) * (d || 0); };
  const W = '#FFF8EC';
  return <div className={'intro' + (out ? ' out' : '')}>
    <video ref={v} src="assets/video/logo-animation.mp4" playsInline preload="auto" onTimeUpdate={e => setT(e.target.currentTime)} onLoadedMetadata={e => setD(e.target.duration)} onEnded={end} onClick={toggle}></video>
    {!playing && <button className="iv-big" onClick={toggle} aria-label="Lire la vidéo"><svg width="34" height="34" viewBox="0 0 32 32"><polygon points="11,7 27,16 11,25" fill="#641124"></polygon></svg></button>}
    <div className="iv-bar">
      <div className="iv-track" onClick={seek}><span style={{ width: (d ? t / d * 100 : 0) + '%' }}></span></div>
      <div className="iv-row">
        <button className="iv-btn" onClick={toggle} aria-label={playing ? 'Pause' : 'Lecture'}>{playing ? <svg width="14" height="14" viewBox="0 0 14 14"><rect x="2" y="1" width="3.5" height="12" fill={W}></rect><rect x="8.5" y="1" width="3.5" height="12" fill={W}></rect></svg> : <svg width="14" height="14" viewBox="0 0 14 14"><polygon points="3,1 13,7 3,13" fill={W}></polygon></svg>}</button>
        <button className="iv-btn" onClick={() => setMute(!muted)} aria-label={muted ? 'Activer le son' : 'Couper le son'}><svg width="18" height="18" viewBox="0 0 16 16"><path d="M2 5.5h2.5L8 2.5v11L4.5 10.5H2z" fill={W}></path>{muted ? <path d="M10.5 5.5l4 5M14.5 5.5l-4 5" stroke={W} strokeWidth="1.4" strokeLinecap="round"></path> : <path d="M10 5.5a3 3 0 0 1 0 5M11.8 3.5a5.5 5.5 0 0 1 0 9" stroke={W} strokeWidth="1.3" fill="none" strokeLinecap="round"></path>}</svg></button>
        <input className="iv-vol" type="range" min="0" max="1" step="0.05" value={muted ? 0 : vol} aria-label="Volume" onChange={e => { const x = +e.target.value; setVol(x); v.current.volume = x; setMute(x === 0); }}></input>
        <span className="iv-time">{fmt(t)} / {fmt(d)}</span>
        {muted && <button className="iv-sound" onClick={() => setMute(false)}>Activer le son</button>}
        <button className="iv-skip" onClick={end}>Passer l'intro</button>
      </div>
    </div>
  </div>;
}

function App() {
  const [jewel, setJewel] = React.useState(localStorage.getItem('q-jewel') || 'bague');
  const [, force] = React.useState(0);
  const [cart, setCart] = React.useState(() => { try { return JSON.parse(localStorage.getItem('q-cart') || '[]'); } catch (e) { return []; } });
  const [liked, setLiked] = React.useState({});
  const [qv, setQv] = React.useState(null), [cartOpen, setCartOpen] = React.useState(false), [legal, setLegal] = React.useState(false);
  const [intro, setIntro] = React.useState(true), [toast, setToast] = React.useState(null);
  useScrollEngine([]);
  React.useEffect(() => { loadLogo(); const r = () => force(x => x + 1), c = e => setJewel(e.detail); addEventListener('qjewel:ready', r); addEventListener('qjewel:change', c); if (window.QJewel) r(); return () => { removeEventListener('qjewel:ready', r); removeEventListener('qjewel:change', c); }; }, []);
  React.useEffect(() => { localStorage.setItem('q-cart', JSON.stringify(cart)); }, [cart]);
  const items = cart.map(c => ({ p: PRODUCTS.find(p => p.id === c.id), q: c.q })).filter(x => x.p);
  const add = p => { setCart(c => { const f = c.find(x => x.id === p.id); return f ? c.map(x => x.id === p.id ? { ...x, q: x.q + 1 } : x) : [...c, { id: p.id, q: 1 }]; }); setToast(p.name); clearTimeout(window.__qt); window.__qt = setTimeout(() => setToast(null), 2200); };
  const setQty = (id, q) => setCart(c => q <= 0 ? c.filter(x => x.id !== id) : c.map(x => x.id === id ? { ...x, q } : x));
  const pick = id => { setJewel(id); window.QJewel && window.QJewel.select(id); };
  return <>
    {intro && <Intro onDone={() => setIntro(false)}></Intro>}
    <div className="progress"></div>
    <Header count={items.reduce((s, i) => s + i.q, 0)} onCart={() => setCartOpen(true)}></Header>
    <main>
      <Hero jewel={jewel} onPick={pick}></Hero>
      <div className="layer"><Marquee items={['Bijoux', 'Accessoires', 'Vêtements', 'Bijoux', 'Accessoires', 'Vêtements']}></Marquee></div>
      <Manifeste></Manifeste>
      <Bienvenue></Bienvenue>
      <Univers></Univers>
      <Shop liked={liked} onLike={id => setLiked(l => ({ ...l, [id]: !l[id] }))} onOpen={setQv} onAdd={add}></Shop>
      <Garanties></Garanties>
      <Histoire></Histoire>
      <Visite></Visite>
    </main>
    <Footer onLegal={() => setLegal(true)}></Footer>
    <JewelPanel jewel={jewel} onPick={pick}></JewelPanel>
    <QuickView p={qv} onClose={() => setQv(null)} onAdd={add}></QuickView>
    <CartDrawer open={cartOpen} items={items} onClose={() => setCartOpen(false)} setQty={setQty}></CartDrawer>
    <Legal open={legal} onClose={() => setLegal(false)}></Legal>
    <div className={'toast' + (toast ? ' show' : '')}><img src="assets/elements/02_etoile.svg" alt="" width="20"></img>{toast} ajouté au panier</div>
  </>;
}

ReactDOM.createRoot(document.getElementById('root')).render(<App></App>);
