// checkout.jsx — cart drawer + multi-step checkout overlay
const { useState: useStateCo, useMemo: useMemoCo } = React;

const SHIPPING = 0; // free
const fmt = (n) => `$${n.toFixed(2)}`;

// Pre-baked confetti pieces for the celebratory confirmation screen.
const CONFETTI = Array.from({ length: 48 }).map((_, i) => ({
  left: 1 + (i * 2.04) % 98,
  delay: ((i * 7) % 18) * 0.12,
  dur: 2.4 + ((i * 5) % 8) * 0.28,
  size: 5 + (i % 4) * 3,
  round: i % 3 === 0,
  color: i % 2 === 0 ? 'var(--hat)' : 'var(--accent)',
}));

// ---- Cart drawer -------------------------------------------------------
function CartDrawer({ open, items, onClose, onQty, onRemove, onCheckout, colorways }) {
  const subtotal = items.reduce((s, it) => s + it.price * it.qty, 0);
  const count = items.reduce((s, it) => s + it.qty, 0);
  const cwById = (id) => colorways.find((c) => c.id === id);

  return (
    <div className={`drawer-scrim ${open ? 'open' : ''}`} onClick={onClose}>
      <aside className={`drawer ${open ? 'open' : ''}`} onClick={(e) => e.stopPropagation()}>
        <div className="drawer-head">
          <h3>Your cart <span className="muted">({count})</span></h3>
          <button className="icon-x" onClick={onClose} aria-label="Close">✕</button>
        </div>

        {items.length === 0 ? (
          <div className="cart-empty">
            <p>Nothing in here yet.</p>
            <button className="btn btn-outline" onClick={onClose}>Pick a color</button>
          </div>
        ) : (
          <>
            <div className="cart-items">
              {items.map((it) => {
                const cw = cwById(it.colorId);
                return (
                  <div className="cart-item" key={it.colorId}>
                    <div className="cart-thumb" style={{ background: cw.theme.wash }}>
                      <img src={it.img} alt="" />
                    </div>
                    <div className="cart-item-body">
                      <p className="cart-item-name">{it.name}</p>
                      <p className="cart-item-meta">{cw.name} · One size</p>
                      <div className="cart-item-bottom">
                        <div className="qty-stepper sm">
                          <button onClick={() => onQty(it.colorId, Math.max(1, it.qty - 1))}>–</button>
                          <span>{it.qty}</span>
                          <button onClick={() => onQty(it.colorId, Math.min(10, it.qty + 1))}>+</button>
                        </div>
                        <span className="cart-item-price">{fmt(it.price * it.qty)}</span>
                      </div>
                    </div>
                    <button className="cart-remove" onClick={() => onRemove(it.colorId)} aria-label="Remove">Remove</button>
                  </div>
                );
              })}
            </div>
            <div className="drawer-foot">
              <div className="cart-line"><span>Subtotal</span><span>{fmt(subtotal)}</span></div>
              <div className="cart-line muted"><span>Shipping</span><span>Free</span></div>
              <button className="btn btn-solid btn-lg full" onClick={onCheckout}>
                Join Waitlist
              </button>
              <p className="drawer-note">No payment today · reserve your color before they're gone.</p>
            </div>
          </>
        )}
      </aside>
    </div>
  );
}

