// pages/cart-checkout.jsx — full cart page + multi-step checkout

function CartPage() {
  const store = useStore();
  const [coupon, setCoupon] = React.useState(store.state.couponCode || '');
  const [couponOpen, setCouponOpen] = React.useState(!!store.state.couponCode);
  const [couponMsg, setCouponMsg] = React.useState(null);
  const validation = store.cartValidation();
  const quote = store.cartQuote({ shipMethod: 'standard', couponCode: store.state.couponCode || undefined });
  const lines = validation.lines.filter((l) => l.product);
  const issues = validation.issues;
  const subtotal = quote.subtotal;
  const shipping = quote.shipping;
  const total = quote.total;
  const ship = window.CustomerCommerce.shippingSettings();
  const progress = quote.freeShippingProgress || window.CustomerCommerce.freeShippingProgress(subtotal);

  const applyCoupon = () => {
    if (!store.setCouponCode) return;
    const code = store.setCouponCode(coupon);
    const q = store.cartQuote({ shipMethod: 'standard', couponCode: code });
    if (!code) {
      setCouponMsg({ ok: true, text: 'Coupon cleared.' });
      return;
    }
    if (q.promotion && q.promotion.ok) {
      setCouponMsg({ ok: true, text: q.promotion.message });
    } else {
      setCouponMsg({ ok: false, text: (q.promotion && q.promotion.message) || 'This coupon code is not valid.' });
      store.setCouponCode('');
    }
  };

  return (
    <main className="container" style={{ paddingBlock: 48 }}>
      <div className="crumb" style={{ marginBottom: 16 }}>
        <a href="#/">Home</a><span className="sep">/</span><span className="here">Shopping Bag</span>
      </div>
      <h1 className="serif" style={{ fontSize: 'var(--fs-display)', marginBottom: 32 }}>Your shopping bag</h1>

      {lines.length === 0 ? (
        <EmptyState icon="cart" title="Your bag is empty"
                    note="Browse pebbles, pots and decor to get started."
                    cta={{ label: 'Shop pebbles', href: '#/collections/pebbles' }} />
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 'clamp(24px, 4vw, 56px)' }} className="cart-grid">
          <div>
            {issues.length > 0 && (
              <div style={{ background: 'var(--cream)', border: '1px solid var(--line-strong)', borderRadius: 12, padding: 16, marginBottom: 16 }}>
                <strong>Some items need attention</strong>
                <ul style={{ marginTop: 8, paddingLeft: 18, color: 'var(--ink-2)', fontSize: '.9rem' }}>
                  {issues.map((i) => (
                    <li key={i.productId + i.variant} style={{ marginBottom: 6 }}>
                      {i.message}{' '}
                      {i.product ? (
                        <a href={'#/products/' + i.product.slug} style={{ color: 'var(--forest)' }}>Choose another size</a>
                      ) : null}
                      {' · '}
                      <button onClick={() => store.removeCart(i.productId, i.variant)} style={{ color: 'var(--terra)', textDecoration: 'underline' }}>Remove</button>
                    </li>
                  ))}
                </ul>
              </div>
            )}
            <div className="cart-mobile-list">
              {lines.map((l) => (
                <div key={l.productId + l.variant} className="cart-mobile-card">
                  <a href={'#/products/' + l.product.slug} className="cart-mobile-card__img">
                    <img src={l.product.image} alt={l.product.name} />
                  </a>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <a href={'#/products/' + l.product.slug} className="serif" style={{ fontSize: '1rem' }}>{l.product.name}</a>
                    <div style={{ color: 'var(--muted)', fontSize: '.82rem', marginTop: 4 }}>{l.variant} · {HAP.formatPrice(l.unit)}</div>
                    <div className="cart-line__qty" style={{ marginTop: 10 }}>
                      <button onClick={() => store.setCartQty(l.productId, l.variant, l.qty - 1)} aria-label="Decrease"><Icon name="minus" size={14} /></button>
                      <span className="count">{l.qty}</span>
                      <button onClick={() => store.setCartQty(l.productId, l.variant, l.qty + 1)} aria-label="Increase"><Icon name="plus" size={14} /></button>
                    </div>
                  </div>
                  <div style={{ textAlign: 'right', fontWeight: 600 }}>{HAP.formatPrice(l.line)}</div>
                </div>
              ))}
            </div>
            <table className="cart-desktop-table" style={{ width: '100%' }}>
              <thead>
                <tr style={{ borderBottom: '1px solid var(--line-strong)' }}>
                  <th style={{ textAlign: 'left', padding: '12px 0', fontSize: '.75rem', textTransform: 'uppercase', letterSpacing: '.1em', color: 'var(--muted)' }} colSpan="2">Product</th>
                  <th style={{ textAlign: 'left', padding: '12px 0', fontSize: '.75rem', textTransform: 'uppercase', letterSpacing: '.1em', color: 'var(--muted)' }}>Quantity</th>
                  <th style={{ textAlign: 'right', padding: '12px 0', fontSize: '.75rem', textTransform: 'uppercase', letterSpacing: '.1em', color: 'var(--muted)' }}>Total</th>
                </tr>
              </thead>
              <tbody>
                {lines.map((l) => (
                  <tr key={l.productId + l.variant} style={{ borderBottom: '1px solid var(--line)', opacity: l.ok ? 1 : 0.55 }}>
                    <td style={{ padding: '20px 0', width: 100 }}>
                      <a href={'#/products/' + l.product.slug} style={{ display: 'block', width: 84, height: 100, borderRadius: 8, overflow: 'hidden', background: 'var(--cream)' }}>
                        <img src={l.product.image} alt={l.product.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                      </a>
                    </td>
                    <td style={{ padding: '20px 16px 20px 0' }}>
                      <a href={'#/products/' + l.product.slug} className="serif" style={{ fontSize: '1.05rem' }}>{l.product.name}</a>
                      <div style={{ color: 'var(--muted)', fontSize: '.82rem', marginTop: 4 }}>{l.variant} · {HAP.formatPrice(l.unit)}</div>
                      {!l.ok && <div style={{ color: 'var(--danger)', fontSize: '.8rem', marginTop: 4 }}>{l.message}</div>}
                      <button onClick={() => store.removeCart(l.productId, l.variant)}
                              style={{ fontSize: '.75rem', color: 'var(--muted)', marginTop: 8, letterSpacing: '.06em', textTransform: 'uppercase' }}>
                        <Icon name="trash" size={12} style={{ verticalAlign: 'middle', marginRight: 4 }} /> Remove
                      </button>
                    </td>
                    <td style={{ padding: '20px 0' }}>
                      <div className="cart-line__qty">
                        <button onClick={() => store.setCartQty(l.productId, l.variant, l.qty - 1)} aria-label="Decrease"><Icon name="minus" size={14} /></button>
                        <span className="count">{l.qty}</span>
                        <button onClick={() => store.setCartQty(l.productId, l.variant, l.qty + 1)} aria-label="Increase"><Icon name="plus" size={14} /></button>
                      </div>
                    </td>
                    <td style={{ padding: '20px 0', textAlign: 'right' }}>{HAP.formatPrice(l.line)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            <div style={{ marginTop: 24, display: 'flex', justifyContent: 'space-between', gap: 12 }}>
              <a className="btn btn--ghost" href="#/collections/pebbles"><Icon name="chev-left" size={14} /> Continue shopping</a>
              <button className="btn btn--secondary" onClick={() => store.clearCart()}>Clear bag</button>
            </div>
          </div>

          <aside>
            <div style={{ position: 'sticky', top: 'calc(var(--header-h) + 16px)', background: 'var(--cream)', padding: 28, borderRadius: 16 }}>
              <h3 className="serif" style={{ fontSize: '1.4rem', marginBottom: 18 }}>Order summary</h3>
              <Row k="Subtotal" v={HAP.formatPrice(subtotal)} />
              <Row k="Shipping" v={shipping === 0 ? <span style={{ color: 'var(--success)' }}>Free</span> : HAP.formatPrice(shipping)} />
              <Row k="Tax (GST)" v="Included · shown at checkout" small />
              {(quote.discount || 0) > 0 && <Row k="Discount" v={<span style={{ color: 'var(--success)' }}>{'-' + HAP.formatPrice(quote.discount)}</span>} />}
              <div style={{ height: 1, background: 'var(--line-strong)', margin: '16px 0' }}></div>
              <div className="spread" style={{ fontFamily: 'var(--serif)', fontSize: '1.4rem' }}>
                <span>Total</span><span>{HAP.formatPrice(total)}</span>
              </div>
              {progress && !progress.eligible && progress.remaining > 0 && (
                <p style={{ fontSize: '.78rem', color: 'var(--muted)', marginTop: 8 }}>{progress.message}</p>
              )}
              {progress && progress.eligible && (
                <p style={{ fontSize: '.78rem', color: 'var(--success)', marginTop: 8 }}>{progress.message}</p>
              )}
              {!progress && <p style={{ fontSize: '.78rem', color: 'var(--muted)', marginTop: 8 }}>Free standard shipping above {HAP.formatPrice(ship.freeAbove)}.</p>}

              <details style={{ marginTop: 18 }} open={!!couponOpen}>
                <summary style={{ cursor: 'pointer', fontSize: '.85rem', color: 'var(--ink-2)' }} onClick={(e) => { e.preventDefault(); setCouponOpen((o) => !o); }}>Have a discount code?</summary>
                <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
                  <label className="sr-only" htmlFor="cart-coupon">Coupon code</label>
                  <input id="cart-coupon" className="input" style={{ flex: 1 }} value={coupon} onChange={(e) => setCoupon(e.target.value)} placeholder="Enter code" autoComplete="off" />
                  <button type="button" className="btn btn--secondary btn--sm" onClick={applyCoupon}>Apply</button>
                </div>
                {couponMsg && <p style={{ fontSize: '.82rem', color: couponMsg.ok ? 'var(--success)' : 'var(--danger)', marginTop: 8 }}>{couponMsg.text}</p>}
              </details>

              <a className={'btn btn--primary btn--full btn--lg' + (validation.canCheckout ? '' : '')}
                 href={validation.canCheckout ? '#/checkout' : '#/cart'}
                 onClick={(e) => {
                   if (!validation.canCheckout) {
                     e.preventDefault();
                     HAPStore.notify('Fix unavailable items before checkout');
                   } else if (window.CustomerAnalytics) window.CustomerAnalytics.begin_checkout();
                 }}
                 style={{ marginTop: 18, opacity: validation.canCheckout ? 1 : 0.5 }}>
                Proceed to checkout <Icon name="arrow-right" size={16} />
              </a>
              <div className="checkout-place-order" style={{ display: 'none' }}>
                <a className="btn btn--primary btn--lg"
                   href={validation.canCheckout ? '#/checkout' : '#/cart'}
                   onClick={(e) => { if (!validation.canCheckout) { e.preventDefault(); HAPStore.notify('Fix unavailable items before checkout'); } }}>
                  PLACE ORDER · {HAP.formatPrice(total)}
                </a>
              </div>
            </div>
          </aside>
        </div>
      )}

      <style>{`
        @media (max-width: 980px) { .cart-grid { grid-template-columns: 1fr !important; } }
      `}</style>
    </main>
  );
}

function Row({ k, v, small }) {
  return (
    <div className="spread" style={{ paddingBlock: 6, fontSize: small ? '.85rem' : '.95rem', color: small ? 'var(--muted)' : 'var(--ink)' }}>
      <span>{k}</span><span>{v}</span>
    </div>
  );
}

// ----------------- Checkout -----------------
function CheckoutPage() {
  const store = useStore();
  const [step, setStep] = React.useState(1);
  const [data, setData] = React.useState({
    email: store.state.user?.email || '',
    firstName: '', lastName: '',
    address: '', address2: '', city: '', state: 'Kerala', pincode: '', phone: '',
    shipMethod: 'standard',
    payMethod: 'card',
    notes: '',
    saveInfo: true,
    idempotencyKey: 'chk-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8)
  });
  const [order, setOrder] = React.useState(null);
  const [paying, setPaying] = React.useState(false);
  const [payErr, setPayErr] = React.useState('');

  const quote = store.cartQuote({
    shipMethod: data.shipMethod,
    payMethod: data.payMethod,
    state: data.state,
  });
  const lines = quote.validated.okLines;
  const subtotal = quote.subtotal;
  const shipping = quote.shipping;
  const total = quote.total;
  const shipCfg = window.CustomerCommerce.shippingSettings();

  if (lines.length === 0 && !order) {
    return (
      <main className="container section">
        <EmptyState icon="cart" title="Your bag is empty"
                    note="Add a few things first."
                    cta={{ label: 'Shop pebbles', href: '#/collections/pebbles' }} />
      </main>
    );
  }

  const set = (patch) => setData((d) => ({ ...d, ...patch }));

  const submit = async () => {
    setPaying(true);
    setPayErr('');
    try {
      if (!quote.validated.canCheckout) throw Object.assign(new Error('Cart validation failed'), { code: 'CART_INVALID' });
      const result = store.placeOrder(data, { idempotencyKey: data.idempotencyKey });
      const o = result && result.then ? await result : result;
      setOrder(o);
      if (data.saveInfo && !store.state.user) store.signIn(data.email, data.firstName, data.phone);
      setStep(4);
    } catch (e) {
      setPayErr(e.message || 'Payment failed. Please try again — your bag is preserved.');
    } finally {
      setPaying(false);
    }
  };

  if (order) return <OrderConfirmation order={order} />;

  return (
    <main className="container" style={{ paddingBlock: 32 }}>
      <div className="spread" style={{ marginBottom: 20 }}>
        <a href="#/cart" className="btn btn--ghost btn--sm"><Icon name="chev-left" size={14} /> Back to bag</a>
        <div className="serif" style={{ fontSize: '1.4rem', fontStyle: 'italic', color: 'var(--forest)' }}>
          <span style={{ fontFamily: 'var(--sans)', fontWeight: 700, letterSpacing: '0.12em' }}>AMBADY</span>
        </div>
        <div style={{ fontSize: '.78rem', color: 'var(--muted)' }}><Icon name="lock" size={12} style={{ verticalAlign: 'middle' }} /> Secure checkout</div>
      </div>

      <Stepper step={step} setStep={setStep} />

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 'clamp(24px, 4vw, 56px)', marginTop: 32 }} className="checkout-grid">
        <div>
          {step === 1 && <ContactStep data={data} set={set} onNext={() => setStep(2)} />}
          {step === 2 && <ShippingStep data={data} set={set} onNext={() => setStep(3)} onBack={() => setStep(1)} shipCfg={shipCfg} />}
          {step === 3 && <PaymentStep data={data} set={set} onSubmit={submit} onBack={() => setStep(2)} paying={paying} payErr={payErr} quote={quote} />}
        </div>
        <aside>
          <div style={{ position: 'sticky', top: 'calc(var(--header-h) + 16px)', background: 'var(--cream)', padding: 24, borderRadius: 16 }}>
            <h3 className="serif" style={{ fontSize: '1.2rem', marginBottom: 16 }}>Your order ({lines.length})</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12, maxHeight: 320, overflowY: 'auto', marginBottom: 16 }}>
              {lines.map((l) => (
                <div key={l.productId + l.variant} style={{ display: 'flex', gap: 12 }}>
                  <div style={{ width: 56, height: 68, borderRadius: 8, overflow: 'hidden', background: 'var(--paper)', flexShrink: 0, position: 'relative' }}>
                    <img src={l.product.image} alt={l.product.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                    <span style={{ position: 'absolute', top: -6, right: -6, background: 'var(--forest)', color: 'var(--paper)', borderRadius: 999, minWidth: 20, height: 20, fontSize: '.7rem', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', paddingInline: 4 }}>{l.qty}</span>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="serif" style={{ fontSize: '.95rem', lineHeight: 1.2 }}>{l.product.name}</div>
                    <div style={{ fontSize: '.72rem', color: 'var(--muted)', marginTop: 2 }}>{l.variant}</div>
                  </div>
                  <div style={{ fontSize: '.88rem' }}>{HAP.formatPrice(l.line)}</div>
                </div>
              ))}
            </div>
            <Row k="Subtotal" v={HAP.formatPrice(subtotal)} />
            <Row k="Shipping" v={shipping === 0 ? <span style={{ color: 'var(--success)' }}>Free</span> : HAP.formatPrice(shipping)} />
            {quote.codFee > 0 && <Row k="COD fee" v={HAP.formatPrice(quote.codFee)} />}
            {quote.gst && <Row k="GST (incl.)" v={HAP.formatPrice(Math.round((quote.gst.cgst || 0) + (quote.gst.sgst || 0) + (quote.gst.igst || 0)))} small />}
            <div style={{ height: 1, background: 'var(--line-strong)', margin: '12px 0' }}></div>
            <div className="spread" style={{ fontFamily: 'var(--serif)', fontSize: '1.3rem' }}>
              <span>Total</span><span>{HAP.formatPrice(total)}</span>
            </div>
            <p style={{ fontSize: '.72rem', color: 'var(--muted)', marginTop: 8 }}>Totals from CustomerCommerce + APG settings — not client-trusted cart prices.</p>
          </div>
        </aside>
      </div>

      <style>{`
        @media (max-width: 980px) {
          .checkout-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </main>
  );
}

function Stepper({ step, setStep }) {
  const steps = [
    { n: 1, t: 'Contact' },
    { n: 2, t: 'Shipping' },
    { n: 3, t: 'Payment' },
    { n: 4, t: 'Confirm' }
  ];
  return (
    <div style={{ display: 'flex', gap: 8, alignItems: 'center', borderBottom: '1px solid var(--line)', paddingBottom: 18 }}>
      {steps.map((s, i) => (
        <React.Fragment key={s.n}>
          <button onClick={() => s.n < step && setStep(s.n)}
            disabled={s.n > step}
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 8, fontSize: '.88rem',
              color: s.n === step ? 'var(--forest)' : s.n < step ? 'var(--ink)' : 'var(--muted)',
              fontWeight: s.n === step ? 600 : 400, cursor: s.n < step ? 'pointer' : 'default'
            }}>
            <span style={{
              width: 24, height: 24, borderRadius: 999, fontSize: '.78rem',
              background: s.n <= step ? 'var(--forest)' : 'var(--cream)',
              color: s.n <= step ? 'var(--paper)' : 'var(--muted)',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontWeight: 600
            }}>{s.n < step ? <Icon name="check" size={12} /> : s.n}</span>
            {s.t}
          </button>
          {i < steps.length - 1 && <span style={{ flex: 'none', width: 24, height: 1, background: 'var(--line-strong)' }}></span>}
        </React.Fragment>
      ))}
    </div>
  );
}

function ContactStep({ data, set, onNext }) {
  const ok = data.email.includes('@');
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div className="spread">
        <h2 className="serif" style={{ fontSize: '1.6rem' }}>Contact</h2>
        <a href="#/account/login" style={{ fontSize: '.85rem', color: 'var(--forest)', textDecoration: 'underline', textUnderlineOffset: 3 }}>Have an account? Sign in</a>
      </div>
      <div className="field">
        <label>Email</label>
        <input className="input input--lg" type="email" value={data.email} onChange={(e) => set({ email: e.target.value })} placeholder="you@home.com" />
      </div>
      <label className="check">
        <input type="checkbox" checked={data.saveInfo} onChange={(e) => set({ saveInfo: e.target.checked })} />
        <span className="check__box"><Icon name="check" size={12} /></span>
        <span>Email me about new arrivals & offers</span>
      </label>
      <div className="spread">
        <span></span>
        <button className="btn btn--primary btn--lg" onClick={onNext} disabled={!ok} style={{ opacity: ok ? 1 : 0.5 }}>
          Continue to shipping <Icon name="arrow-right" size={16} />
        </button>
      </div>
    </div>
  );
}

function ShippingStep({ data, set, onNext, onBack, shipCfg }) {
  const ok = data.firstName && data.lastName && data.address && data.city && /^\d{6}$/.test(data.pincode) && data.phone;
  const cfg = shipCfg || window.CustomerCommerce.shippingSettings();
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <h2 className="serif" style={{ fontSize: '1.6rem' }}>Shipping address</h2>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <Field label="First name" value={data.firstName} onChange={(v) => set({ firstName: v })} />
        <Field label="Last name" value={data.lastName} onChange={(v) => set({ lastName: v })} />
      </div>
      <Field label="Address line 1" value={data.address} onChange={(v) => set({ address: v })} />
      <Field label="Address line 2 (optional)" value={data.address2} onChange={(v) => set({ address2: v })} />
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr', gap: 14 }}>
        <Field label="City" value={data.city} onChange={(v) => set({ city: v })} />
        <Field label="State" value={data.state} onChange={(v) => set({ state: v })} />
        <Field label="Pincode" value={data.pincode} onChange={(v) => set({ pincode: v.replace(/\D/g, '').slice(0, 6) })} />
      </div>
      <Field label="Phone (for delivery updates)" value={data.phone} onChange={(v) => set({ phone: v.replace(/\D/g, '').slice(0, 10) })} />
      <Field label="Order notes (optional)" type="textarea" value={data.notes} onChange={(v) => set({ notes: v })} />

      <div>
        <h3 style={{ fontSize: '.92rem', marginBottom: 10, marginTop: 8 }}>Shipping method</h3>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <RadioBox checked={data.shipMethod === 'standard'} onClick={() => set({ shipMethod: 'standard' })}
            t="Standard delivery" s={'Free above ' + HAP.formatPrice(cfg.freeAbove)} right={HAP.formatPrice(cfg.flat)} />
          <RadioBox checked={data.shipMethod === 'express'} onClick={() => set({ shipMethod: 'express' })}
            t="Express tracked" s="From store settings" right={HAP.formatPrice(cfg.express)} />
          <RadioBox checked={data.shipMethod === 'local'} onClick={() => set({ shipMethod: 'local' })}
            t="Kerala local delivery" s="Select only if you are in the local delivery area" right="FREE" />
        </div>
      </div>

      <div className="spread">
        <button className="btn btn--ghost" onClick={onBack}><Icon name="chev-left" size={14} /> Back</button>
        <button className="btn btn--primary btn--lg" onClick={onNext} disabled={!ok} style={{ opacity: ok ? 1 : 0.5 }}>
          Continue to payment <Icon name="arrow-right" size={16} />
        </button>
      </div>
    </div>
  );
}

function PaymentStep({ data, set, onSubmit, onBack, paying, payErr, quote }) {
  const remote = !!(window.APG_CONFIG && window.APG_CONFIG.useRemote);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <h2 className="serif" style={{ fontSize: '1.6rem' }}>Payment</h2>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        <RadioBox checked={data.payMethod === 'card' || data.payMethod === 'upi'} onClick={() => set({ payMethod: 'card' })}
          t="Pay online" s={remote ? 'UPI · Cards · Netbanking via Razorpay' : 'Recorded as online intent (gateway active when remote mode is on)'} right={<small style={{ color: 'var(--muted)' }}>{remote ? 'Razorpay' : 'local'}</small>} />
        {remote && data.payMethod !== 'cod' && (
          <p style={{ fontSize: '.82rem', color: 'var(--ink-2)', padding: '0 4px' }}>You will complete payment securely in the Razorpay window. Card details are never stored here.</p>
        )}
        <RadioBox checked={data.payMethod === 'cod'} onClick={() => set({ payMethod: 'cod' })}
          t="Cash on delivery" s={'Pay when your order arrives' + ((quote && quote.codFee) ? (' · fee ' + HAP.formatPrice(quote.codFee)) : ' · fee ₹49')} right="COD" />
      </div>

      {payErr && <div role="alert" style={{ color: 'var(--danger)', fontSize: '.85rem' }}>{payErr}</div>}

      <div style={{ display: 'flex', gap: 12, padding: 14, background: 'var(--cream)', borderRadius: 12, fontSize: '.85rem', color: 'var(--ink-2)' }}>
        <Icon name="shield" size={18} style={{ color: 'var(--forest)', flexShrink: 0 }} />
        We never store raw card CVV. Payment confirmation comes from the trusted payment path when remote mode is enabled.
      </div>

      <div className="spread">
        <button className="btn btn--ghost" onClick={onBack} disabled={paying}><Icon name="chev-left" size={14} /> Back</button>
        <button className="btn btn--primary btn--lg checkout-desktop-btn" onClick={onSubmit} disabled={paying} style={{ opacity: paying ? 0.5 : 1 }}>
          {paying ? 'Processing…' : 'Place order'} <Icon name="check" size={16} />
        </button>
      </div>
      <div className="checkout-place-order">
        <button className="btn btn--primary btn--lg" onClick={onSubmit} disabled={paying}>
          {paying ? 'Processing…' : 'PLACE ORDER'}
        </button>
      </div>
    </div>
  );
}

function RadioBox({ checked, onClick, t, s, right }) {
  return (
    <button type="button" role="radio" aria-checked={!!checked} onClick={onClick} style={{
      display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 14, alignItems: 'center',
      padding: '14px 16px', border: '1px solid ' + (checked ? 'var(--forest)' : 'var(--line-strong)'),
      borderRadius: 12, textAlign: 'left', cursor: 'pointer',
      background: checked ? 'var(--cream)' : 'var(--paper)',
      transition: 'all 160ms'
    }}>
      <span aria-hidden="true" style={{
        width: 18, height: 18, borderRadius: 999,
        border: '2px solid ' + (checked ? 'var(--forest)' : 'var(--line-strong)'),
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center'
      }}>
        {checked && <span style={{ width: 8, height: 8, background: 'var(--forest)', borderRadius: 999 }}></span>}
      </span>
      <div>
        <div style={{ fontWeight: 500 }}>{t}</div>
        <div style={{ fontSize: '.78rem', color: 'var(--muted)' }}>{s}</div>
      </div>
      <div style={{ fontSize: '.85rem', color: 'var(--ink-2)' }}>{right}</div>
    </button>
  );
}

function Field({ label, value, onChange, placeholder, type, id }) {
  const fieldId = id || ('field-' + String(label || 'input').toLowerCase().replace(/\s+/g, '-'));
  return (
    <div className="field">
      <label htmlFor={fieldId}>{label}</label>
      {type === 'textarea'
        ? <textarea id={fieldId} className="textarea" value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} />
        : <input id={fieldId} className="input input--lg" type={type || 'text'} value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} />}
    </div>
  );
}

function OrderConfirmation({ order }) {
  React.useEffect(() => { window.scrollTo({ top: 0 }); }, []);
  const storeUser = window.HAPStore && window.HAPStore.state && window.HAPStore.state.user;
  return (
    <main className="container" style={{ paddingBlock: 64, maxWidth: 740, margin: '0 auto' }}>
      <div style={{ textAlign: 'center', marginBottom: 40 }}>
        <div style={{ width: 64, height: 64, borderRadius: 999, background: 'var(--success)', color: 'var(--paper)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 }}>
          <Icon name="check" size={28} />
        </div>
        <h1 className="serif" style={{ fontSize: 'var(--fs-display)', lineHeight: 1.05 }}>Order placed.<br/>Thank you!</h1>
        <p style={{ color: 'var(--ink-2)', marginTop: 12, maxWidth: 480, marginInline: 'auto' }}>
          We'll pack your order in the morning. A confirmation is on its way to <b>{order.details.email}</b>.
        </p>
      </div>

      <div style={{ background: 'var(--cream)', borderRadius: 16, padding: 28, marginBottom: 24 }}>
        <div className="spread" style={{ paddingBottom: 16, borderBottom: '1px solid var(--line)' }}>
          <div>
            <div className="eyebrow">Order number</div>
            <div className="serif" style={{ fontSize: '1.3rem' }}>{order.id}</div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div className="eyebrow">Placed</div>
            <div style={{ fontSize: '.95rem' }}>{new Date(order.placedAt).toLocaleString('en-IN', { dateStyle: 'medium', timeStyle: 'short' })}</div>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 16 }}>
          {order.lines.map((l) => (
            <div key={l.productId + l.variant} style={{ display: 'flex', gap: 12 }}>
              <div style={{ width: 48, height: 60, borderRadius: 6, overflow: 'hidden', background: 'var(--paper)' }}>
                <img src={l.product.image} alt={l.product.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              </div>
              <div style={{ flex: 1 }}>
                <div className="serif" style={{ fontSize: '.95rem' }}>{l.product.name}</div>
                <div style={{ fontSize: '.74rem', color: 'var(--muted)' }}>{l.variant} · qty {l.qty}</div>
              </div>
              <div style={{ fontSize: '.88rem' }}>{HAP.formatPrice(l.line)}</div>
            </div>
          ))}
        </div>
        <div style={{ height: 1, background: 'var(--line)', margin: '16px 0' }}></div>
        <Row k="Subtotal" v={HAP.formatPrice(order.subtotal)} />
        <Row k="Shipping" v={order.shipping === 0 ? 'Free' : HAP.formatPrice(order.shipping)} />
        {order.codFee > 0 && <Row k="COD fee" v={HAP.formatPrice(order.codFee)} />}
        <div className="spread" style={{ fontFamily: 'var(--serif)', fontSize: '1.2rem', marginTop: 6 }}>
          <span>Total</span><span>{HAP.formatPrice(order.total)}</span>
        </div>
        <div style={{ fontSize: '.82rem', color: 'var(--muted)', marginTop: 8 }}>Status: {order.status} · Payment: {order.paymentStatus || 'recorded'}</div>
      </div>

      <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
        <a className="btn btn--primary" href={'#/track?o=' + encodeURIComponent(order.id)}>Track order</a>
        <a className="btn btn--secondary" href="#/account/orders">View my orders</a>
        <a className="btn btn--ghost" href="#/collections/pebbles">Continue shopping</a>
        <a className="btn btn--ghost" href="#/pages/contact">Contact support</a>
      </div>
      {!storeUser && (
        <div style={{ marginTop: 28, textAlign: 'center', background: 'var(--cream)', borderRadius: 12, padding: 20 }}>
          <p style={{ marginBottom: 10 }}>Create an account to track future orders faster.</p>
          <a className="btn btn--secondary btn--sm" href="#/account/register">Create account</a>
        </div>
      )}
    </main>
  );
}

window.CartPage = CartPage;
window.CheckoutPage = CheckoutPage;
window.OrderConfirmation = OrderConfirmation;
