// CheckoutScreen — review the line items, then mint a checkout session and
// redirect to the mock-pay page (or, in production, Stripe Checkout).

function CheckoutScreen({ items, onBack }) {
  const [status, setStatus] = React.useState('idle');   // idle | creating | redirecting | error
  const [error, setError] = React.useState(null);

  const subtotal = items.reduce((sum, it) => sum + (it.price_cents || 0) * (it.quantity || 1), 0);
  const shipping = 0;        // free white-glove delivery, you romantic
  const total = subtotal + shipping;
  const currency = items[0]?.currency || 'USD';

  const goPay = async () => {
    setStatus('creating');
    setError(null);
    try {
      const session = await window.api.createCheckoutSession({
        items: items.map((it) => ({ artwork_id: it.id, quantity: it.quantity || 1 })),
      });
      setStatus('redirecting');
      window.location.href = session.url;
    } catch (err) {
      setError(err.message || 'Couldn\'t start checkout.');
      setStatus('error');
    }
  };

  return (
    <div style={{ paddingBottom: 100 }}>
      <AppHeader title="Checkout" onBack={onBack}/>

      <div style={{ padding: '20px' }}>
        <Eyebrow style={{ marginBottom: 12 }}>In your bag</Eyebrow>

        {items.map((a) => (
          <div key={a.id} style={{ display: 'flex', gap: 14, padding: '14px 0', borderBottom: '1px solid var(--line)' }}>
            <div style={{
              width: 64, height: 80, borderRadius: 6, padding: 4,
              background: '#bfa27a', boxShadow: 'var(--shadow-frame)', flexShrink: 0,
            }}>
              <div style={{ width: '100%', height: '100%', borderRadius: 3, background: a.grad }}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 500, color: 'var(--fg)' }}>
                {a.title}{a.num && <span style={{ color: 'var(--fg-faint)', fontStyle: 'italic' }}>, {a.num}</span>}
              </div>
              <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 12, color: 'var(--fg-muted)', marginTop: 2 }}>
                — {a.artist}
              </div>
              {a.dimensions && (
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--fg-faint)', marginTop: 6 }}>
                  {a.dimensions}
                </div>
              )}
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 15, color: 'var(--fg)' }}>
              {window.api.formatPrice(a.price_cents, currency)}
            </div>
          </div>
        ))}

        <div style={{ padding: '20px 0 4px' }}>
          <SummaryRow label="Subtotal" value={window.api.formatPrice(subtotal, currency)}/>
          <SummaryRow label="Shipping" value={shipping === 0 ? 'Complimentary' : window.api.formatPrice(shipping, currency)}/>
          <SummaryRow label="Total" value={window.api.formatPrice(total, currency)} bold/>
        </div>

        <p style={{
          margin: '20px 0 0', fontFamily: 'var(--font-display)', fontStyle: 'italic',
          fontSize: 13, color: 'var(--fg-muted)', lineHeight: 1.5,
        }}>
          We wrap each piece in archival tissue and tuck a handwritten note between the boards.
        </p>

        {error && (
          <div style={{ marginTop: 16, fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--accent)' }}>
            {error}
          </div>
        )}
      </div>

      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0, padding: '14px 20px calc(22px + env(safe-area-inset-bottom))',
        background: 'rgba(251,247,236,0.92)', backdropFilter: 'blur(12px)',
        borderTop: '1px solid var(--line)',
      }}>
        <Button
          variant="primary" full iconRight="arrowRight"
          disabled={status === 'creating' || status === 'redirecting'}
          onClick={goPay}
        >
          {status === 'creating' ? 'Opening checkout…' :
           status === 'redirecting' ? 'Redirecting…' :
           `Pay ${window.api.formatPrice(total, currency)}`}
        </Button>
      </div>
    </div>
  );
}

function SummaryRow({ label, value, bold }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
      padding: '8px 0',
      borderTop: bold ? '1px solid var(--line)' : 'none',
      marginTop: bold ? 8 : 0, paddingTop: bold ? 14 : 8,
    }}>
      <div style={{ fontFamily: 'var(--font-body)', fontSize: bold ? 14 : 13, color: bold ? 'var(--fg)' : 'var(--fg-muted)' }}>{label}</div>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: bold ? 18 : 14, fontWeight: bold ? 500 : 400, color: 'var(--fg)' }}>{value}</div>
    </div>
  );
}

function OrderSuccessScreen({ order, onBack, onViewOrders }) {
  return (
    <div style={{ paddingBottom: 40 }}>
      <AppHeader title="" onBack={onBack}/>
      <div style={{ padding: '40px 24px 24px', textAlign: 'center' }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 24 }}>
          {eightBall(72)}
        </div>
        <Eyebrow style={{ marginBottom: 10 }}>Confirmed</Eyebrow>
        <h1 style={{
          margin: 0, fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 400,
          lineHeight: 1.15, color: 'var(--fg)',
        }}>
          It's in.
        </h1>
        <p style={{
          margin: '12px auto 0', maxWidth: 320,
          fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 15,
          color: 'var(--fg-muted)', lineHeight: 1.5,
        }}>
          A receipt is on the way. Order <strong style={{ fontStyle: 'normal', color: 'var(--fg)' }}>#{order?.short_id || '—'}</strong>.
        </p>

        <div style={{ marginTop: 32 }}>
          <Button variant="primary" onClick={onViewOrders} iconRight="arrowRight">View orders</Button>
        </div>
        <div style={{ marginTop: 12 }}>
          <button onClick={onBack} style={{
            background: 'none', border: 'none', cursor: 'pointer',
            fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--fg-muted)',
          }}>
            Back to browsing
          </button>
        </div>
      </div>
    </div>
  );
}

window.CheckoutScreen = CheckoutScreen;
window.OrderSuccessScreen = OrderSuccessScreen;
