// cart-checkout.jsx — Cart drawer + Checkout

function CartDrawer({ open, onClose, items, setItems, onCheckout }) {
  const [removing, setRemoving] = React.useState(null);
  const [swipe, setSwipe] = React.useState({});

  const subtotal = items.reduce((s, i) => s + i.product.price * i.qty, 0);
  const shipping = subtotal >= 15000 ? 0 : 995;
  const total = subtotal + shipping;

  const updateQty = (id, dq) => {
    setItems(its => its.map(i => i.id === id ? { ...i, qty: Math.max(1, i.qty + dq) } : i));
  };
  const removeItem = (id) => {
    setRemoving(id);
    setTimeout(() => setItems(its => its.filter(i => i.id !== id)), 240);
  };

  if (!open) return null;
  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 80 }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.6)',
        backdropFilter: 'blur(4px)', animation: 'ff-fade-in 220ms' }}/>
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        height: '92svh', background: 'var(--ff-bg)',
        borderTop: '1px solid var(--ff-border)',
        borderRadius: '16px 16px 0 0',
        animation: 'ff-slide-up 320ms var(--ff-ease-out)',
        display: 'flex', flexDirection: 'column',
        boxShadow: '0 -16px 48px rgba(0,0,0,0.5)',
      }}>
        <div style={{ padding: '12px 0 4px', flexShrink: 0 }}>
          <div style={{ width: 40, height: 4, borderRadius: 2, background: 'var(--ff-border-strong)', margin: '0 auto' }}/>
        </div>
        <div style={{ padding: '8px 20px 14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          borderBottom: '1px solid var(--ff-border)' }}>
          <div>
            <div style={{ fontFamily: 'var(--ff-display)', fontSize: 20, fontWeight: 600 }}>Cart</div>
            <div className="mono" style={{ fontSize: 11, color: 'var(--ff-text-3)', letterSpacing: '0.1em', marginTop: 2 }}>
              {items.length} ITEM{items.length === 1 ? '' : 'S'}
            </div>
          </div>
          <button onClick={onClose} className="tap"
            style={{ background: 'none', border: 'none', color: 'var(--ff-text-2)', padding: 8, marginRight: -8, cursor: 'pointer' }}>
            <IconClose size={20}/>
          </button>
        </div>

        <div style={{ flex: 1, overflowY: 'auto' }}>
          {items.length === 0 ? (
            <div style={{ padding: '64px 24px', textAlign: 'center' }}>
              <div style={{ width: 64, height: 64, borderRadius: 32, background: 'var(--ff-surface)',
                border: '1px solid var(--ff-border)', display: 'flex', alignItems: 'center', justifyContent: 'center',
                margin: '0 auto 20px' }}>
                <IconCart size={28} color="var(--ff-text-3)"/>
              </div>
              <div style={{ fontFamily: 'var(--ff-display)', fontSize: 18, fontWeight: 600, marginBottom: 8 }}>
                Your cart is empty
              </div>
              <div style={{ color: 'var(--ff-text-2)', fontSize: 14, marginBottom: 20 }}>
                Start with our most-requested upgrade.
              </div>
              <button className="btn btn-primary tap" onClick={onClose}>Shop top sellers</button>
            </div>
          ) : (
            items.map(item => (
              <CartLineItem key={item.id} item={item} removing={removing === item.id}
                onRemove={() => removeItem(item.id)}
                onInc={() => updateQty(item.id, 1)}
                onDec={() => updateQty(item.id, -1)}/>
            ))
          )}
        </div>

        {items.length > 0 && (
          <div style={{ borderTop: '1px solid var(--ff-border)', padding: '16px 20px',
            paddingBottom: 'calc(16px + var(--safe-bottom))', background: 'var(--ff-surface)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 13, color: 'var(--ff-text-2)' }}>
              <span>Subtotal</span>
              <span className="mono">{fmtPrice(subtotal)}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 12, fontSize: 13, color: 'var(--ff-text-2)' }}>
              <span>Shipping {shipping === 0 && <span style={{ color: 'var(--ff-success)' }}>· free</span>}</span>
              <span className="mono">{shipping === 0 ? '$0.00' : fmtPrice(shipping)}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', paddingTop: 12,
              borderTop: '1px solid var(--ff-border)' }}>
              <span style={{ fontSize: 15, fontWeight: 500 }}>Total</span>
              <span className="mono" style={{ fontSize: 22, fontWeight: 600 }}>{fmtPrice(total)}</span>
            </div>
            <button onClick={onCheckout} className="btn btn-primary tap"
              style={{ width: '100%', marginTop: 14, height: 56, fontSize: 15 }}>
              Checkout <IconArrowRight size={16}/>
            </button>
            <div style={{ marginTop: 10, textAlign: 'center', fontSize: 11, color: 'var(--ff-text-3)' }}>
              <IconLock size={10} style={{ verticalAlign: 'middle', marginRight: 4 }}/>
              Secure checkout · Authorize.net
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function CartLineItem({ item, removing, onRemove, onInc, onDec }) {
  const [dx, setDx] = React.useState(0);
  const startX = React.useRef(null);
  const onTouchStart = (e) => { startX.current = e.touches[0].clientX; };
  const onTouchMove = (e) => {
    if (startX.current === null) return;
    const d = e.touches[0].clientX - startX.current;
    setDx(Math.min(0, Math.max(-100, d)));
  };
  const onTouchEnd = () => {
    if (dx < -60) setDx(-80);
    else setDx(0);
    startX.current = null;
  };

  return (
    <div style={{ position: 'relative', overflow: 'hidden', borderBottom: '1px solid var(--ff-border)',
      maxHeight: removing ? 0 : 200, opacity: removing ? 0 : 1,
      transition: 'max-height 240ms, opacity 200ms' }}>
      <div onClick={onRemove}
        style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 80,
          background: 'var(--ff-orange)', color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer' }}>
        <IconTrash size={20}/>
      </div>
      <div onTouchStart={onTouchStart} onTouchMove={onTouchMove} onTouchEnd={onTouchEnd}
        style={{
          background: 'var(--ff-bg)',
          padding: '14px 20px',
          display: 'flex', gap: 14,
          transform: `translateX(${dx}px)`,
          transition: dx === 0 || dx === -80 ? 'transform 200ms var(--ff-ease)' : 'none',
        }}>
        <div style={{ width: 72, height: 72, borderRadius: 4, background: '#0c0c0c',
          border: '1px solid var(--ff-border)', overflow: 'hidden', flexShrink: 0 }}>
          <ProductVisual id={item.product.id}/>
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--ff-text-3)', letterSpacing: '0.1em' }}>
            {item.product.sku}
          </div>
          <div style={{ fontSize: 14, fontWeight: 500, color: 'var(--ff-text)', lineHeight: 1.3, marginTop: 2,
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {item.product.name}
          </div>
          <div style={{ fontSize: 12, color: 'var(--ff-text-2)', marginTop: 2 }}>{item.variant}</div>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 10 }}>
            <div style={{ display: 'flex', alignItems: 'center', border: '1px solid var(--ff-border)', borderRadius: 4 }}>
              <button onClick={onDec} className="tap" style={qtyMini}><IconMinus size={12}/></button>
              <span className="mono" style={{ width: 28, textAlign: 'center', fontSize: 13 }}>{item.qty}</span>
              <button onClick={onInc} className="tap" style={qtyMini}><IconPlus size={12}/></button>
            </div>
            <span className="mono" style={{ fontSize: 14, fontWeight: 600 }}>{fmtPrice(item.product.price * item.qty)}</span>
          </div>
        </div>
      </div>
    </div>
  );
}

const qtyMini = {
  width: 32, height: 32, background: 'none', border: 'none',
  color: 'var(--ff-text)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
};

// ─────────────────────── Checkout ───────────────────────
function CheckoutScreen({ items, onBack, onComplete }) {
  const [step, setStep] = React.useState(0); // 0 contact, 1 ship, 2 pay
  const [summaryOpen, setSummaryOpen] = React.useState(false);

  const subtotal = items.reduce((s, i) => s + i.product.price * i.qty, 0);
  const shipping = subtotal >= 15000 ? 0 : 995;
  const tax = Math.round(subtotal * 0.0625);
  const total = subtotal + shipping + tax;

  return (
    <div style={{ height: '100%', overflowY: 'auto' }}>
      <div style={{ position: 'sticky', top: 0, zIndex: 10, background: 'var(--ff-bg)',
        borderBottom: '1px solid var(--ff-border)', paddingTop: 'var(--safe-top)' }}>
        <div style={{ display: 'flex', alignItems: 'center', padding: '8px 12px', height: 56 }}>
          <button onClick={onBack} className="tap"
            style={{ background: 'none', border: 'none', color: 'var(--ff-text)', padding: 10, marginLeft: -10, cursor: 'pointer' }}>
            <IconChevronLeft size={22}/>
          </button>
          <div style={{ flex: 1, textAlign: 'center', fontFamily: 'var(--ff-display)', fontSize: 16, fontWeight: 600 }}>
            Checkout
          </div>
          <div style={{ width: 40 }}/>
        </div>
      </div>

      {/* Order summary collapsed */}
      <button onClick={() => setSummaryOpen(o => !o)}
        style={{ width: '100%', padding: '14px 16px', background: 'var(--ff-surface)', border: 'none',
          borderBottom: '1px solid var(--ff-border)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', cursor: 'pointer',
          color: 'var(--ff-text)', textAlign: 'left' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 14 }}>Order summary ({items.length})</span>
          <IconChevronDown size={14} style={{ transform: summaryOpen ? 'rotate(180deg)' : 'none', transition: 'transform 200ms', color: 'var(--ff-text-2)' }}/>
        </div>
        <span className="mono" style={{ fontSize: 15, fontWeight: 600 }}>{fmtPrice(total)}</span>
      </button>
      {summaryOpen && (
        <div style={{ background: 'var(--ff-surface)', borderBottom: '1px solid var(--ff-border)', padding: '4px 16px 16px' }}>
          {items.map(it => (
            <div key={it.id} style={{ display: 'flex', gap: 12, padding: '12px 0', borderBottom: '1px solid var(--ff-border)' }}>
              <div style={{ width: 56, height: 56, borderRadius: 4, background: '#0c0c0c',
                border: '1px solid var(--ff-border)', overflow: 'hidden', flexShrink: 0 }}>
                <ProductVisual id={it.product.id}/>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.product.name}</div>
                <div style={{ fontSize: 12, color: 'var(--ff-text-2)' }}>Qty {it.qty} · {it.variant}</div>
              </div>
              <span className="mono" style={{ fontSize: 13 }}>{fmtPrice(it.product.price * it.qty)}</span>
            </div>
          ))}
          <div style={{ paddingTop: 12, fontSize: 13 }}>
            {[
              ['Subtotal', subtotal],
              ['Shipping', shipping],
              ['Tax', tax],
            ].map(([l, v]) => (
              <div key={l} style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', color: 'var(--ff-text-2)' }}>
                <span>{l}</span><span className="mono">{fmtPrice(v)}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Apple/Google Pay (placeholder visual only — real flow would be conditional) */}
      <div style={{ padding: '20px 16px 0' }}>
        <button className="tap" style={{
          width: '100%', height: 52, borderRadius: 6, background: '#000',
          border: '1px solid var(--ff-border-strong)', color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          fontSize: 15, fontWeight: 500, cursor: 'pointer', marginBottom: 8,
        }}>
          <svg width="18" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M17.5 12.5c0-2.5 2-3.7 2.1-3.8-1.1-1.7-2.9-1.9-3.5-1.9-1.5-.2-2.9.9-3.7.9s-1.9-.9-3.2-.9c-1.6 0-3.2 1-4 2.5-1.7 3-.4 7.4 1.2 9.8.8 1.2 1.8 2.5 3 2.4 1.2 0 1.7-.8 3.1-.8 1.5 0 1.9.8 3.2.8 1.3 0 2.2-1.2 3-2.4.9-1.4 1.3-2.7 1.3-2.8-.1 0-2.5-1-2.5-3.8zM15.4 4.5c.7-.8 1.1-2 1-3.2-1 0-2.2.7-2.9 1.5-.7.8-1.2 2-1.1 3.1 1.2.1 2.4-.6 3-1.4z"/></svg>
          Pay with Apple Pay
        </button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '14px 0' }}>
          <div style={{ flex: 1, height: 1, background: 'var(--ff-border)' }}/>
          <span className="mono" style={{ fontSize: 10, color: 'var(--ff-text-3)', letterSpacing: '0.16em' }}>OR PAY WITH CARD</span>
          <div style={{ flex: 1, height: 1, background: 'var(--ff-border)' }}/>
        </div>
      </div>

      {/* Steps */}
      <div style={{ padding: '0 16px' }}>
        {/* Contact */}
        <CheckoutSection n={1} title="Contact" open={step >= 0} done={step > 0} onEdit={() => setStep(0)}>
          <Field label="Email" type="email" placeholder="you@example.com" autoComplete="email" inputMode="email"/>
          <label style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 12 }}>
            <input type="checkbox" defaultChecked style={{ width: 18, height: 18, accentColor: 'var(--ff-orange)' }}/>
            <span style={{ fontSize: 13, color: 'var(--ff-text-2)' }}>Email me about new releases and field notes</span>
          </label>
          {step === 0 && (
            <button onClick={() => setStep(1)} className="btn btn-primary tap" style={{ width: '100%', marginTop: 16, height: 52 }}>
              Continue to shipping
            </button>
          )}
        </CheckoutSection>

        {/* Shipping */}
        <CheckoutSection n={2} title="Shipping" open={step >= 1} done={step > 1} onEdit={() => setStep(1)}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <Field label="First name" autoComplete="given-name"/>
            <Field label="Last name" autoComplete="family-name"/>
          </div>
          <Field label="Address" autoComplete="street-address"/>
          <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr', gap: 10 }}>
            <Field label="City" autoComplete="address-level2"/>
            <Field label="State" autoComplete="address-level1"/>
            <Field label="ZIP" inputMode="numeric" autoComplete="postal-code"/>
          </div>
          <Field label="Phone" type="tel" autoComplete="tel" inputMode="tel"/>
          <div style={{ marginTop: 14 }}>
            <div className="eyebrow" style={{ marginBottom: 8 }}>METHOD</div>
            {[
              ['Standard', '3–5 business days', 'Free'],
              ['Expedited', '2 business days', '$14.95'],
            ].map(([n, d, p], i) => (
              <label key={n} style={{
                display: 'flex', alignItems: 'center', gap: 12, padding: '14px 12px', minHeight: 56,
                border: '1px solid var(--ff-border)', borderRadius: 4, marginBottom: 8,
                background: i === 0 ? 'var(--ff-orange-dim)' : 'var(--ff-surface)',
                borderColor: i === 0 ? 'var(--ff-orange)' : 'var(--ff-border)',
              }}>
                <input type="radio" name="ship" defaultChecked={i === 0} style={{ accentColor: 'var(--ff-orange)' }}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 500 }}>{n}</div>
                  <div style={{ fontSize: 12, color: 'var(--ff-text-2)' }}>{d}</div>
                </div>
                <span className="mono" style={{ fontSize: 14, fontWeight: 500 }}>{p}</span>
              </label>
            ))}
          </div>
          {step === 1 && (
            <button onClick={() => setStep(2)} className="btn btn-primary tap" style={{ width: '100%', marginTop: 12, height: 52 }}>
              Continue to payment
            </button>
          )}
        </CheckoutSection>

        {/* Payment */}
        <CheckoutSection n={3} title="Payment" open={step >= 2} done={false} onEdit={() => setStep(2)}>
          <Field label="Card number" autoComplete="cc-number" inputMode="numeric" placeholder="1234 1234 1234 1234"/>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <Field label="Expiry" autoComplete="cc-exp" inputMode="numeric" placeholder="MM / YY"/>
            <Field label="CVC" autoComplete="cc-csc" inputMode="numeric" placeholder="123"/>
          </div>
          <Field label="Name on card" autoComplete="cc-name"/>
          <div style={{ marginTop: 14, padding: 12, border: '1px solid var(--ff-border)',
            background: 'var(--ff-surface)', borderRadius: 4, display: 'flex', gap: 10, alignItems: 'flex-start' }}>
            <IconLock size={14} color="var(--ff-text-2)" style={{ marginTop: 3 }}/>
            <div style={{ fontSize: 12, color: 'var(--ff-text-2)', lineHeight: 1.5 }}>
              Encrypted and processed by Authorize.net. Your card details never touch our servers.
            </div>
          </div>
        </CheckoutSection>
      </div>

      <div style={{ height: 'calc(120px + var(--safe-bottom))' }}/>

      {/* Sticky place order */}
      {step === 2 && (
        <div style={{
          position: 'fixed', left: 0, right: 0, bottom: 0,
          padding: '12px 16px',
          paddingBottom: 'calc(12px + var(--safe-bottom))',
          background: 'rgba(10,10,10,0.95)', backdropFilter: 'blur(20px)',
          borderTop: '1px solid var(--ff-border)', zIndex: 25,
        }}>
          <button onClick={onComplete} className="btn btn-primary tap"
            style={{ width: '100%', height: 56, fontSize: 16 }}>
            <IconLock size={14}/> Place order · {fmtPrice(total)}
          </button>
        </div>
      )}
    </div>
  );
}

