/* ============================================================
   CART + MULTI-STEP CHECKOUT + CONFIRMATION
   ============================================================ */
function CartPage() {
  const { cartLines, subtotal, setQty, removeItem, money, nav, currency } = useStore();
  if (cartLines.length === 0) {
    return (
      <div className="container" style={{ padding: 'clamp(70px,12vw,140px) var(--gutter)', textAlign: 'center', maxWidth: 560 }}>
        <I.bag width={52} height={52} style={{ opacity: .3, margin: '0 auto 18px' }} />
        <h1 style={{ fontSize: 'clamp(34px,5vw,52px)' }}>Your bag is empty</h1>
        <p className="muted" style={{ marginTop: 12, fontSize: 16 }}>Let's find something beautiful for your next celebration.</p>
        <button className="btn btn-gold btn-lg" style={{ marginTop: 28 }} onClick={() => nav('shop')}>Shop the collection</button>
      </div>
    );
  }
  const shipping = subtotal >= BB.BRAND.shipping.freeThreshold ? 0 : BB.BRAND.shipping.flat;
  return (
    <div className="container wide" style={{ padding: 'clamp(36px,5vw,64px) var(--gutter) clamp(64px,9vw,110px)' }}>
      <h1 style={{ fontSize: 'clamp(36px,5vw,60px)', marginBottom: 8 }}>Your Bag</h1>
      <p className="muted" style={{ marginBottom: 36 }}>{cartLines.length} item{cartLines.length !== 1 ? 's' : ''} · prices in {currency}</p>
      <div className="cart-layout">
        <div>
          {cartLines.map(l => (
            <div key={l.idx} style={{ display: 'flex', gap: 20, padding: '24px 0', borderBottom: '1px solid var(--line)' }}>
              <Ph src={l.product.img} label="product" variant={l.product.ph} style={{ width: 110, height: 132, borderRadius: 'var(--r-md)', flexShrink: 0, cursor: 'pointer' }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12 }}>
                  <div>
                    <h3 onClick={() => nav('product', { id: l.product.id })} style={{ fontSize: 23, cursor: 'pointer' }}>{l.product.name}</h3>
                    {Object.keys(l.opts || {}).length > 0 && <p style={{ fontSize: 13, color: 'var(--ink-soft)', marginTop: 4 }}>{Object.entries(l.opts).map(([k, v]) => `${k}: ${v}`).join(' · ')}</p>}
                  </div>
                  <span style={{ fontFamily: 'var(--serif)', fontSize: 24, whiteSpace: 'nowrap' }}>{money(l.lineTotal)}</span>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 18 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, border: '1.5px solid var(--line)', borderRadius: 100, padding: 4, background: 'var(--ivory)' }}>
                    <button onClick={() => setQty(l.idx, l.qty - 1)} style={{ width: 32, height: 32, display: 'grid', placeItems: 'center', borderRadius: 100 }}><I.minus width={15} height={15} /></button>
                    <span style={{ minWidth: 26, textAlign: 'center' }}>{l.qty}</span>
                    <button onClick={() => setQty(l.idx, l.qty + 1)} style={{ width: 32, height: 32, display: 'grid', placeItems: 'center', borderRadius: 100 }}><I.plus width={15} height={15} /></button>
                  </div>
                  <button onClick={() => removeItem(l.idx)} className="link-u" style={{ fontSize: 13, color: 'var(--ink-soft)' }}>Remove</button>
                </div>
              </div>
            </div>
          ))}
          <button onClick={() => nav('shop')} className="link-u" style={{ marginTop: 24, fontSize: 14, display: 'inline-flex', gap: 8, alignItems: 'center' }}><span style={{ transform: 'rotate(180deg)', display: 'inline-flex' }}><I.arrow width={16} height={16} /></span> Continue shopping</button>
        </div>
        <OrderSummary subtotal={subtotal} shipping={shipping} cta="Proceed to checkout" onCta={() => nav('checkout')} />
      </div>
    </div>
  );
}

