// ── Overlays: cart drawer, newsletter modal, search ──────────────────

function CartDrawer({ open, onClose, items, removeItem, updateQty, goTo }) {
  const loPrice = useCurrency();
  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const wasTotal = items.reduce((s, i) => s + (i.was || i.price) * i.qty, 0);
  const saved = Math.max(0, wasTotal - subtotal);
  const total = subtotal;

  const [checkingOut, setCheckingOut] = React.useState(false);
  const [checkoutErr, setCheckoutErr] = React.useState('');
  const [discountCode, setDiscountCode] = React.useState('');

  const checkout = async () => {
    setCheckoutErr('');
    setCheckingOut(true);
    try {
      // Read affiliate code from localStorage (set when visitor arrived via ?ref=CODE)
      let affiliateCode = '';
      try {
        const stored = localStorage.getItem('jta_ref');
        const storedTime = parseInt(localStorage.getItem('jta_ref_time') || '0', 10);
        // 30-day attribution window
        if (stored && storedTime && Date.now() - storedTime < 30 * 24 * 3600 * 1000) {
          affiliateCode = stored;
        } else {
          localStorage.removeItem('jta_ref');
          localStorage.removeItem('jta_ref_time');
        }
      } catch (e) {}

      const res = await fetch('/api/create-checkout-session', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          items: items.map((i) => ({
          id: i.id, size: i.size, color: i.color, qty: i.qty,
          ...(i.bespokeConfig ? { bespokeConfig: i.bespokeConfig } : {}),
          ...(i.refImage ? { refImage: i.refImage } : {}),
        })),
          currency: (window.LO_CURRENCY && window.LO_CURRENCY.code) || 'USD',
          ...(affiliateCode ? { affiliate_code: affiliateCode } : {}),
          ...(discountCode.trim() ? { discount_code: discountCode.trim() } : {}),
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data.url) throw new Error(data.error || 'Checkout is unavailable right now.');
      window.location.href = data.url; // → Stripe-hosted payment page
    } catch (e) {
      setCheckoutErr(e.message || 'Something went wrong. Please try again.');
      setCheckingOut(false);
    }
  };

  return (
    <>
      <div className={`scrim ${open ? 'on' : ''}`} onClick={onClose} />
      <aside className={`drawer ${open ? 'on' : ''}`} aria-hidden={!open}>
        <div className="drawer-head">
          <div>
            <div className="display" style={{ fontSize: 30 }}>
              <em>Cart.</em>
            </div>
            <div className="mono" style={{ color: 'var(--fg-3)', marginTop: 4 }}>
              {items.length} {items.length === 1 ? 'piece' : 'pieces'}
            </div>
          </div>
          <button className="close-x" onClick={onClose} aria-label="Close cart">
            <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.3">
              <line x1="3" y1="3" x2="15" y2="15" />
              <line x1="15" y1="3" x2="3" y2="15" />
            </svg>
          </button>
        </div>

        {/* Promise list — free shipping always, 14-day returns */}
        <div style={{
          padding: '14px 28px', display: 'grid',
          gridTemplateColumns: 'repeat(2, 1fr)', gap: 6,
          borderBottom: '.5px solid var(--line)',
        }}>
          {[
            ['Free', 'worldwide shipping'],
            ['14 day', 'money-back'],
          ].map(([k, l]) => (
            <div key={k} style={{
              display: 'flex', flexDirection: 'column', gap: 2,
            }}>
              <span className="display" style={{ fontSize: 16 }}><em>{k}</em></span>
              <span className="mono" style={{ color: 'var(--fg-3)', fontSize: 9 }}>{l}</span>
            </div>
          ))}
        </div>

        <div className="drawer-body">
          {items.length === 0 ? (
            <div style={{ padding: '80px 0', textAlign: 'center' }}>
              <div className="display" style={{ fontSize: 42, marginBottom: 16 }}><em>Empty.</em></div>
              <p style={{ color: 'var(--fg-2)', fontSize: 13, marginBottom: 32 }}>
                Add a piece to get started.
              </p>
              <button className="btn sm" onClick={() => { onClose(); goTo('collection'); }}>
                Shop the collection <span className="arrow">→</span>
              </button>
            </div>
          ) : (
            items.map((it) => (
              <div key={it.cartId} style={{
                display: 'grid',
                gridTemplateColumns: '88px 1fr auto',
                gap: 16,
                padding: '20px 0',
                borderBottom: '.5px solid var(--line)',
              }}>
                {it.images?.[0] ? (
                  <img src={it.images[0]} alt={it.frenchName || it.name}
                    style={{ width: 88, height: 116, objectFit: 'contain',
                      background: 'var(--surface)', display: 'block', flexShrink: 0 }} />
                ) : (
                  <div style={{ width: 88, height: 116, background: 'var(--surface)', flexShrink: 0 }} />
                )}
                <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                  <div>
                    <div style={{
                      fontFamily: 'var(--font-mono)', fontSize: 11,
                      letterSpacing: '.16em', textTransform: 'uppercase',
                      marginBottom: 4,
                    }}>
                      {it.bespokeConfig ? `Custom · ${it.frenchName || it.name}` : (it.frenchName || it.name)}
                    </div>
                    <div className="mono" style={{ color: 'var(--fg-3)', fontSize: 10 }}>
                      {it.bespokeConfig
                        ? [it.bespokeConfig.leather, it.bespokeConfig.primary_color, it.bespokeConfig.hardware, 'Custom fit'].filter(Boolean).join(' · ')
                        : [it.color, it.size && `Size ${it.size}`].filter(Boolean).join(' · ')}
                    </div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8 }}>
                    <div style={{
                      display: 'flex', alignItems: 'center',
                      border: '.5px solid var(--line-2)',
                    }}>
                      <button onClick={() => updateQty(it.cartId, Math.max(1, it.qty - 1))}
                        style={{ width: 28, height: 28, color: 'var(--fg-2)', fontSize: 13 }}>−</button>
                      <span style={{
                        minWidth: 18, textAlign: 'center',
                        fontFamily: 'var(--font-mono)', fontSize: 11,
                      }}>{it.qty}</span>
                      <button onClick={() => updateQty(it.cartId, it.qty + 1)}
                        style={{ width: 28, height: 28, color: 'var(--fg-2)', fontSize: 13 }}>+</button>
                    </div>
                    <button onClick={() => removeItem(it.cartId)}
                      className="mono"
                      style={{ color: 'var(--fg-3)', marginLeft: 8 }}
                      onMouseEnter={(e) => e.currentTarget.style.color = 'var(--fg)'}
                      onMouseLeave={(e) => e.currentTarget.style.color = ''}>
                      Remove
                    </button>
                  </div>
                </div>
                <div style={{
                  fontFamily: 'var(--font-display)', fontSize: 18,
                }}>
                  {loPrice(it.price * it.qty)}
                </div>
              </div>
            ))
          )}
        </div>

        {items.length > 0 && (
          <div className="drawer-foot">
            <div style={{
              display: 'flex', justifyContent: 'space-between',
              fontFamily: 'var(--font-mono)', fontSize: 11,
              letterSpacing: '.18em', textTransform: 'uppercase',
              color: 'var(--fg-2)', marginBottom: 6,
            }}>
              <span>Subtotal</span><span>{loPrice(subtotal)}</span>
            </div>
            {saved > 0 && (
              <div style={{
                display: 'flex', justifyContent: 'space-between',
                fontFamily: 'var(--font-mono)', fontSize: 11,
                letterSpacing: '.18em', textTransform: 'uppercase',
                color: 'var(--fg-2)', marginBottom: 6,
              }}>
                <span>You saved</span>
                <span style={{ color: 'var(--fg)' }}>−{loPrice(saved)}</span>
              </div>
            )}
            <div style={{
              display: 'flex', justifyContent: 'space-between',
              fontFamily: 'var(--font-mono)', fontSize: 11,
              letterSpacing: '.18em', textTransform: 'uppercase',
              color: 'var(--fg-2)', marginBottom: 6,
            }}>
              <span>Shipping</span>
              <span>Free · worldwide</span>
            </div>
            <div style={{
              display: 'flex', justifyContent: 'space-between',
              fontFamily: 'var(--font-display)', fontSize: 24,
              padding: '16px 0', marginBottom: 12,
              borderTop: '.5px solid var(--line)',
              marginTop: 12,
            }}>
              <span>Total</span><span>{loPrice(total)}</span>
            </div>
            <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
              <input type="text" placeholder="Discount code" value={discountCode}
                onChange={(e) => setDiscountCode(e.target.value)}
                className="mono"
                style={{
                  flex: 1, padding: '10px 12px', fontSize: 11, letterSpacing: '.08em',
                  textTransform: 'uppercase', border: '.5px solid var(--line-2)',
                  background: 'transparent', color: 'var(--fg)',
                }} />
            </div>
            <button className="btn" style={{ width: '100%' }}
              onClick={checkout} disabled={checkingOut}>
              {checkingOut ? 'Redirecting…' : <>Checkout <span className="arrow">→</span></>}
            </button>
            {checkoutErr && (
              <div className="mono" style={{
                color: '#e57373', fontSize: 10, marginTop: 8, textAlign: 'center',
              }}>
                {checkoutErr}
              </div>
            )}
            <button className="btn ghost sm" style={{ width: '100%', marginTop: 8 }}
              onClick={onClose}>
              Continue browsing
            </button>
            <div className="mono" style={{
              textAlign: 'center', color: 'var(--fg-3)', marginTop: 16, fontSize: 9.5,
            }}>
              Secure checkout · 14-day money-back guarantee
            </div>
            <div className="mono" style={{
              textAlign: 'center', color: 'var(--fg-3)', marginTop: 6, fontSize: 9,
              letterSpacing: '.06em',
            }}>
              All prices charged in USD · displayed currencies are for reference only
            </div>
          </div>
        )}
      </aside>
    </>
  );
}

