// Lettres en papier découpé (repris du site « Quintescence Papier v2 »)
const SCRAP_COL = [['var(--q-pink)', 'var(--q-creme)', 'var(--font-display)'], ['var(--q-sunflower)', 'var(--q-bordeaux-chic)', 'var(--font-body)'], ['#fff', 'var(--q-bordeaux-chic)', 'var(--font-display)'], ['var(--q-peach)', 'var(--q-bordeaux-chic)', 'var(--font-display)'], ['var(--q-fuchsia)', 'var(--q-creme)', 'var(--font-display)'], ['var(--q-blush)', 'var(--q-bordeaux-chic)', 'var(--font-body)']];
const SCRAP_CUT = ['polygon(2% 4%,98% 0,100% 96%,0 100%)', 'polygon(0 0,96% 5%,100% 100%,4% 95%)', 'polygon(4% 0,100% 3%,97% 100%,0 94%)'];
function Scraps({ text, as = 'span', className = '', style, base = 0 }) {
  const T = as; let i = 0;
  return <T data-words="" className={'scraps ' + className} style={style} aria-label={text}>{text.split(' ').map((w, wi) => <React.Fragment key={wi}><span className="sw" aria-hidden="true">{[...w].map(ch => {
    const k = i++, c = SCRAP_COL[(k * 7 + ch.charCodeAt(0)) % SCRAP_COL.length];
    return <span key={k} className={'sc' + (c[2] === 'var(--font-body)' ? ' sans' : '')} style={{ background: c[0], color: c[1], fontFamily: c[2], '--r': ((((k * 37) % 13) - 6) * 0.9).toFixed(1) + 'deg', clipPath: SCRAP_CUT[k % 3], '--d': (base + k * 0.035).toFixed(3) + 's', '--hd': (k % 12) * 16 + 'ms', '--fx': ((((k * 53) % 9) - 4) * 0.35).toFixed(2) + 'em', '--fy': (-0.9 - ((k * 29) % 5) * 0.25).toFixed(2) + 'em', '--fr': ((((k * 71) % 11) - 5) * 9) + 'deg', '--r2': ((((k * 37) % 13) - 6) * -0.6).toFixed(1) + 'deg' }}>{ch}</span>;
  })}</span>{' '}</React.Fragment>)}</T>;
}

const fmt = n => n.toFixed(2).replace('.', ',') + ' €';
const PROMOS = { QUINTEZVIP: 15, NOEL2026: 10, BOURGES: 5 };
const shipCost = (type, sub) => type === 'retrait' ? 0 : sub >= 60 ? 0 : type === 'express' ? 9.9 : 4.9;

function useCart() {
  const [cart, setCart] = React.useState(() => { try { return JSON.parse(localStorage.getItem('q2-cart')) || []; } catch (e) { return []; } });
  const [toast, setToast] = React.useState(null);
  const t = React.useRef();
  React.useEffect(() => { localStorage.setItem('q2-cart', JSON.stringify(cart)); }, [cart]);
  const add = p => { setCart(c => c.find(l => l.id === p.id) ? c.map(l => l.id === p.id ? { ...l, qty: l.qty + 1 } : l) : [...c, { id: p.id, qty: 1 }]); setToast({ name: p.name, id: Date.now() }); clearTimeout(t.current); t.current = setTimeout(() => setToast(null), 2800); };
  const qty = (id, d) => setCart(c => c.map(l => l.id === id ? { ...l, qty: Math.max(1, l.qty + d) } : l));
  const remove = id => setCart(c => c.filter(l => l.id !== id));
  const lines = cart.map(l => ({ ...l, p: PIECES.find(x => x.id === l.id) })).filter(l => l.p);
  const count = lines.reduce((t, l) => t + l.qty, 0), sub = lines.reduce((t, l) => t + l.p.price * l.qty, 0);
  return { lines, count, sub, add, qty, remove, clear: () => setCart([]), toast };
}

function CartButton({ count, onClick }) {
  return <button className="cart-btn" onClick={onClick} aria-label={'Panier, ' + count + ' article' + (count > 1 ? 's' : '')}>
    {Ic('shopping-bag', 20, 'var(--q-bordeaux-chic)')}
    {count > 0 && <span key={count} className="cart-badge">{count}</span>}
  </button>;
}