function OrderSummary({ subtotal, shipping, cta, onCta, compact }) {
  const { money } = useStore();
  const total = subtotal + shipping;
  return (
    <aside style={{ background: 'var(--ivory)', borderRadius: 'var(--r-lg)', padding: 28, boxShadow: 'var(--shadow-sm)', alignSelf: 'start', position: compact ? 'static' : 'sticky', top: 100 }}>
      <h3 style={{ fontSize: 24, marginBottom: 20 }}>Order summary</h3>
      <Row l="Subtotal" v={money(subtotal)} />
      <Row l="Shipping" v={shipping === 0 ? 'Free' : money(shipping)} note={shipping === 0 ? 'Free over ' + money(BB.BRAND.shipping.freeThreshold) : undefined} />
      <Row l="Est. taxes" v="Calculated at pay" />
      <hr className="divider" style={{ margin: '16px 0' }} />
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <span style={{ fontWeight: 500 }}>Total</span>
        <span style={{ fontFamily: 'var(--serif)', fontSize: 32 }}>{money(total)}</span>
      </div>
      {cta && <button className="btn btn-gold btn-block btn-lg" style={{ marginTop: 22 }} onClick={onCta}>{cta}</button>}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, marginTop: 16, fontSize: 12, color: 'var(--ink-faint)' }}>
        <I.shield width={15} height={15} /> Secure SSL checkout
      </div>
    </aside>
  );
}
function Row({ l, v, note }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '7px 0', fontSize: 14.5 }}>
      <span className="muted">{l}{note && <em style={{ display: 'block', fontStyle: 'normal', fontSize: 11.5, color: 'var(--sage-deep)' }}>{note}</em>}</span>
      <span>{v}</span>
    </div>
  );
}

