/* ============================================================
   CART + CHECKOUT + CONFIRMATION — Paystack (NGN) or USD wire
   ============================================================ */
const NG_STATES = ['Lagos', 'FCT (Abuja)', 'Rivers', 'Oyo', 'Kano', 'Kaduna', 'Enugu', 'Anambra', 'Delta', 'Edo', 'Ogun', 'Akwa Ibom', 'Abia', 'Other'];
const COUNTRIES = ['Nigeria', 'United Kingdom', 'United States', 'Ghana', 'United Arab Emirates', 'Canada'];

const usdRate = () => Math.round(1 / BB.BRAND.currency.rate);
const rateLine = () => `${BB.BRAND.currency.primary.symbol}${usdRate().toLocaleString('en-NG')} / ${BB.BRAND.currency.secondary.symbol}1`;
const wireAmount = (ngn) => `${BB.fmt(ngn, 'USD')} (${BB.fmt(ngn, 'NGN')} at ${rateLine()})`;

const deliveryFee = (form) => {
  const D = BB.BRAND.delivery;
  if (form.delivery === 'pickup') return 0;
  if (form.country !== 'Nigeria') return null;      // quoted separately
  return form.state === 'Lagos' ? D.lagos : D.nigeria;
};

function CartPage() {
  const { cartLines, setQty, removeItem, nav, money, subtotal } = 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 cart is empty</h1>
        <button className="btn btn-gold btn-lg" style={{ marginTop: 24 }} onClick={() => nav('shop')}>Browse the stock</button>
      </div>
    );
  }
  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: 12 }}>Your Cart</h1>
      <p className="muted" style={{ marginBottom: 36, maxWidth: 560 }}>Fabric is cut and sourced to order. Delivery is calculated at checkout, and you can pay by Paystack in naira or by dollar wire transfer.</p>
      <div className="cart-layout">
        <div>
          {cartLines.map(l => {
            const c = BB.catOf(l.product);
            return (
            <div key={l.idx} style={{ display: 'flex', gap: 20, padding: '24px 0', borderBottom: '1px solid var(--line)' }}>
              <Ph src={l.product.img} label="" variant={l.product.ph} style={{ width: 110, height: 110, borderRadius: 'var(--r-md)', flexShrink: 0, cursor: 'pointer' }} onClick={() => nav('product', { id: l.product.id })} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', gap: 12 }}>
                  <div>
                    <span className="cat-tag">{c?.short}</span>
                    <h3 onClick={() => nav('product', { id: l.product.id })} style={{ fontSize: 22, cursor: 'pointer', lineHeight: 1.15, marginTop: 3 }}>{l.product.name}</h3>
                    <p style={{ fontSize: 13, color: 'var(--ink-soft)', marginTop: 4 }}>{Object.keys(l.opts || {}).length > 0 ? Object.entries(l.opts).map(([k, v]) => `${k}: ${v}`).join(' · ') : BB.specLine(l.product)}</p>
                  </div>
                  <div style={{ textAlign: 'right', flexShrink: 0 }}>
                    <div style={{ fontFamily: 'var(--serif)', fontWeight: 700, fontSize: 20 }}>{money(l.product.price * l.qty)}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-faint)', marginTop: 2 }}>{money(l.product.price)} / {l.product.unit}</div>
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 16 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <span className="eyebrow" style={{ fontSize: 11 }}>{l.product.unit === 'set' ? 'Sets' : 'Yards'}</span>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, border: '1.5px solid var(--line)', borderRadius: 100, padding: 4, background: 'var(--ivory)' }}>
                      <button className="qbtn" onClick={() => setQty(l.idx, l.qty - 1)} aria-label="Decrease"><I.minus width={15} height={15} /></button>
                      <span style={{ minWidth: 26, textAlign: 'center' }}>{l.qty}</span>
                      <button className="qbtn" onClick={() => setQty(l.idx, l.qty + 1)} aria-label="Increase"><I.plus width={15} height={15} /></button>
                    </div>
                  </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} lines={cartLines} cta="Proceed to checkout" onCta={() => nav('checkout')} />
      </div>
    </div>
  );
}