function NewsletterModal({ open, onClose }) {
  const [email, setEmail]   = React.useState('');
  const [sent, setSent]     = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [err, setErr]       = React.useState('');

  const submit = async (e) => {
    e?.preventDefault();
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
      document.getElementById('nl-field')?.animate(
        [{ transform: 'translateX(-6px)' }, { transform: 'translateX(6px)' }, { transform: 'none' }],
        { duration: 280 }
      );
      return;
    }
    setLoading(true);
    setErr('');
    try {
      await fetch('/api/subscribe', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, source: 'newsletter-modal' }),
      });
    } catch (e) { /* silent — still show success */ }
    setLoading(false);
    setSent(true);
    setTimeout(() => { onClose(); setSent(false); setEmail(''); }, 1800);
  };

  return (
    <div className={`modal ${open ? 'on' : ''}`} onClick={onClose}>
      <div className="modal-card" onClick={(e) => e.stopPropagation()}>
        <button className="close-x" onClick={onClose}
          style={{ position: 'absolute', top: 12, right: 12 }} aria-label="Close">
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.3">
            <line x1="3" y1="3" x2="15" y2="15" />
            <line x1="15" y1="3" x2="3" y2="15" />
          </svg>
        </button>
        <div className="eyebrow" style={{ marginBottom: 18 }}>◇ &nbsp; The studio list</div>
        <h2 className="display" style={{
          fontSize: 56, margin: 0,
        }}>
          {sent ? <><em>Welcome</em> to the list.</> : <>First look. <em>Slow news.</em></>}
        </h2>
        <p style={{
          fontSize: 14, lineHeight: 1.65, color: 'var(--fg-2)',
          marginTop: 18, marginBottom: 32, maxWidth: 420,
        }}>
          {sent
            ? `We'll be in touch — sparingly, and never about anything you didn't ask for.`
            : 'New arrivals, seasonal sales and studio essays. No more than two emails a month.'}
        </p>
        {!sent && (
          <form className="field" id="nl-field" onSubmit={submit}>
            <input type="email" placeholder="your@email.com"
              value={email} onChange={(e) => setEmail(e.target.value)}
              autoFocus disabled={loading} />
            <button type="submit" disabled={loading}>
              {loading ? '…' : 'Subscribe →'}
            </button>
          </form>
        )}
        {!sent && (
          <div className="mono" style={{ color: 'var(--fg-3)', marginTop: 16, fontSize: 9.5 }}>
            By subscribing you agree to our privacy notice.
          </div>
        )}
      </div>
    </div>
  );
}