function CartToast({ toast }) {
  const [t, leaving] = useLeave(toast, 180);
  if (!t) return null;
  const name = t.name;
  return <div key={t.id} className={'c-toast' + (leaving ? ' out' : '')} role="status"><Paper n={1} color="var(--q-sunflower)" innerStyle={{ padding: '20px 38px' }}><b>Ajouté au panier</b><span>{name}</span></Paper></div>;
}

// Note de cahier d'écolier déchirée (lignes + marge rouge)
function Cahier({ children, className = '', style }) {
  return <div className={'cahier ' + className} style={style}><div className="cahier-in">{children}</div></div>;
}

function Field({ label, k, form, setForm, ...rest }) {
  return <label className="fld"><span>{label}</span><input value={form[k] || ''} onChange={e => setForm({ ...form, [k]: e.target.value })} {...rest}></input></label>;
}

function CartPage({ cart, onClose, leaving }) {
  const { Button, Tape } = QDS();
  const [step, setStep] = React.useState(0), [form, setForm] = React.useState({ pays: 'FR' }), [ship, setShip] = React.useState('standard');
  const [promo, setPromo] = React.useState(null), [code, setCode] = React.useState(''), [err, setErr] = React.useState(null), [order, setOrder] = React.useState(null);
  const box = React.useRef(null), [gone, setGone] = React.useState(null);
  const removeLine = id => { setGone(id); setTimeout(() => { cart.remove(id); setGone(null); }, 200); };
  React.useEffect(() => { document.documentElement.style.overflow = 'hidden'; const k = e => e.key === 'Escape' && onClose(); addEventListener('keydown', k); return () => { document.documentElement.style.overflow = ''; removeEventListener('keydown', k); }; }, []);
  React.useEffect(() => { if (box.current) box.current.scrollTop = 0; setErr(null); }, [step]);
  const disc = promo && !promo.invalid ? Math.round(cart.sub * promo.pct / 100) : 0;
  const shipping = step >= 2 ? shipCost(ship, cart.sub - disc) : shipCost('standard', cart.sub - disc);
  const total = cart.sub - disc + (cart.sub ? shipping : 0);
  const steps = ['Panier', 'Adresse', 'Livraison', 'Paiement'];
  const next = () => {
    if (step === 1) { for (const [k, l] of [['prenom', 'prénom'], ['nom', 'nom'], ['email', 'e-mail'], ['adresse', 'adresse'], ['cp', 'code postal'], ['ville', 'ville']]) if (!(form[k] || '').trim()) return setErr('Merci de renseigner votre ' + l + '.'); if (!/^\S+@\S+\.\S+$/.test(form.email)) return setErr('Adresse e-mail invalide.'); }
    if (step === 3) {
      const card = (form.card || '').replace(/\s/g, '');
      if (card.length < 13) return setErr('Numéro de carte invalide.');
      if (!/^\d{2}\/\d{2}$/.test(form.exp || '')) return setErr('Date d’expiration invalide (MM/AA).');
      if ((form.cvv || '').length < 3) return setErr('CVV invalide.');
      setOrder({ id: 'Q' + Date.now().toString(36).toUpperCase(), lines: cart.lines, total, email: form.email, ship }); cart.clear(); setStep(4); return;
    }
    setStep(step + 1);
  };
  const applyPromo = () => { const c = code.trim().toUpperCase(); setPromo(PROMOS[c] ? { code: c, pct: PROMOS[c] } : { code: c, invalid: true }); };
  const shipOpts = [['standard', 'Livraison standard', 'Colissimo 2–5 jours', cart.sub - disc >= 60 ? 'Offerte' : '4,90 €'], ['express', 'Livraison express', 'Chronopost J+1', cart.sub - disc >= 60 ? 'Offerte' : '9,90 €'], ['retrait', 'Retrait en boutique', '68 rue Mirebeau, Bourges', 'Gratuit']];

  const Recap = ({ lines, final }) => <Cahier className="recap">
    <div className="ch-title">{final ? 'Votre commande' : 'Récapitulatif'}</div>
    {lines.map(l => <div key={l.id} className="ch-line"><span>{l.qty} × {l.p.name}</span><span>{fmt(l.p.price * l.qty)}</span></div>)}
    <div className="ch-line"><span>Sous-total</span><span>{fmt(final ? lines.reduce((t, l) => t + l.p.price * l.qty, 0) : cart.sub)}</span></div>
    {!final && disc > 0 && <div className="ch-line promo"><span>Code {promo.code} (−{promo.pct} %)</span><span>−{fmt(disc)}</span></div>}
    {!final && <div className="ch-line"><span>Livraison</span><span>{shipping === 0 ? 'Offerte' : fmt(shipping)}</span></div>}
    <div className="ch-line total"><span>Total</span><span>{fmt(final ? order.total : total)}</span></div>
    {!final && step < 4 && <div className="ch-line ch-promo"><input placeholder="Code promo" value={code} onChange={e => setCode(e.target.value)} onKeyDown={e => e.key === 'Enter' && applyPromo()} aria-label="Code promo"></input><button onClick={applyPromo}>OK</button></div>}
    {!final && promo && promo.invalid && <div className="ch-line err"><span>Code invalide</span></div>}
    <div className="ch-sign">Merci de faire partie de notre histoire</div>
  </Cahier>;

  return <div className={'cartpage' + (leaving ? ' out' : '')} ref={box} role="dialog" aria-modal="true" aria-label="Panier">
    <div className="cp-top">
      <img src="assets/logo/quintescence-logo-couleur.svg" alt="Quintescence" className="cp-logo"></img>
      <button className="cp-close" onClick={onClose} aria-label="Continuer mes achats">{Ic('arrow-left', 18, 'var(--q-bordeaux-chic)')}<span>Continuer mes achats</span></button>
    </div>
    <div className="wrap cp-wrap">
      <h1 className="h2 cp-h1"><Scraps text={step === 4 ? 'Merci !' : step === 0 ? 'Mon panier' : 'Commander'} as="span"></Scraps></h1>
      {step > 0 && step < 4 && <ol className="cp-steps">{steps.map((s, i) => <li key={s} className={i === step ? 'on' : i < step ? 'done' : ''}><span>{i < step ? '✓' : i + 1}</span>{s}</li>)}</ol>}

      {step === 4 ? <div className="cp-done">
        <Paper n={12} color="var(--q-creme)" className="cp-form" innerStyle={{ padding: 'clamp(44px,6vw,64px) clamp(38px,5vw,60px)' }}>
          <Eyebrow color="var(--q-fuchsia)">Commande n° {order.id}</Eyebrow>
          <p className="body" style={{ marginTop: 14 }}>Un e-mail de confirmation a été envoyé à <b>{order.email}</b>. {order.ship === 'retrait' ? 'Votre commande vous attend au 68 rue Mirebeau sous 48 h.' : 'Votre commande sera expédiée sous 2 à 3 jours ouvrés.'}</p>
          <div className="row" style={{ marginTop: 24 }}><Button variant="cta" iconRight={Ic('arrow-right', 16, '#fff')} onClick={onClose}>Retour à la boutique</Button></div>
        </Paper>
        <Recap lines={order.lines} final></Recap>
      </div>
      : cart.lines.length === 0 ? <div className="cp-empty"><Cahier><div className="ch-title">Votre panier est vide</div><div className="ch-line"><span>Nos pièces vous attendent en vitrine.</span></div><div className="ch-line"><button className="ch-link" onClick={() => { onClose(); setTimeout(() => go('vitrine'), 60); }}>Voir la vitrine →</button></div></Cahier></div>
      : <div className="cp-grid">
        <div className="cp-main" key={step}>
          {step === 0 && <div className="cp-lines">{cart.lines.map((l, i) => <div key={l.id} className={'cp-line' + (gone === l.id ? ' gone' : '')} style={{ rotate: [-0.8, 0.6, -0.4][i % 3] + 'deg' }}>
            <Paper n={[4, 16, 3][i % 3]} color="var(--q-creme)" innerStyle={{ padding: '28px 40px' }}>
              <div className="cl-in">
                <img src={l.p.img} alt={l.p.name}></img>
                <div className="cl-txt"><div className="piece-brand">{l.p.brand}</div><div className="cl-name">{l.p.name}</div>
                  <div className="qty"><button onClick={() => cart.qty(l.id, -1)} aria-label="Retirer un">−</button><span>{l.qty}</span><button onClick={() => cart.qty(l.id, 1)} aria-label="Ajouter un">+</button></div></div>
                <div className="cl-right"><div className="cl-price">{fmt(l.p.price * l.qty)}</div><button className="cl-rm" onClick={() => removeLine(l.id)}>Retirer</button></div>
              </div>
            </Paper>
          </div>)}
            <div className="row"><Button variant="cta" size="lg" iconRight={Ic('arrow-right', 18, '#fff')} onClick={next}>Passer commande</Button></div>
          </div>}

          {step === 1 && <Paper n={12} color="var(--q-creme)" className="cp-form" innerStyle={{ padding: 'clamp(40px,5vw,60px) clamp(36px,5vw,58px)' }}>
            <Eyebrow color="var(--q-fuchsia)">Adresse de livraison</Eyebrow>
            <div className="fgrid">
              <Field label="Prénom *" k="prenom" form={form} setForm={setForm} autoComplete="given-name"></Field>
              <Field label="Nom *" k="nom" form={form} setForm={setForm} autoComplete="family-name"></Field>
              <Field label="E-mail *" k="email" type="email" form={form} setForm={setForm} autoComplete="email" className="span2"></Field>
              <Field label="Téléphone" k="tel" type="tel" form={form} setForm={setForm} autoComplete="tel"></Field>
              <label className="fld"><span>Pays</span><select value={form.pays} onChange={e => setForm({ ...form, pays: e.target.value })}><option value="FR">France</option><option value="BE">Belgique</option><option value="CH">Suisse</option><option value="LU">Luxembourg</option></select></label>
              <Field label="Adresse *" k="adresse" form={form} setForm={setForm} autoComplete="street-address"></Field>
              <Field label="Code postal *" k="cp" form={form} setForm={setForm} inputMode="numeric" autoComplete="postal-code"></Field>
              <Field label="Ville *" k="ville" form={form} setForm={setForm} autoComplete="address-level2"></Field>
            </div>
          </Paper>}

          {step === 2 && <Paper n={12} color="var(--q-creme)" className="cp-form" innerStyle={{ padding: 'clamp(40px,5vw,60px) clamp(36px,5vw,58px)' }}>
            <Eyebrow color="var(--q-fuchsia)">Mode de livraison</Eyebrow>
            <div className="ship">{shipOpts.map(([id, l, d, p]) => <label key={id} className={'ship-o' + (ship === id ? ' on' : '')}><input type="radio" name="ship" checked={ship === id} onChange={() => setShip(id)}></input><div><b>{l}</b><span>{d}</span></div><em>{p}</em></label>)}</div>
          </Paper>}

          {step === 3 && <Paper n={12} color="var(--q-creme)" className="cp-form" innerStyle={{ padding: 'clamp(40px,5vw,60px) clamp(36px,5vw,58px)' }}>
            <Eyebrow color="var(--q-fuchsia)">Paiement sécurisé</Eyebrow>
            <div className="secure">{Ic('lock', 16, 'var(--q-fuchsia)')}Paiement sécurisé via Stripe · Cryptage SSL 256 bits</div>
            <div className="fgrid">
              <Field label="Numéro de carte" k="card" form={form} setForm={setForm} inputMode="numeric" placeholder="1234 5678 9012 3456" maxLength={19} autoComplete="cc-number" className="span2 mono"></Field>
              <Field label="Expiration" k="exp" form={form} setForm={setForm} placeholder="MM/AA" maxLength={5} autoComplete="cc-exp"></Field>
              <Field label="CVV" k="cvv" type="password" inputMode="numeric" form={form} setForm={setForm} maxLength={4} autoComplete="cc-csc"></Field>
              <Field label="Nom sur la carte" k="cardName" form={form} setForm={setForm} autoComplete="cc-name" className="span2"></Field>
            </div>
          </Paper>}

          {err && <p className="cp-err" role="alert">{err}</p>}
          {step > 0 && <div className="row cp-nav">
            <Button variant="outlineLight" iconLeft={Ic('arrow-left', 16, 'var(--q-creme)')} onClick={() => setStep(step - 1)}>Retour</Button>
            <Button variant="cta" size="lg" iconRight={Ic(step === 3 ? 'lock' : 'arrow-right', 16, '#fff')} onClick={next}>{step === 1 ? 'Choisir la livraison' : step === 2 ? 'Payer' : 'Confirmer · ' + fmt(total)}</Button>
          </div>}
        </div>
        <div className="cp-side"><Recap lines={cart.lines}></Recap></div>
      </div>}
    </div>
  </div>;
}

Object.assign(window, { Scraps, fmt, useCart, CartButton, CartToast, CartPage, Cahier });
