/* global React */
/* Cart drawer PARTAGÉ (panneau latéral) — s'ouvre au clic sur le panier du header, sur toutes les pages.
   Source unique : le panier serveur (GET /panier enrichi nom/réf/image, POST /panier/modifier).
   Émet l'événement 'ec-cart-changed' après modif pour que la page (barre + badge) se resynchronise. */
function EcCartDrawer({ open, onClose }) {
  const cfg = window.EXTRANET_CONFIG || {};
  const T = (window.EcUI && window.EcUI.T) || {};
  const base = cfg.base_url || '';
  const CARTON = (window.PORTAIL_CONFIG && window.PORTAIL_CONFIG.conditionnement) || 3;
  const FRANCO = parseFloat(cfg.franco_ht) || 250;
  const PRIMARY = T.primary || 'oklch(0.62 0.14 40)';
  const INK = T.ink || 'oklch(0.255 0.016 48)';
  const BORDER = T.border || 'oklch(0.88 0.012 75)';
  const MUTE = T.mute || 'oklch(0.55 0.012 65)';
  const SERIF = T.serif || "'Playfair Display',serif";
  const SANS = T.sans || "'Hanken Grotesk',sans-serif";
  const fmt = (n) => (Math.round((n || 0) * 100) / 100).toFixed(2).replace('.', ',') + ' €';

  const [lignes, setLignes] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [loading, setLoading] = React.useState(false);

  const load = React.useCallback(() => {
    setLoading(true);
    fetch(base + '/panier', { credentials: 'same-origin' })
      .then(r => r.json())
      .then(d => { setLignes(d.lignes || []); setTotal(parseFloat(d.total_ht) || 0); setLoading(false); })
      .catch(() => setLoading(false));
  }, [base]);

  React.useEffect(() => { if (open) load(); }, [open, load]);

  const setQty = (l, newQty) => {
    setLignes(ls => ls.map(x => x.product_id === l.product_id ? { ...x, quantite: newQty, total_ht: l.prix_ht * newQty } : x).filter(x => x.quantite > 0));
    setTotal(t => t + l.prix_ht * (newQty - l.quantite));
    fetch(base + '/panier/modifier', { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'same-origin', body: JSON.stringify({ product_id: l.product_id, quantite: newQty }) })
      .then(() => { load(); try { window.dispatchEvent(new Event('ec-cart-changed')); } catch (e) {} })
      .catch(() => {});
  };

  const units = lignes.reduce((s, l) => s + l.quantite, 0);
  const francoText = total >= FRANCO ? '✓ Franco de port acquis' : ('Plus que ' + fmt(FRANCO - total) + ' pour le franco de port');

  return (
    <React.Fragment>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 75, background: 'rgba(40,22,12,.4)', opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none', transition: 'opacity .3s' }}></div>
      <aside style={{ position: 'fixed', top: 0, right: 0, height: '100vh', width: 400, maxWidth: '92vw', background: 'oklch(0.985 0.008 84)', zIndex: 80, boxShadow: '-30px 0 70px -30px rgba(40,20,10,.5)', transform: open ? 'translateX(0)' : 'translateX(102%)', transition: 'transform .34s cubic-bezier(.2,.8,.2,1)', display: 'flex', flexDirection: 'column', fontFamily: SANS }}>
        <div style={{ padding: '20px 22px', borderBottom: '1px solid ' + BORDER, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ fontFamily: SERIF, fontSize: 20, color: INK }}>Votre commande <span style={{ fontSize: 13, color: MUTE }}>· {units} article{units > 1 ? 's' : ''}</span></div>
          <button onClick={onClose} aria-label="Fermer" style={{ border: 'none', background: 'transparent', fontSize: 26, color: MUTE, cursor: 'pointer', lineHeight: 1 }}>×</button>
        </div>
        <div style={{ flex: 1, overflowY: 'auto', padding: '12px 16px' }}>
          {loading && lignes.length === 0 && <div style={{ padding: 30, textAlign: 'center', color: MUTE, fontSize: 14 }}>Chargement…</div>}
          {!loading && lignes.length === 0 && <div style={{ padding: '50px 20px', textAlign: 'center', color: MUTE }}><div style={{ fontFamily: SERIF, fontSize: 18, marginBottom: 6 }}>Votre panier est vide</div><div style={{ fontSize: 13 }}>Ajoutez des kits depuis les nouveautés.</div></div>}
          {lignes.map(l => (
            <div key={l.product_id} style={{ display: 'flex', gap: 12, padding: '12px 6px', borderBottom: '1px solid ' + BORDER }}>
              <div style={{ width: 64, height: 64, borderRadius: 12, overflow: 'hidden', background: T.card || 'oklch(0.965 0.012 84)', flexShrink: 0 }}>{l.img && <img src={l.img} alt={l.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: SERIF, fontSize: 15, color: INK, lineHeight: 1.2 }}>{l.name}</div>
                <div style={{ fontSize: 11.5, color: MUTE, margin: '2px 0 8px' }}>Réf. {l.ref} · {fmt(l.prix_ht)} HT</div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                  <div style={{ display: 'flex', alignItems: 'center', border: '1.5px solid ' + PRIMARY, borderRadius: 999, overflow: 'hidden' }}>
                    <button onClick={() => setQty(l, Math.max(0, l.quantite - CARTON))} style={{ width: 28, height: 30, border: 'none', background: 'transparent', color: 'oklch(0.5 0.06 40)', fontSize: 15, cursor: 'pointer' }}>−</button>
                    <span style={{ minWidth: 22, textAlign: 'center', fontWeight: 700, fontSize: 12.5, color: 'oklch(0.55 0.13 40)' }}>{l.quantite}</span>
                    <button onClick={() => setQty(l, l.quantite + CARTON)} style={{ width: 28, height: 30, border: 'none', background: PRIMARY, color: '#fff', fontSize: 15, cursor: 'pointer' }}>+</button>
                  </div>
                  <div style={{ fontFamily: SERIF, fontSize: 15, color: INK }}>{fmt(l.total_ht)}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
        <div style={{ padding: '16px 20px 20px', borderTop: '1px solid ' + BORDER, background: 'oklch(0.965 0.012 84)' }}>
          <div style={{ fontSize: 12.5, color: total >= FRANCO ? 'oklch(0.5 0.12 150)' : MUTE, marginBottom: 10 }}>{francoText}</div>
          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14 }}>
            <span style={{ fontSize: 12.5, color: MUTE, letterSpacing: '.06em' }}>TOTAL HT</span>
            <span style={{ fontFamily: SERIF, fontSize: 24, color: INK }}>{fmt(total)}</span>
          </div>
          <a href={cfg.commander_url || (base + '/commander')} style={{ display: 'block', textAlign: 'center', background: PRIMARY, color: '#fff', fontWeight: 600, fontSize: 15, padding: '14px', borderRadius: 12, textDecoration: 'none' }}>Voir le bon de commande →</a>
        </div>
      </aside>
    </React.Fragment>
  );
}