/* ---------- Checkout (multi-step) ---------- */
function CheckoutPage() {
  const { cartLines, subtotal, nav, currency, placeOrder, money } = useStore();
  const [step, setStep] = useState(1);
  const [form, setForm] = useState({ email: '', firstName: '', lastName: '', phone: '', address: '', city: '', country: 'United States', method: 'card', account: false });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const shipping = subtotal >= BB.BRAND.shipping.freeThreshold ? 0 : BB.BRAND.shipping.flat;

  if (cartLines.length === 0) {
    return (
      <div className="container" style={{ padding: '120px var(--gutter)', textAlign: 'center' }}>
        <h1 style={{ fontSize: 44 }}>Nothing to check out</h1>
        <button className="btn btn-gold btn-lg" style={{ marginTop: 24 }} onClick={() => nav('shop')}>Browse the shop</button>
      </div>
    );
  }

  const steps = ['Information', 'Shipping', 'Payment'];
  const next = () => setStep(s => Math.min(3, s + 1));
  const pay = () => {
    const order = placeOrder({ email: form.email, name: `${form.firstName} ${form.lastName}`, address: `${form.address}, ${form.city}, ${form.country}`, method: form.method, shipping });
    nav('confirm', { num: order.num });
  };

  return (
    <div className="container wide" style={{ padding: 'clamp(28px,4vw,48px) var(--gutter) clamp(64px,9vw,110px)' }}>
      <button onClick={() => nav('cart')} className="link-u" style={{ fontSize: 13.5, marginBottom: 18, display: 'inline-flex', gap: 8, alignItems: 'center' }}><span style={{ transform: 'rotate(180deg)', display: 'inline-flex' }}><I.arrow width={15} height={15} /></span> Back to bag</button>
      <h1 style={{ fontSize: 'clamp(34px,5vw,56px)', marginBottom: 8 }}>Checkout</h1>

      {/* stepper */}
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', margin: '20px 0 36px', flexWrap: 'wrap' }}>
        {steps.map((s, i) => (
          <React.Fragment key={s}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 13.5, fontWeight: 500, color: step >= i + 1 ? 'var(--ink)' : 'var(--ink-faint)' }}>
              <span style={{ width: 26, height: 26, borderRadius: 100, display: 'grid', placeItems: 'center', fontSize: 12, background: step > i + 1 ? 'var(--sage)' : step === i + 1 ? 'var(--ink)' : 'var(--line)', color: step >= i + 1 ? '#fff' : 'var(--ink-soft)' }}>{step > i + 1 ? <I.check width={14} height={14} /> : i + 1}</span>
              {s}
            </span>
            {i < 2 && <span style={{ flex: '0 1 40px', height: 1, background: 'var(--line)' }} />}
          </React.Fragment>
        ))}
      </div>

      <div className="cart-layout">
        <div>
          {/* dual currency reminder */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, background: 'var(--sage-soft)', borderRadius: 'var(--r-md)', padding: '14px 18px', marginBottom: 26 }}>
            <span style={{ fontSize: 13.5, display: 'flex', gap: 9, alignItems: 'center' }}><I.globe width={18} height={18} style={{ color: 'var(--sage-deep)' }} /> Paying in <strong>{currency}</strong></span>
            <CurrencySwitch compact />
          </div>

          {step === 1 && (
            <Section title="Contact & details">
              <div className="field" style={{ marginBottom: 16 }}><label>Email</label><input className="input" type="email" value={form.email} onChange={e => set('email', e.target.value)} placeholder="you@email.com" /></div>
              <div className="form-row">
                <div className="field"><label>First name</label><input className="input" value={form.firstName} onChange={e => set('firstName', e.target.value)} placeholder="Alex" /></div>
                <div className="field"><label>Last name</label><input className="input" value={form.lastName} onChange={e => set('lastName', e.target.value)} placeholder="Morgan" /></div>
              </div>
              <div className="field" style={{ marginTop: 16 }}><label>Phone</label><input className="input" value={form.phone} onChange={e => set('phone', e.target.value)} placeholder="+1 …" /></div>
              <label style={{ display: 'flex', gap: 10, alignItems: 'center', marginTop: 18, fontSize: 14, cursor: 'pointer' }}>
                <input type="checkbox" checked={form.account} onChange={e => set('account', e.target.checked)} style={{ width: 17, height: 17, accentColor: 'var(--gold-deep)' }} />
                Create an account for faster checkout &amp; order tracking
              </label>
              <button className="btn btn-primary btn-lg" style={{ marginTop: 26 }} disabled={!form.email} onClick={next}>Continue to shipping</button>
            </Section>
          )}

          {step === 2 && (
            <Section title="Shipping address">
              <div className="field" style={{ marginBottom: 16 }}><label>Street address</label><input className="input" value={form.address} onChange={e => set('address', e.target.value)} placeholder="123 Example Street" /></div>
              <div className="form-row">
                <div className="field"><label>City</label><input className="input" value={form.city} onChange={e => set('city', e.target.value)} placeholder="Your city" /></div>
                <div className="field"><label>Country</label>
                  <select className="input" value={form.country} onChange={e => set('country', e.target.value)} style={{ cursor: 'pointer' }}>
                    {['United States', 'United Kingdom', 'Canada', 'Australia', 'Germany', 'Other'].map(c => <option key={c}>{c}</option>)}
                  </select>
                </div>
              </div>
              <div style={{ marginTop: 22 }}>
                <p className="eyebrow" style={{ marginBottom: 10 }}>Delivery method</p>
                {[['Standard', shipping === 0 ? 'Free' : money(shipping), '3–5 working days'], ['Express', money(12000), '1–2 working days']].map(([n, price, eta], i) => (
                  <label key={n} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '15px 18px', border: '1.5px solid var(--line)', borderRadius: 'var(--r-md)', marginBottom: 10, cursor: 'pointer' }}>
                    <input type="radio" name="ship" defaultChecked={i === 0} style={{ accentColor: 'var(--gold-deep)', width: 17, height: 17 }} />
                    <span style={{ flex: 1 }}><strong style={{ fontWeight: 500 }}>{n}</strong><br /><span style={{ fontSize: 13, color: 'var(--ink-soft)' }}>{eta}</span></span>
                    <span style={{ fontWeight: 500 }}>{price}</span>
                  </label>
                ))}
              </div>
              <button className="btn btn-primary btn-lg" style={{ marginTop: 20 }} disabled={!form.address || !form.city} onClick={next}>Continue to payment</button>
            </Section>
          )}

          {step === 3 && (
            <Section title="Payment">
              <p className="muted" style={{ fontSize: 14, marginBottom: 18 }}>All transactions are secure and encrypted. You're paying in <strong style={{ color: 'var(--ink)' }}>{currency}</strong>.</p>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {[
                  ['card', 'Card', 'Visa · Mastercard · Amex'],
                  ...(currency === BB.BRAND.currency.primary.code ? [['transfer', 'Bank Transfer', 'Pay by direct transfer — auto-confirmed']] : [['paypal', 'PayPal / Card', 'Pay securely online']]),
                ].map(([id, n, s]) => (
                  <label key={id} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '16px 18px', border: '1.5px solid ' + (form.method === id ? 'var(--gold)' : 'var(--line)'), borderRadius: 'var(--r-md)', cursor: 'pointer', background: form.method === id ? 'var(--gold-soft)' : 'var(--ivory)', transition: 'all .25s' }}>
                    <input type="radio" name="pay" checked={form.method === id} onChange={() => set('method', id)} style={{ accentColor: 'var(--gold-deep)', width: 17, height: 17 }} />
                    <span style={{ flex: 1 }}><strong style={{ fontWeight: 500 }}>{n}</strong><br /><span style={{ fontSize: 13, color: 'var(--ink-soft)' }}>{s}</span></span>
                  </label>
                ))}
              </div>
              {form.method === 'card' && (
                <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 14 }}>
                  <div className="field"><label>Card number</label><input className="input" placeholder="1234 5678 9012 3456" /></div>
                  <div className="form-row">
                    <div className="field"><label>Expiry</label><input className="input" placeholder="MM / YY" /></div>
                    <div className="field"><label>CVC</label><input className="input" placeholder="123" /></div>
                  </div>
                </div>
              )}
              {form.method === 'transfer' && (
                <div style={{ marginTop: 16, background: 'var(--cream-deep)', borderRadius: 'var(--r-md)', padding: 18, fontSize: 14, lineHeight: 1.7 }}>
                  <p className="eyebrow" style={{ marginBottom: 8 }}>Transfer to</p>
                  {BB.BRAND.bank.legal}<br />{BB.BRAND.bank.name} · <strong>{BB.BRAND.bank.account}</strong><br /><span className="muted">Your order confirms automatically on receipt.</span>
                </div>
              )}
              <button className="btn btn-gold btn-block btn-lg" style={{ marginTop: 24 }} onClick={pay}>Pay {money(subtotal + shipping)}</button>
              <p style={{ textAlign: 'center', fontSize: 12, color: 'var(--ink-faint)', marginTop: 14, display: 'flex', gap: 7, justifyContent: 'center', alignItems: 'center' }}><I.shield width={14} height={14} /> Protected by 256-bit SSL encryption</p>
            </Section>
          )}
        </div>

        {/* summary with line items */}
        <aside style={{ background: 'var(--ivory)', borderRadius: 'var(--r-lg)', padding: 26, boxShadow: 'var(--shadow-sm)', alignSelf: 'start', position: 'sticky', top: 100 }}>
          <h3 style={{ fontSize: 22, marginBottom: 18 }}>In your bag</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 18, maxHeight: 260, overflowY: 'auto' }}>
            {cartLines.map(l => (
              <div key={l.idx} style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                <div style={{ position: 'relative', flexShrink: 0 }}>
                  <Ph src={l.product.img} label="" variant={l.product.ph} style={{ width: 52, height: 60, borderRadius: 'var(--r-sm)' }} />
                  <span style={{ position: 'absolute', top: -7, right: -7, width: 20, height: 20, borderRadius: 100, background: 'var(--ink-soft)', color: '#fff', fontSize: 11, display: 'grid', placeItems: 'center' }}>{l.qty}</span>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 14, fontWeight: 500, lineHeight: 1.2 }}>{l.product.name}</div></div>
                <span style={{ fontSize: 13.5 }}>{money(l.lineTotal)}</span>
              </div>
            ))}
          </div>
          <hr className="divider" />
          <div style={{ paddingTop: 14 }}>
            <Row l="Subtotal" v={money(subtotal)} />
            <Row l="Shipping" v={shipping === 0 ? 'Free' : money(shipping)} />
          </div>
          <hr className="divider" style={{ margin: '12px 0' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <span style={{ fontWeight: 500 }}>Total</span><span style={{ fontFamily: 'var(--serif)', fontSize: 28 }}>{money(subtotal + shipping)}</span>
          </div>
        </aside>
      </div>
    </div>
  );
}

