/* ============================================================
   BAG + CHECKOUT (payment) + ORDER CONFIRMATION
   ============================================================ */
const COUNTRIES = ['Nigeria', 'United Kingdom', 'United States', 'Ghana', 'United Arab Emirates', 'Canada'];

function CartPage() {
  const { cartLines, removeFromCart, setQty, nav, subtotal, fmt } = 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>
        <button className="btn btn-accent btn-lg" style={{ marginTop: 24 }} onClick={() => nav('shop')}>Shop fabrics</button>
      </div>
    );
  }
  const S = BB.BRAND.shipping;
  const toFree = S.free - subtotal;
  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: 36 }}>Your Bag</h1>
      <div className="cart-layout">
        <div>
          {cartLines.map(l => {
            const c = BB.catOf(l.product);
            return (
            <div key={l.id} style={{ display: 'flex', gap: 20, padding: '24px 0', borderBottom: '1px solid var(--line)' }}>
              <Ph src={l.product.img} label="" 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 }}>
                <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 }}>{fmt(l.product.price)} per {l.product.unit}</p>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 14, marginTop: 14, flexWrap: 'wrap' }}>
                  <QtyStepper value={l.qty} max={l.product.stock} unit={l.product.unit} onChange={q => setQty(l.id, q)} />
                  <strong style={{ fontFamily: 'var(--serif)', fontSize: 21, fontVariantNumeric: 'tabular-nums' }}>{fmt(l.total)}</strong>
                </div>
                <button onClick={() => removeFromCart(l.id)} className="link-u" style={{ fontSize: 13, color: 'var(--ink-soft)', marginTop: 12 }}>Remove</button>
              </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>
        <aside style={{ background: 'var(--ivory)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: 28, boxShadow: 'var(--shadow-sm)', alignSelf: 'start', position: 'sticky', top: 100 }}>
          <h3 style={{ fontSize: 24, marginBottom: 18 }}>Order summary</h3>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14.5, marginBottom: 10 }}>
            <span style={{ color: 'var(--ink-soft)' }}>Subtotal</span><strong style={{ fontVariantNumeric: 'tabular-nums' }}>{fmt(subtotal)}</strong>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14.5 }}>
            <span style={{ color: 'var(--ink-soft)' }}>Delivery</span><span style={{ color: 'var(--ink-soft)' }}>At checkout</span>
          </div>
          <hr className="divider" style={{ margin: '18px 0' }} />
          {toFree > 0
            ? <p style={{ fontSize: 13, color: 'var(--accent-deep)', marginBottom: 18 }}>Spend {fmt(toFree)} more for free delivery in Nigeria.</p>
            : <p style={{ fontSize: 13, color: 'var(--sage)', fontWeight: 600, marginBottom: 18 }}>Free delivery within Nigeria unlocked.</p>}
          <button className="btn btn-accent btn-block btn-lg" onClick={() => nav('checkout')}>Checkout</button>
          <p style={{ fontSize: 12, color: 'var(--ink-faint)', marginTop: 14, textAlign: 'center' }}>Paystack or dollar wire transfer</p>
        </aside>
      </div>
    </div>
  );
}