function CheckoutSection({ n, title, open, done, onEdit, children }) {
  return (
    <div style={{ borderBottom: '1px solid var(--ff-border)', padding: '20px 0' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: open ? 16 : 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{
            width: 26, height: 26, borderRadius: 13,
            border: '1px solid', borderColor: done ? 'var(--ff-success)' : open ? 'var(--ff-orange)' : 'var(--ff-border)',
            background: done ? 'rgba(74,222,128,0.1)' : open ? 'var(--ff-orange-dim)' : 'transparent',
            color: done ? 'var(--ff-success)' : open ? 'var(--ff-orange)' : 'var(--ff-text-3)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'var(--ff-mono)', fontSize: 11, fontWeight: 600,
          }}>
            {done ? <IconCheck size={14}/> : n}
          </div>
          <span style={{ fontFamily: 'var(--ff-display)', fontSize: 17, fontWeight: 600,
            color: open ? 'var(--ff-text)' : 'var(--ff-text-3)' }}>{title}</span>
        </div>
        {done && (
          <button onClick={onEdit} style={{ background: 'none', border: 'none', color: 'var(--ff-orange)',
            fontSize: 13, fontWeight: 500, cursor: 'pointer', padding: 4 }}>
            Edit
          </button>
        )}
      </div>
      {open && children}
    </div>
  );
}

function Field({ label, type = 'text', autoComplete, inputMode, placeholder }) {
  return (
    <div style={{ marginBottom: 10 }}>
      <label style={{ display: 'block', fontSize: 12, color: 'var(--ff-text-2)', marginBottom: 6 }}>{label}</label>
      <input type={type} autoComplete={autoComplete} inputMode={inputMode} placeholder={placeholder}
        style={{
          width: '100%', minHeight: 48, padding: '12px 14px',
          background: 'var(--ff-surface)', border: '1px solid var(--ff-border)', borderRadius: 4,
          color: 'var(--ff-text)', fontSize: 16, fontFamily: 'var(--ff-body)',
          outline: 'none',
        }}/>
    </div>
  );
}

// Order confirmation
function OrderComplete({ onBack }) {
  return (
    <div style={{ padding: '64px 24px', textAlign: 'center', minHeight: '100%' }}>
      <div style={{ width: 80, height: 80, borderRadius: 40,
        background: 'rgba(74,222,128,0.08)', border: '1px solid rgba(74,222,128,0.4)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 24px' }}>
        <IconCheck size={32} color="var(--ff-success)"/>
      </div>
      <div className="eyebrow" style={{ marginBottom: 8, color: 'var(--ff-success)' }}>ORDER PLACED</div>
      <h1 className="display" style={{ fontSize: 30, margin: 0, fontWeight: 700, letterSpacing: '-0.02em' }}>
        Thanks. We’re on it.
      </h1>
      <p style={{ marginTop: 14, color: 'var(--ff-text-2)', fontSize: 15, lineHeight: 1.6 }}>
        Confirmation sent to your email. Your order ships from our Texas facility within 24 hours.
      </p>
      <div style={{ marginTop: 24, padding: 16, background: 'var(--ff-surface)', border: '1px solid var(--ff-border)',
        borderRadius: 4, textAlign: 'left' }}>
        <div className="mono" style={{ fontSize: 11, color: 'var(--ff-text-3)', letterSpacing: '0.12em', marginBottom: 8 }}>ORDER</div>
        <div className="mono" style={{ fontSize: 18, fontWeight: 600 }}>FF-2026-0481</div>
      </div>
      <button onClick={onBack} className="btn btn-primary tap" style={{ width: '100%', marginTop: 24, height: 52 }}>
        Continue shopping
      </button>
    </div>
  );
}

Object.assign(window, { CartDrawer, CheckoutScreen, OrderComplete });