function Section({ title, children }) {
  return <div style={{ animation: 'fade .4s' }}><h2 style={{ fontSize: 28, marginBottom: 22 }}>{title}</h2>{children}</div>;
}

/* ---------- Order confirmation ---------- */
function ConfirmPage({ params }) {
  const { orders, nav, money } = useStore();
  const order = orders.find(o => o.num === params.num) || orders[0];
  if (!order) { return <div className="container" style={{ padding: '120px var(--gutter)', textAlign: 'center' }}><h1>No order found</h1><button className="btn btn-gold" style={{ marginTop: 20 }} onClick={() => nav('shop')}>Shop</button></div>; }
  return (
    <div className="container" style={{ padding: 'clamp(50px,7vw,90px) var(--gutter) clamp(64px,9vw,110px)', maxWidth: 720, textAlign: 'center' }}>
      <div style={{ width: 76, height: 76, borderRadius: 100, background: 'var(--sage)', color: '#fff', display: 'grid', placeItems: 'center', margin: '0 auto 24px', animation: 'scaleIn .5s cubic-bezier(.2,.8,.2,1)' }}><I.check width={38} height={38} /></div>
      <p className="eyebrow">Order confirmed</p>
      <h1 style={{ fontSize: 'clamp(36px,5vw,58px)', margin: '14px 0 12px' }}>Thank you — it's <em style={{ fontStyle: 'italic' }}>on its way</em></h1>
      <p className="muted" style={{ fontSize: 16.5 }}>We've emailed your receipt. Order <strong style={{ color: 'var(--ink)' }}>#{order.num}</strong> is now being lovingly prepared.</p>
      <div style={{ background: 'var(--ivory)', borderRadius: 'var(--r-lg)', padding: 26, marginTop: 32, textAlign: 'left', boxShadow: 'var(--shadow-sm)' }}>
        {order.lines.map((l, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', fontSize: 14.5 }}>
            <span>{l.qty} × {l.name}</span><span>{BB.fmt(l.price * l.qty, order.currency)}</span>
          </div>
        ))}
        <hr className="divider" style={{ margin: '12px 0' }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', fontWeight: 500 }}><span>Total paid</span><span style={{ fontFamily: 'var(--serif)', fontSize: 22 }}>{BB.fmt(order.subtotal + (order.shipping || 0), order.currency)}</span></div>
      </div>
      <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 30, flexWrap: 'wrap' }}>
        <button className="btn btn-primary btn-lg" onClick={() => nav('account')}>Track my order</button>
        <button className="btn btn-outline btn-lg" onClick={() => nav('shop')}>Keep shopping</button>
      </div>
    </div>
  );
}

Object.assign(window, { CartPage, CheckoutPage, ConfirmPage, OrderSummary });