/* ---------- Checkout ---------- */
function CheckoutPage() {
  const { cartLines, nav, placeOrder, subtotal, shipFor, fmt } = useStore();
  const [form, setForm] = useState({
    email: '', firstName: '', lastName: '', phone: '', address: '', city: '', country: 'Nigeria',
    method: 'delivery', zone: 'lagos', payment: 'paystack',
    message: '', marketing: true,
  });
  const [wireModal, setWireModal] = useState(false);
  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 bag is empty</h1>
        <button className="btn btn-accent btn-lg" style={{ marginTop: 24 }} onClick={() => nav('shop')}>Shop fabrics</button>
      </div>
    );
  }

  const ship = form.method === 'pickup' ? { zone: null, fee: 0 } : shipFor(form.zone);
  const total = subtotal + ship.fee;

  const contactOk = form.email.includes('@') && form.firstName && form.lastName && form.phone;
  const addressOk = form.method === 'pickup' || (form.address && form.city);
  const canPay = contactOk && addressOk;

  const pay = () => {
    const record = placeOrder({
      email: form.email, name: `${form.firstName} ${form.lastName}`.trim(), phone: form.phone,
      address: form.address, city: form.city, country: form.country,
      method: form.method, zoneLabel: ship.zone ? ship.zone.label : 'Pickup',
      eta: ship.zone ? ship.zone.eta : 'Ready in 24 hours',
      shipping: ship.fee, total, payment: form.payment,
      message: form.message,
    });
    nav('confirm', { num: record.num });
  };

  const radio = (checked) => (
    <span style={{ width: 18, height: 18, borderRadius: 100, border: '1.5px solid ' + (checked ? 'var(--accent-deep)' : 'var(--ink-faint)'), display: 'grid', placeItems: 'center', flexShrink: 0 }}>
      {checked && <span style={{ width: 9, height: 9, borderRadius: 100, background: 'var(--accent-deep)' }} />}
    </span>
  );
  const optionRow = (checked, onSelect, title, sub, right) => (
    <label onClick={onSelect} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '15px 18px', border: '1.5px solid ' + (checked ? 'var(--accent)' : 'var(--line)'), background: checked ? 'var(--accent-soft)' : 'var(--ivory)', borderRadius: 'var(--r-md)', marginBottom: 10, cursor: 'pointer', transition: 'all .25s' }}>
      {radio(checked)}
      <span style={{ flex: 1 }}><strong style={{ fontWeight: 600 }}>{title}</strong>{sub && <><br /><span style={{ fontSize: 13, color: 'var(--ink-soft)' }}>{sub}</span></>}</span>
      {right && <strong style={{ fontSize: 14, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>{right}</strong>}
    </label>
  );

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

      <div className="cart-layout">
        <div>
          <p className="eyebrow" style={{ marginBottom: 12 }}>Contact</p>
          <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>

          <p className="eyebrow" style={{ marginTop: 30, marginBottom: 12 }}>Delivery</p>
          {optionRow(form.method === 'delivery', () => set('method', 'delivery'), 'Deliver to me', 'Coordinated via ' + BB.BRAND.logistics.provider)}
          {optionRow(form.method === 'pickup', () => set('method', 'pickup'), 'Pickup in Lagos', 'Lekki 1 or Town Planning Way — ready in 24 hours', 'Free')}

          {form.method === 'delivery' && (
            <div style={{ marginTop: 6 }}>
              <div className="field" style={{ marginBottom: 16 }}><label>Street address</label><input className="input" value={form.address} onChange={e => set('address', e.target.value)} placeholder="12 Admiralty Way" /></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="Lagos" /></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>
              <p className="eyebrow" style={{ marginTop: 24, marginBottom: 10 }}>Delivery zone</p>
              {BB.BRAND.shipping.zones.map(z => {
                const fee = subtotal >= BB.BRAND.shipping.free && z.id !== 'intl' ? 0 : z.fee;
                return optionRow(form.zone === z.id, () => set('zone', z.id), z.label, z.eta, fee === 0 ? 'Free' : fmt(fee));
              })}
            </div>
          )}

          <p className="eyebrow" style={{ marginTop: 30, marginBottom: 12 }}>Payment</p>
          {optionRow(form.payment === 'paystack', () => set('payment', 'paystack'), 'Paystack', 'Card, bank transfer or USSD in naira — secured by Paystack')}
          {optionRow(form.payment === 'wire', () => { set('payment', 'wire'); setWireModal(true); }, 'Dollar wire transfer', 'For international customers paying in USD — view account details')}
          {form.payment === 'wire' && (
            <button onClick={() => setWireModal(true)} className="link-u" style={{ fontSize: 13.5, marginBottom: 6, display: 'inline-flex', gap: 7, alignItems: 'center' }}>
              <I.doc width={15} height={15} /> View wire transfer details again
            </button>
          )}

          <div className="field" style={{ marginTop: 22 }}><label>Order notes (optional)</label><textarea className="input" rows="3" value={form.message} onChange={e => set('message', e.target.value)} placeholder="Colour preference, event date…"></textarea></div>

          <label style={{ display: 'flex', gap: 10, alignItems: 'flex-start', marginTop: 18, 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(--accent-deep)', marginTop: 1 }} />
            Keep me posted on new fabric arrivals by email
          </label>

          <button className="btn btn-accent btn-block btn-lg" style={{ marginTop: 22 }} disabled={!canPay} onClick={pay}>
            {form.payment === 'paystack' ? `Pay ${fmt(total)} with Paystack` : `Confirm order · ${fmt(total)}`}
          </button>
          <p style={{ fontSize: 12, color: 'var(--ink-faint)', marginTop: 12, textAlign: 'center', display: 'flex', gap: 7, justifyContent: 'center', alignItems: 'center' }}>
            <I.shield width={14} height={14} /> {form.payment === 'paystack' ? 'You’ll complete payment on Paystack’s secure page' : 'Your order is held for 48 hours while your transfer clears'}
          </p>
        </div>

        <aside style={{ background: 'var(--ivory)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: 26, boxShadow: 'var(--shadow-sm)', alignSelf: 'start', position: 'sticky', top: 100 }}>
          <h3 style={{ fontSize: 22, marginBottom: 18 }}>Order summary</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14, maxHeight: 280, overflowY: 'auto' }}>
            {cartLines.map(l => (
              <div key={l.id} style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                <Ph src={l.product.img} label="" style={{ width: 54, height: 54, borderRadius: 'var(--r-sm)' }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, lineHeight: 1.2 }}>{l.product.name}</div>
                  <div style={{ fontSize: 12.5, color: 'var(--ink-soft)' }}>{l.qty} {l.product.unit}{l.qty !== 1 ? 's' : ''}</div>
                </div>
                <strong style={{ fontSize: 14, fontVariantNumeric: 'tabular-nums' }}>{fmt(l.total)}</strong>
              </div>
            ))}
          </div>
          <hr className="divider" style={{ margin: '18px 0' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14.5, marginBottom: 9 }}>
            <span style={{ color: 'var(--ink-soft)' }}>Subtotal</span><span style={{ fontVariantNumeric: 'tabular-nums' }}>{fmt(subtotal)}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14.5 }}>
            <span style={{ color: 'var(--ink-soft)' }}>{form.method === 'pickup' ? 'Pickup' : 'Delivery'}</span>
            <span style={{ fontVariantNumeric: 'tabular-nums' }}>{ship.fee === 0 ? 'Free' : fmt(ship.fee)}</span>
          </div>
          <hr className="divider" style={{ margin: '16px 0' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <strong style={{ fontSize: 15 }}>Total</strong>
            <strong style={{ fontFamily: 'var(--serif)', fontSize: 27, fontVariantNumeric: 'tabular-nums' }}>{fmt(total)}</strong>
          </div>
        </aside>
      </div>
      {wireModal && <WireModal total={total} onClose={() => setWireModal(false)} />}
    </div>
  );
}