function OrderSummary({ subtotal, lines, fee, cta, onCta, compact, ctaDisabled }) {
  const { money } = useStore();
  const total = subtotal + (fee || 0);
  return (
    <aside style={{ background: 'var(--ivory)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: 28, boxShadow: 'var(--shadow-sm)', alignSelf: 'start', position: compact ? 'static' : 'sticky', top: 100 }}>
      <h3 style={{ fontSize: 24, marginBottom: 14 }}>Order summary</h3>
      <Row l={`Subtotal · ${lines.length} fabric${lines.length !== 1 ? 's' : ''}`} v={money(subtotal)} />
      <Row l="Delivery" v={fee === undefined ? 'At checkout' : fee === null ? 'Quoted' : fee === 0 ? 'Free — pickup' : money(fee)} note={fee === null ? 'International — we confirm the rate by email' : undefined} />
      <hr className="divider" style={{ margin: '16px 0' }} />
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <span style={{ fontWeight: 600 }}>Total</span>
        <span style={{ fontFamily: 'var(--serif)', fontSize: 28, fontWeight: 700 }}>{money(total)}</span>
      </div>
      <p style={{ fontSize: 12.5, color: 'var(--ink-soft)', lineHeight: 1.55, marginTop: 12 }}>Pay by Paystack in naira, or by dollar wire transfer.</p>
      {cta && <button className="btn btn-gold btn-block btn-lg" style={{ marginTop: 18 }} disabled={ctaDisabled} onClick={onCta}>{cta}</button>}
    </aside>
  );
}
function Row({ l, v, note }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '7px 0', fontSize: 14.5, gap: 14 }}>
      <span className="muted">{l}{note && <em style={{ display: 'block', fontStyle: 'normal', fontSize: 11.5, color: 'var(--sage-deep)' }}>{note}</em>}</span>
      <span style={{ textAlign: 'right' }}>{v}</span>
    </div>
  );
}

/* ---------- Dollar wire transfer modal ---------- */
function WireModal({ open, onClose, amountNgn, orderNum }) {
  const W = BB.BRAND.payment.wire;
  const { toast } = useStore();
  useEffect(() => {
    const esc = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', esc);
    return () => window.removeEventListener('keydown', esc);
  }, [onClose]);
  const copy = () => {
    const text = W.rows.map(([k, v]) => `${k}: ${v === 'Your order number' && orderNum ? orderNum : v}`).join('\n');
    if (navigator.clipboard) navigator.clipboard.writeText(text);
    toast('Account details copied', 'check');
  };
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(33,26,17,.45)', backdropFilter: 'blur(3px)', zIndex: 180, opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none', transition: 'opacity .3s' }} />
      <div role="dialog" aria-modal="true" aria-label="Dollar wire transfer details" style={{ position: 'fixed', top: '50%', left: '50%', width: 'min(560px, calc(100vw - 32px))', maxHeight: 'calc(100vh - 48px)', overflowY: 'auto', transform: open ? 'translate(-50%,-50%) scale(1)' : 'translate(-50%,-48%) scale(.97)', background: 'var(--cream)', borderRadius: 'var(--r-xl)', boxShadow: 'var(--shadow-lg)', zIndex: 181, opacity: open ? 1 : 0, pointerEvents: open ? 'auto' : 'none', transition: 'all .35s cubic-bezier(.2,.8,.2,1)' }}>
        <header style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, padding: '26px 28px 18px', borderBottom: '1px solid var(--line)' }}>
          <div>
            <span className="eyebrow" style={{ color: 'var(--gold-deep)' }}>Dollar wire transfer</span>
            <h3 style={{ fontSize: 26, marginTop: 6, lineHeight: 1.1 }}>Transfer details</h3>
          </div>
          <button className="icobtn" onClick={onClose} aria-label="Close" style={{ marginRight: -8 }}><I.close width={22} height={22} /></button>
        </header>
        <div style={{ padding: '22px 28px 26px' }}>
          <div style={{ background: 'var(--gold-soft)', border: '1px solid var(--gold)', borderRadius: 'var(--r-md)', padding: '16px 18px', marginBottom: 20 }}>
            <span className="eyebrow" style={{ fontSize: 10.5 }}>Amount to send</span>
            <div style={{ fontFamily: 'var(--serif)', fontSize: 34, fontWeight: 700, lineHeight: 1.1, marginTop: 4 }}>{BB.fmt(amountNgn, 'USD')}</div>
            <p style={{ fontSize: 13, color: 'var(--ink)', marginTop: 4 }}>{BB.fmt(amountNgn, 'NGN')} converted at {rateLine()}</p>
            <p style={{ fontSize: 12.5, color: 'var(--ink-soft)', marginTop: 6 }}>Send the exact dollar amount. Your bank's fees are not deducted from the order total.</p>
          </div>
          <dl className="spec-sheet">
            {W.rows.map(([k, v]) => (
              <div className="spec-row" key={k}><dt>{k}</dt><dd style={{ fontVariantNumeric: 'tabular-nums' }}>{v === 'Your order number' && orderNum ? orderNum : v}</dd></div>
            ))}
          </dl>
          <p style={{ fontSize: 13, color: 'var(--ink-soft)', lineHeight: 1.65, marginTop: 18 }}>{W.note}</p>
          <div style={{ display: 'flex', gap: 10, marginTop: 22, flexWrap: 'wrap' }}>
            <button className="btn btn-primary" style={{ flex: '1 1 180px' }} onClick={copy}><I.doc width={16} height={16} /> Copy details</button>
            <button className="btn btn-outline" style={{ flex: '1 1 120px' }} onClick={onClose}>Done</button>
          </div>
        </div>
      </div>
    </>
  );
}