function SearchOverlay({ open, onClose, goTo }) {
  const loPrice = useCurrency();
  const [q, setQ] = React.useState('');
  React.useEffect(() => { if (!open) setQ(''); }, [open]);
  const results = React.useMemo(() => {
    if (!q.trim()) return PRODUCTS.slice(0, 8);
    const s = q.toLowerCase();
    return PRODUCTS.filter((p) =>
      p.name.toLowerCase().includes(s) ||
      (p.frenchName || '').toLowerCase().includes(s) ||
      p.category.toLowerCase().includes(s) ||
      p.finish.toLowerCase().includes(s) ||
      p.gender.toLowerCase().includes(s) ||
      (p.colors || []).some((c) => c.toLowerCase().includes(s)) ||
      String(p.price).includes(s)
    );
  }, [q]);

  return (
    <div className={`modal ${open ? 'on' : ''}`} onClick={onClose}
      style={{ alignItems: 'flex-start', paddingTop: 60 }}>
      <div className="modal-card" onClick={(e) => e.stopPropagation()}
        style={{ width: 880, maxWidth: '100%', padding: '36px 40px' }}>
        <button className="close-x" onClick={onClose}
          style={{ position: 'absolute', top: 12, right: 12 }} aria-label="Close">
          <svg width="18" height="18" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.3">
            <line x1="3" y1="3" x2="15" y2="15" />
            <line x1="15" y1="3" x2="3" y2="15" />
          </svg>
        </button>
        <div className="eyebrow" style={{ marginBottom: 18 }}>◇ &nbsp; Search the studio</div>
        <input value={q} onChange={(e) => setQ(e.target.value)}
          autoFocus
          placeholder="Search for biker, trench, oxide…"
          style={{
            width: '100%', background: 'transparent', border: 0, outline: 0,
            color: 'var(--fg)', padding: '12px 0',
            fontFamily: 'var(--font-display)', fontSize: 42, fontWeight: 300,
            borderBottom: '.5px solid var(--line-2)',
          }} />
        <div className="mono" style={{ color: 'var(--fg-3)', margin: '18px 0' }}>
          {q ? `${results.length} results` : 'Suggested pieces'}
        </div>
        <div className="search-results-grid" style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, maxHeight: 420, overflowY: 'auto' }}>
          {results.length === 0 ? (
            <div style={{ gridColumn: '1 / -1', padding: '40px 0', textAlign: 'center', color: 'var(--fg-2)' }}>
              <div className="display" style={{ fontSize: 36 }}><em>Nothing matches.</em></div>
              <p style={{ marginTop: 10, fontSize: 13 }}>Try a different search term — name, category, color, or gender.</p>
            </div>
          ) : (
            results.slice(0, 8).map((p) => (
              <button key={p.id} onClick={() => { goTo('product', { product: p }); onClose(); }}
                style={{ textAlign: 'left' }}>
                {p.images && p.images[0] ? (
                  <div style={{ aspectRatio: '3/4', overflow: 'hidden', background: 'var(--surface)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <img src={p.images[0]} alt={p.frenchName || p.name} loading="lazy"
                      style={{ width: '100%', height: '100%', objectFit: 'contain', display: 'block' }} />
                  </div>
                ) : (
                  <Editorial product={p} ratio="3/4" />
                )}
                <div style={{ paddingTop: 8 }}>
                  <div className="mono" style={{ fontSize: 10 }}>{p.frenchName || p.name}</div>
                  <div className="mono" style={{ color: 'var(--fg-3)', fontSize: 10 }}>
                    {(() => {
                      const sale = window.getSaleInfo && window.getSaleInfo(p);
                      return sale
                        ? <><span style={{ textDecoration: 'line-through', marginRight: 5 }}>{loPrice(sale.original)}</span><span style={{ color: '#c0392b' }}>{loPrice(sale.sale)}</span></>
                        : loPrice(p.price);
                    })()}
                  </div>
                </div>
              </button>
            ))
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CartDrawer, NewsletterModal, SearchOverlay });