/* ---------- Dollar wire transfer details modal ----------
   PLACEHOLDER banking details — replace with Glitz Allure's real USD account. */
function WireModal({ total, onClose }) {
  const { toast } = useStore();
  const W = BB.BRAND.wire;
  const usd = BB.money(total, BB.BRAND.currency.secondary.code);
  const copy = (label, val) => {
    if (navigator.clipboard) navigator.clipboard.writeText(val).catch(() => {});
    toast(`${label} copied`, 'check');
  };
  useEffect(() => {
    const esc = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', esc);
    return () => window.removeEventListener('keydown', esc);
  }, [onClose]);

  const row = (label, val) => (
    <div key={label} style={{ display: 'flex', alignItems: 'center', gap: 12, justifyContent: 'space-between', padding: '13px 0', borderBottom: '1px solid var(--line)' }}>
      <span style={{ fontSize: 11.5, letterSpacing: '.12em', textTransform: 'uppercase', color: 'var(--ink-soft)', flexShrink: 0 }}>{label}</span>
      <span style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
        <strong style={{ fontSize: 14.5, textAlign: 'right', wordBreak: 'break-word', fontVariantNumeric: 'tabular-nums' }}>{val}</strong>
        <button onClick={() => copy(label, val)} aria-label={`Copy ${label}`} className="icobtn" style={{ flexShrink: 0, width: 30, height: 30, color: 'var(--ink-soft)' }}><I.doc width={15} height={15} /></button>
      </span>
    </div>
  );

  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 300, background: 'rgba(33,26,17,.5)', backdropFilter: 'blur(4px)', display: 'grid', placeItems: 'center', padding: 'var(--gutter)', overflowY: 'auto' }}>
      <div onClick={e => e.stopPropagation()} style={{ background: 'var(--cream)', borderRadius: 'var(--r-lg)', boxShadow: 'var(--shadow-lg)', width: 'min(560px, 100%)', margin: 'auto', animation: 'scaleIn .35s cubic-bezier(.2,.8,.2,1)' }}>
        <header style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 14, padding: 'clamp(22px,4vw,30px) clamp(22px,4vw,32px) 18px', borderBottom: '1px solid var(--line)' }}>
          <div>
            <p className="eyebrow" style={{ marginBottom: 7 }}>Dollar wire transfer</p>
            <h3 style={{ fontSize: 'clamp(24px,3.4vw,30px)', lineHeight: 1.1 }}>Send {usd} to this account</h3>
          </div>
          <button className="icobtn" onClick={onClose} aria-label="Close" style={{ marginRight: -8, marginTop: -4 }}><I.close width={21} height={21} /></button>
        </header>
        <div style={{ padding: '6px clamp(22px,4vw,32px) clamp(22px,4vw,30px)' }}>
          {row('Amount', usd)}
          {row('Bank', W.bank)}
          {row('Account name', W.accountName)}
          {row('Account number', W.accountNumber)}
          {row('SWIFT / BIC', W.swift)}
          {row('Routing / Sort', W.routing)}
          {row('Bank address', W.bankAddress)}
          {row('Reference', W.reference)}
          <div style={{ background: 'var(--accent-soft)', border: '1px solid var(--line)', borderRadius: 'var(--r-md)', padding: '15px 18px', marginTop: 20, display: 'flex', gap: 11, alignItems: 'flex-start', fontSize: 13.5, lineHeight: 1.6 }}>
            <I.shield width={19} height={19} style={{ color: 'var(--accent-deep)', flexShrink: 0, marginTop: 2 }} />
            <span>Use your order number as the transfer reference so we can match your payment. Your fabric is held for 48 hours while the wire clears — send proof of payment to <strong>{BB.BRAND.email}</strong> to speed this up. Wire fees are paid by the sender.</span>
          </div>
          <button className="btn btn-accent btn-block btn-lg" style={{ marginTop: 20 }} onClick={onClose}>Got it — continue</button>
        </div>
      </div>
    </div>
  );
}