// ---- Waitlist overlay (styled like a checkout) -------------------------
function Checkout({ open, items, colorways, onClose, onDone }) {
  const [step, setStep] = useStateCo(0); // 0 = details form, 1 = confirmed
  const [info, setInfo] = useStateCo({ email: '', name: '' });
  const [touched, setTouched] = useStateCo(false);
  const [loading, setLoading] = useStateCo(false);
  const [submitErr, setSubmitErr] = useStateCo(false);

  const subtotal = items.reduce((s, it) => s + it.price * it.qty, 0);
  const count = items.reduce((s, it) => s + it.qty, 0);
  const cwById = (id) => colorways.find((c) => c.id === id);

  React.useEffect(() => { if (open) { setStep(0); setTouched(false); setSubmitErr(false); } }, [open]);

  const valid = info.email.includes('@') && info.name.trim().length > 0;

  const join = async () => {
    setTouched(true);
    if (!valid) return;

    const params = new URLSearchParams(window.location.search);
    const payload = {
      name: info.name,
      email: info.email,
      items: items.map(({ colorId, name, qty, price }) => ({ colorId, name, qty, price })),
      referrer: document.referrer || null,
      utm_source:   params.get('utm_source'),
      utm_medium:   params.get('utm_medium'),
      utm_campaign: params.get('utm_campaign'),
    };

    setLoading(true);
    setSubmitErr(false);
    try {
      const r = await fetch('/api/waitlist', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!r.ok) throw new Error('failed');
      setStep(1);
    } catch {
      setSubmitErr(true);
    } finally {
      setLoading(false);
    }
  };

  if (!open) return null;

  const colorList = items.map((it) => `${cwById(it.colorId).name} ×${it.qty}`).join(', ');

  return (
    <div className="checkout-scrim">
      <div className="checkout">
        <div className="checkout-head">
          <button className="brandmark co" onClick={onClose}>
            <span className="brandmark-spd">SPD</span>
            <span className="brandmark-full">Waitlist</span>
          </button>
          {step === 0 && <button className="icon-x" onClick={onClose} aria-label="Close">✕</button>}
        </div>

        {step === 0 && (
          <div className="co-steps">
            <div className="co-step active">
              <span className="co-step-n">1</span>Your details
            </div>
            <div className="co-step">
              <span className="co-step-n">2</span>Confirm
            </div>
          </div>
        )}

        <div className="checkout-body">
          {step === 0 && (
            <div className="co-form">
              <h3 className="co-h">Join the waitlist</h3>
              <p className="co-sub">No payment today — just your spot. We'll hold the color you picked and reach out the moment these caps are ready to ship.</p>
              <Field label="Email" value={info.email} onChange={(v) => setInfo({ ...info, email: v })}
                     placeholder="you@email.com" err={touched && !info.email.includes('@')} />
              <Field label="Full name" value={info.name} onChange={(v) => setInfo({ ...info, name: v })}
                     placeholder="Jordan Rivera" err={touched && !info.name.trim()} />
              {submitErr && (
                <p style={{ color: 'red', fontSize: '0.85rem', marginBottom: '0.5rem' }}>
                  Something went wrong — please try again.
                </p>
              )}
              <div className="co-actions">
                <button className="co-back" onClick={onClose}>← Back to shop</button>
                <button className="btn btn-solid btn-lg" onClick={join} disabled={loading}>
                  {loading ? 'Saving…' : 'Join Waitlist'}
                </button>
              </div>
            </div>
          )}

          {step === 1 && (
            <div className="co-done">
              <div className="co-burst" aria-hidden="true">
                {CONFETTI.map((c, i) => (
                  <span key={i} style={{
                    left: `${c.left}%`,
                    '--s': `${c.size}px`,
                    '--c': c.color,
                    '--r': c.round ? '999px' : '2px',
                    '--d': `${c.dur}s`,
                    '--dl': `${c.delay}s`,
                  }} />
                ))}
              </div>
              <div className="co-check">✓</div>
              <h3>You're on the list</h3>
              <p>Thanks, {info.name.split(' ')[0] || 'friend'} — your spot is saved. We'll email <b>{info.email}</b> the moment these caps are released.</p>

              <div className="co-reserved">
                {items.map((it) => {
                  const cw = cwById(it.colorId);
                  return (
                    <div className="co-cap" key={it.colorId}>
                      <div className="co-cap-stage" style={{
                        background: `radial-gradient(120% 100% at 50% 12%, color-mix(in srgb, ${cw.theme.hat} 16%, ${cw.theme.panel}) 0%, ${cw.theme.panel} 72%)`,
                      }}>
                        <img src={it.img} alt={`${cw.name} cap`} />
                        <span className="co-cap-qty" style={{ background: cw.theme.hat, color: cw.theme.onHat }}>×{it.qty}</span>
                      </div>
                      <div className="co-cap-foot">
                        <span className="co-cap-name">{cw.name}</span>
                        <span className="co-cap-tag" style={{ color: cw.theme.hat, background: `color-mix(in srgb, ${cw.theme.hat} 12%, transparent)` }}>Reserved</span>
                      </div>
                    </div>
                  );
                })}
              </div>

              <p className="co-done-sub">{count} cap{count > 1 ? 's' : ''} held against your name<br/>No payment until they're ready to ship.</p>
              <button className="btn btn-solid btn-lg" onClick={onDone}>Back home &amp; keep browsing</button>
            </div>
          )}

          {/* order summary — captures color + quantities */}
          {step === 0 && (
            <aside className="co-summary">
              <h4>Your caps</h4>
              <div className="co-sum-items">
                {items.map((it) => {
                  const cw = cwById(it.colorId);
                  return (
                    <div className="co-sum-item" key={it.colorId}>
                      <div className="co-sum-thumb" style={{ background: cw.theme.wash }}>
                        <img src={it.img} alt="" />
                        <span className="co-sum-qty">{it.qty}</span>
                      </div>
                      <div className="co-sum-info">
                        <p>{it.name}</p>
                        <span>{cw.name}</span>
                      </div>
                      <span className="co-sum-price">×{it.qty}</span>
                    </div>
                  );
                })}
              </div>
              <div className="co-sum-lines">
                <div className="cart-line"><span>Caps reserved</span><span>{count}</span></div>
                <div className="cart-line muted"><span>Due today</span><span>$0.00</span></div>
                <div className="cart-line total"><span>Total</span><span>{fmt(subtotal)}</span></div>
              </div>
            </aside>
          )}
        </div>
      </div>
    </div>
  );
}

function Field({ label, value, onChange, placeholder, err, mono }) {
  return (
    <label className={`field ${err ? 'err' : ''}`}>
      <span className="field-label">{label}</span>
      <input
        className={mono ? 'mono' : ''}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        autoComplete="off"
      />
    </label>
  );
}

Object.assign(window, { CartDrawer, Checkout });