/* ---------- Checkout (contact → delivery → payment) ---------- */
function CheckoutPage() {
  const { cartLines, nav, placeOrder, subtotal, money, toast } = useStore();
  const [step, setStep] = useState(1);
  const [wireOpen, setWireOpen] = useState(false);
  const [paying, setPaying] = useState(false);
  const [form, setForm] = useState({ email: '', firstName: '', lastName: '', address: '', city: '', state: 'Lagos', country: 'Nigeria', phone: '', delivery: 'pickup', payment: 'paystack', notes: '', marketing: true });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

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

  const fee = deliveryFee(form);
  const total = subtotal + (fee || 0);
  const steps = ['Contact', 'Delivery', 'Payment'];
  const next = () => setStep(s => Math.min(3, s + 1));
  const submit = () => {
    setPaying(true);
    setTimeout(() => {
      const order = placeOrder({
        email: form.email, name: `${form.firstName} ${form.lastName}`.trim(), phone: form.phone,
        address: form.delivery === 'pickup' ? 'Pickup — Victoria Island, Lagos' : `${form.address}, ${form.city}${form.country === 'Nigeria' && form.state ? ', ' + form.state : ''}, ${form.country}`,
        city: form.city, region: form.country, delivery: form.delivery, notes: form.notes,
        payment: form.payment, fee: fee || 0, total,
      });
      nav('confirm', { num: order.num });
    }, 900);
  };
  const canContinue1 = form.email.includes('@') && form.firstName && form.lastName;
  const canContinue2 = form.delivery === 'pickup' || (form.address && form.city);

  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> Return to cart</button>
      <h1 style={{ fontSize: 'clamp(34px,5vw,56px)', marginBottom: 8 }}>Checkout</h1>

      <div style={{ display: 'flex', gap: 8, alignItems: 'center', margin: '20px 0 36px', flexWrap: 'wrap' }}>
        {steps.map((s, i) => (
          <React.Fragment key={s}>
            <button onClick={() => step > i + 1 && setStep(i + 1)} style={{ display: 'flex', alignItems: 'center', gap: 9, fontSize: 13.5, fontWeight: 500, minHeight: 44, padding: '4px 2px', color: step >= i + 1 ? 'var(--ink)' : 'var(--ink-faint)', cursor: step > i + 1 ? 'pointer' : 'default' }}>
              <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}
            </button>
            {i < 2 && <span style={{ flex: '0 1 40px', height: 1, background: 'var(--line)' }} />}
          </React.Fragment>
        ))}
      </div>

      <div className="cart-layout">
        <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="Ada" /></div>
                <div className="field"><label>Last name</label><input className="input" value={form.lastName} onChange={e => set('lastName', e.target.value)} placeholder="Okafor" /></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="+234 …" /></div>
              <button className="btn btn-primary btn-lg" style={{ marginTop: 26 }} disabled={!canContinue1} onClick={next}>Continue to delivery</button>
            </Section>
          )}

          {step === 2 && (
            <Section title="Delivery">
              {[
                ['pickup', 'Pickup', 'Victoria Island, Lagos · by appointment · free'],
                ['delivery', 'Delivery', 'Nationwide courier · calculated below'],
              ].map(([id, n, sub]) => (
                <label key={id} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '15px 18px', border: '1.5px solid ' + (form.delivery === id ? 'var(--gold)' : 'var(--line)'), background: form.delivery === id ? 'var(--gold-soft)' : 'var(--ivory)', borderRadius: 'var(--r-md)', marginBottom: 10, cursor: 'pointer', transition: 'all .25s' }}>
                  <span style={{ width: 18, height: 18, borderRadius: 100, border: '1.5px solid ' + (form.delivery === id ? 'var(--gold-deep)' : 'var(--ink-faint)'), display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                    {form.delivery === id && <span style={{ width: 9, height: 9, borderRadius: 100, background: 'var(--gold-deep)' }} />}
                  </span>
                  <input type="radio" name="delivery" checked={form.delivery === id} onChange={() => set('delivery', id)} style={{ position: 'absolute', opacity: 0, width: 0, height: 0 }} />
                  <span style={{ flex: 1 }}><strong style={{ fontWeight: 600 }}>{n}</strong><br /><span style={{ fontSize: 13, color: 'var(--ink-soft)' }}>{sub}</span></span>
                </label>
              ))}
              {form.delivery === 'delivery' && (
                <>
                  <div className="field" style={{ marginTop: 16 }}><label>Address</label><input className="input" value={form.address} onChange={e => set('address', e.target.value)} placeholder="House number & street" /></div>
                  <div className="form-row" style={{ marginTop: 16 }}>
                    <div className="field"><label>City</label><input className="input" value={form.city} onChange={e => set('city', e.target.value)} placeholder="Ikeja" /></div>
                    <div className="field"><label>Country / Region</label>
                      <select className="input" value={form.country} onChange={e => set('country', e.target.value)} style={{ cursor: 'pointer' }}>
                        {COUNTRIES.map(c => <option key={c}>{c}</option>)}
                      </select>
                    </div>
                  </div>
                  {form.country === 'Nigeria' && (
                    <div className="field" style={{ marginTop: 16 }}><label>State</label>
                      <select className="input" value={form.state} onChange={e => set('state', e.target.value)} style={{ cursor: 'pointer' }}>
                        {NG_STATES.map(s => <option key={s}>{s}</option>)}
                      </select>
                    </div>
                  )}
                  <p className="muted" style={{ fontSize: 12.5, marginTop: 14 }}>Dispatched with {BB.BRAND.logistics.provider} partners — {BB.BRAND.logistics.partners.slice(0, 3).join(', ')} and others.</p>
                </>
              )}
              <button className="btn btn-primary btn-lg" style={{ marginTop: 20 }} disabled={!canContinue2} onClick={next}>Continue to payment</button>
            </Section>
          )}

          {step === 3 && (
            <Section title="Payment">
              {BB.BRAND.payment.methods.map(m => (
                <div key={m.id}>
                  <label style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '16px 18px', border: '1.5px solid ' + (form.payment === m.id ? 'var(--gold)' : 'var(--line)'), background: form.payment === m.id ? 'var(--gold-soft)' : 'var(--ivory)', borderRadius: 'var(--r-md)', marginBottom: 10, cursor: 'pointer', transition: 'all .25s' }}>
                    <span style={{ width: 18, height: 18, borderRadius: 100, border: '1.5px solid ' + (form.payment === m.id ? 'var(--gold-deep)' : 'var(--ink-faint)'), display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                      {form.payment === m.id && <span style={{ width: 9, height: 9, borderRadius: 100, background: 'var(--gold-deep)' }} />}
                    </span>
                    <input type="radio" name="payment" checked={form.payment === m.id} onChange={() => { set('payment', m.id); if (m.id === 'wire') setWireOpen(true); }} style={{ position: 'absolute', opacity: 0, width: 0, height: 0 }} />
                    <span style={{ flex: 1 }}><strong style={{ fontWeight: 600 }}>{m.name}</strong><br /><span style={{ fontSize: 13, color: 'var(--ink-soft)' }}>{m.sub}</span></span>
                    <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.1em', color: 'var(--ink-soft)' }}>{m.cur}</span>
                  </label>
                  {form.payment === 'wire' && m.id === 'wire' && (
                    <div style={{ background: 'var(--ivory)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', padding: '16px 18px', marginBottom: 10 }}>
                      <p style={{ fontSize: 13.5, color: 'var(--ink-soft)', lineHeight: 1.6 }}>You'll send <strong style={{ color: 'var(--ink)' }}>{wireAmount(total)}</strong> to our USD domiciliary account and quote your order number as the reference.</p>
                      <button className="btn btn-outline btn-sm" style={{ marginTop: 12 }} onClick={() => setWireOpen(true)}>View account details</button>
                    </div>
                  )}
                </div>
              ))}

              <div className="field" style={{ margin: '20px 0' }}><label>Order notes (optional)</label><textarea className="input" rows="3" value={form.notes} onChange={e => set('notes', e.target.value)} placeholder="Occasion date, colourway preferences…" /></div>
              <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', fontSize: 13.5, cursor: 'pointer', color: 'var(--ink-soft)' }}>
                <input type="checkbox" checked={form.marketing} onChange={e => set('marketing', e.target.checked)} style={{ width: 17, height: 17, accentColor: 'var(--gold-deep)', marginTop: 1 }} />
                Keep me posted on new fabric arrivals
              </label>
              <button className="btn btn-gold btn-block btn-lg" style={{ marginTop: 20 }} disabled={paying} onClick={submit}>
                {paying ? 'Processing…' : form.payment === 'paystack' ? `Pay ${money(total)} with Paystack` : `Place order · ${BB.fmt(total, 'USD')} by wire`}
              </button>
              <p style={{ textAlign: 'center', fontSize: 12, color: 'var(--ink-faint)', marginTop: 14 }}>
                {form.payment === 'paystack' ? 'Secured by Paystack — card, bank transfer or USSD.' : `${BB.fmt(total, 'NGN')} converted at ${rateLine()} — reserved as soon as we confirm the transfer.`}
              </p>
            </Section>
          )}
        </div>

        <div>
          <OrderSummary subtotal={subtotal} lines={cartLines} fee={step === 1 ? undefined : fee} />
          <aside style={{ background: 'var(--ivory)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: 26, boxShadow: 'var(--shadow-sm)', marginTop: 16 }}>
            <h3 style={{ fontSize: 20, marginBottom: 16 }}>In your order</h3>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14, maxHeight: 320, 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: 54, height: 54, 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 }}>
                    <span className="cat-tag" style={{ fontSize: 9.5 }}>{BB.catOf(l.product)?.short}</span>
                    <div style={{ fontSize: 14, fontWeight: 500, lineHeight: 1.2 }}>{l.product.name}</div>
                  </div>
                  <span style={{ fontSize: 13.5, fontWeight: 600, flexShrink: 0 }}>{money(l.product.price * l.qty)}</span>
                </div>
              ))}
            </div>
          </aside>
        </div>
      </div>

      <WireModal open={wireOpen} onClose={() => setWireOpen(false)} amountNgn={total} />
    </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 [wireOpen, setWireOpen] = useState(false);
  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')}>Browse the stock</button></div>; }
  const wire = order.payment === 'wire';
  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>
      <h1 style={{ fontSize: 'clamp(36px,5vw,58px)', margin: '14px 0 12px' }}>{wire ? <>Order placed — <em style={{ color: 'var(--gold-deep)' }}>awaiting your transfer</em></> : <>Payment received — <em style={{ color: 'var(--gold-deep)' }}>thank you</em></>}</h1>
      <p className="muted" style={{ fontSize: 16.5 }}>Order <strong style={{ color: 'var(--ink)' }}>#{order.num}</strong>. {wire ? 'Send the transfer quoting this number as your reference and we\u2019ll confirm by email.' : 'A receipt is on its way to your inbox.'}</p>
      {wire && <button className="btn btn-gold btn-lg" style={{ marginTop: 22 }} onClick={() => setWireOpen(true)}>View transfer details</button>}
      <div style={{ background: 'var(--ivory)', border: '1px solid var(--line)', 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', gap: 12, padding: '8px 0', fontSize: 14.5 }}>
            <span>{l.qty} × {l.name}</span>
            <span style={{ flexShrink: 0 }}>{money((l.price || 0) * l.qty)}</span>
          </div>
        ))}
        <hr className="divider" style={{ margin: '14px 0' }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14.5, padding: '4px 0' }}><span className="muted">Delivery</span><span>{order.fee ? money(order.fee) : order.delivery === 'pickup' ? 'Free — pickup' : 'Quoted'}</span></div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 8 }}>
          <span style={{ fontWeight: 600 }}>Total {wire ? 'due' : 'paid'}</span>
          <span style={{ textAlign: 'right' }}>
            <span style={{ fontFamily: 'var(--serif)', fontSize: 26, fontWeight: 700, display: 'block' }}>{wire ? BB.fmt(order.total, 'USD') : money(order.total)}</span>
            {wire && <span style={{ fontSize: 12.5, color: 'var(--ink-soft)' }}>{BB.fmt(order.total, 'NGN')} at {rateLine()}</span>}
          </span>
        </div>
        <p className="muted" style={{ fontSize: 13, marginTop: 14, lineHeight: 1.5 }}>{order.delivery === 'pickup' ? 'Pickup at our Victoria Island atelier.' : 'Delivering to: ' + order.address}</p>
        {order.notes && <p className="muted" style={{ fontSize: 13, marginTop: 8, lineHeight: 1.5 }}>Notes: {order.notes}</p>}
      </div>
      <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 30, flexWrap: 'wrap' }}>
        <button className="btn btn-primary btn-lg" onClick={() => nav('account')}>Track this order</button>
        <button className="btn btn-outline btn-lg" onClick={() => nav('shop')}>Continue shopping</button>
      </div>
      <WireModal open={wireOpen} onClose={() => setWireOpen(false)} amountNgn={order.total} orderNum={order.num} />
    </div>
  );
}

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