/* ---------- Confirmation ---------- */
function ConfirmPage({ params }) {
  const { orders, nav, fmt } = useStore();
  const record = orders.find(o => o.num === params.num) || orders[0];
  if (!record) { return <div className="container" style={{ padding: '120px var(--gutter)', textAlign: 'center' }}><h1>No order found</h1><button className="btn btn-accent" style={{ marginTop: 20 }} onClick={() => nav('shop')}>Shop</button></div>; }
  const payLabel = record.payment === 'paystack' ? 'Paid with Paystack'
    : 'Dollar wire transfer — order held 48 hours while payment clears';
  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' }}>Order confirmed — <em style={{ color: 'var(--accent-deep)' }}>thank you</em></h1>
      <p className="muted" style={{ fontSize: 16.5 }}>Order <strong style={{ color: 'var(--ink)' }}>#{record.num}</strong>. A receipt is on its way to {record.email}.</p>
      <div style={{ background: 'var(--ivory)', border: '1px solid var(--line)', borderRadius: 'var(--r-lg)', padding: 26, marginTop: 32, textAlign: 'left', boxShadow: 'var(--shadow-sm)' }}>
        {record.lines.map((l, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', gap: 14, padding: '8px 0', fontSize: 14.5 }}>
            <span>{l.name} <span style={{ color: 'var(--ink-soft)' }}>× {l.qty} {l.unit}{l.qty !== 1 ? 's' : ''}</span></span>
            <strong style={{ fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>{fmt(l.total)}</strong>
          </div>
        ))}
        <hr className="divider" style={{ margin: '12px 0' }} />
        <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, color: 'var(--ink-soft)', padding: '4px 0' }}>
          <span>{record.method === 'pickup' ? 'Pickup' : record.zoneLabel}</span>
          <span>{record.shipping === 0 ? 'Free' : fmt(record.shipping)}</span>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 8 }}>
          <strong style={{ fontSize: 15 }}>Total paid</strong>
          <strong style={{ fontFamily: 'var(--serif)', fontSize: 25, fontVariantNumeric: 'tabular-nums' }}>{fmt(record.total)}</strong>
        </div>
        <p style={{ fontSize: 13, color: 'var(--ink-soft)', marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--line)' }}>
          {payLabel} · {record.method === 'pickup' ? 'Ready to collect within 24 hours — we’ll text you.' : `${record.zoneLabel} · ${record.eta}`}
        </p>
      </div>
      <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 30, flexWrap: 'wrap' }}>
        <button className="btn btn-primary btn-lg" onClick={() => nav('account')}>View my orders</button>
        <button className="btn btn-outline btn-lg" onClick={() => nav('shop')}>Continue shopping</button>
      </div>
    </div>
  );
}

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