// screens-checkout.jsx — checkout, confirmation

function CheckoutScreen({ app }) {
  const cartFirst = app.cart[0];
  const r = cartFirst ? RESTAURANT_LOOKUP[cartFirst.restaurant_id] : null;
  const [selectedAddress, setSelectedAddress] = React.useState(ADDRESSES.find(a => a.default)?.id);
  const [deliveryNotes, setDeliveryNotes] = React.useState('');
  const [scheduled, setScheduled] = React.useState('asap'); // 'asap' | 'later'
  const [paymentMethod, setPaymentMethod] = React.useState('card');
  const [promo, setPromo] = React.useState(app.promo?.code || '');
  const [promoApplied, setPromoApplied] = React.useState(!!app.promo);
  const [useWallet, setUseWallet] = React.useState(false);
  const [tip, setTip] = React.useState(2);
  const [placing, setPlacing] = React.useState(false);
  const [addressOpen, setAddressOpen] = React.useState(false);
  const [paymentOpen, setPaymentOpen] = React.useState(false);

  if (!app.authed) {
    // simulate redirect to auth then back
    React.useEffect(() => {
      app.setRedirectAfterAuth('checkout');
      app.nav('auth');
    }, []);
    return null;
  }

  if (!r || app.cart.length === 0) {
    return (
      <Screen>
        <CheckoutHeader app={app}/>
        <EmptyState
          title="Empty bag"
          body="Your bag is empty. Pick a restaurant and start an order."
          cta="Browse restaurants"
          onAction={() => app.nav('home')}
          icon={<Bull size={48}/>}
        />
      </Screen>
    );
  }

  const subtotal = app.cart.reduce((s,i) => s + i.price * i.quantity, 0);
  const delivery = r.deliveryFee;
  const promoDiscount = promoApplied ? (app.promo ? promoValue(app.promo, subtotal, delivery) : Math.min(subtotal * 0.1, 5)) : 0;
  const walletApplied = useWallet ? Math.min(app.walletBalance, subtotal + delivery + tip - promoDiscount) : 0;
  const total = Math.max(0, subtotal + delivery + tip - promoDiscount - walletApplied);
  const address = ADDRESSES.find(a => a.id === selectedAddress);

  const placeOrder = async () => {
    setPlacing(true);
    try {
      const order=await window.LassoCustomer.checkout({
        vendorSlug:r.slug,
        items:app.cart.map(ci => ({ name:ci.item_name, quantity:ci.quantity })),
        address:{ line1:address.line1, line2:address.line2 || null, city:address.city, postal_code:address.postcode, country_code:'GB', delivery_notes:deliveryNotes },
        tip
      });
      app.setActiveOrder({
        id: order.order_code,
        dbId: order.id,
        restaurantId: r.id,
        items: [...app.cart],
        subtotal, delivery, tip, promoDiscount, walletApplied, total,
        address: address,
        notes: deliveryNotes,
        paymentMethod,
        placedAt: Date.now(),
        status: order.status,
      });
      app.clearCart();
      app.nav('confirmation');
    } catch(error) { app.toast(error.message || 'Checkout could not be completed.', 'error'); }
    finally { setPlacing(false); }
  };

  return (
    <Screen scroll={false}>
      <CheckoutHeader app={app}/>

      <div style={{ flex: 1, overflow: 'auto', padding: '0 20px 30px', display: 'flex', flexDirection: 'column', gap: 14 }}>

        {/* Hero */}
        <div>
          <Eyebrow color="var(--brand-orange)">Final stretch</Eyebrow>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 26, letterSpacing: '-0.01em', marginTop: 6 }}>Just before you ride.</div>
        </div>

        {/* Delivery address */}
        <Section title="Deliver to" action={<span onClick={() => setAddressOpen(true)} style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 12, color: 'var(--brand-orange)', cursor: 'pointer' }}>Change</span>}>
          <div onClick={() => setAddressOpen(true)} style={{ display: 'flex', gap: 12, padding: 14, background: 'var(--bg-surface)', borderRadius: 16, border: '1.5px solid var(--soft-line)', cursor: 'pointer' }}>
            <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--bg-warm)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
              <Ico.pin c="var(--brand-orange)" s={18}/>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 14, color: 'var(--fg-primary)' }}>{address.label} · {address.line1}</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--warm-stone)', marginTop: 2 }}>{address.line2 ? `${address.line2}, ` : ''}{address.city} {address.postcode}</div>
            </div>
            <Ico.chev c="var(--warm-stone)" s={16}/>
          </div>

          {/* Delivery notes */}
          <div style={{ marginTop: 10 }}>
            <input
              placeholder="Notes for your rider (gate code, building entry, etc.)"
              value={deliveryNotes}
              onChange={e => setDeliveryNotes(e.target.value)}
              style={{
                width: '100%', height: 46, padding: '0 14px', borderRadius: 14,
                border: '1.5px solid var(--soft-line)', background: 'var(--bg-surface)',
                fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--fg-primary)',
                outline: 'none',
              }}/>
          </div>
        </Section>

        {/* Schedule */}
        <Section title="When">
          <div style={{ display: 'flex', gap: 8 }}>
            <ScheduleChip active={scheduled === 'asap'} onClick={() => setScheduled('asap')} label="ASAP" sub={r.etaShort}/>
            <ScheduleChip active={scheduled === 'later'} onClick={() => setScheduled('later')} label="Schedule" sub="Pick a time"/>
          </div>
        </Section>

        {/* Payment */}
        <Section title="Payment" action={<span onClick={() => setPaymentOpen(true)} style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 12, color: 'var(--brand-orange)', cursor: 'pointer' }}>Change</span>}>
          <PaymentRow method={paymentMethod} onClick={() => setPaymentOpen(true)}/>

          {/* Wallet credit */}
          <div style={{
            marginTop: 10, display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px',
            background: 'var(--bg-surface)', borderRadius: 14, border: '1.5px solid var(--soft-line)',
          }}>
            <div style={{ width: 36, height: 36, borderRadius: 10, background: 'rgba(46,139,78,0.1)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Ico.wallet c="var(--live-green)" s={18}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 13, color: 'var(--fg-primary)' }}>Wallet credit</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, color: 'var(--warm-stone)' }}>£{app.walletBalance.toFixed(2)} available</div>
            </div>
            <Toggle on={useWallet} onChange={setUseWallet}/>
          </div>
        </Section>

        {/* Promo code */}
        <Section title="Promo code">
          <div style={{
            display: 'flex', gap: 8, alignItems: 'center', padding: 6,
            background: 'var(--bg-surface)', borderRadius: 14, border: '1.5px solid var(--soft-line)',
          }}>
            <Ico.ticket c="var(--brand-orange)" s={18} style={{ marginLeft: 10 }}/>
            <input
              placeholder="WELCOME10"
              value={promo}
              onChange={e => setPromo(e.target.value)}
              disabled={promoApplied}
              style={{
                flex: 1, border: 'none', outline: 'none', background: 'transparent',
                fontFamily: 'var(--font-body)', fontSize: 13.5, color: 'var(--fg-primary)',
                textTransform: 'uppercase',
              }}/>
            <Button kind={promoApplied ? 'cream' : 'primary'} size="sm" onClick={() => {
              if (promoApplied) { setPromoApplied(false); setPromo(''); app.setPromo(null); }
              else if (promo.trim()) {
                const found = EARNED_PROMOS.find(p => p.code === promo.trim().toUpperCase());
                if (found) app.setPromo(found);
                setPromoApplied(true); app.toast('Promo applied', 'success');
              }
            }}>{promoApplied ? 'Remove' : 'Apply'}</Button>
          </div>
        </Section>

        {/* Tip your rider */}
        <Section title="Tip your rider">
          <div style={{ background: 'var(--bg-surface)', borderRadius: 16, border: '1.5px solid var(--soft-line)', padding: 14 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
              <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'linear-gradient(135deg,#F4E1C1,#F28C1B)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Bull size={20} variant="twotone"/>
              </div>
              <div style={{ flex: 1, fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--warm-stone)', lineHeight: 1.4 }}>
                100% goes to the rider. <strong style={{ color: 'var(--fg-primary)', fontFamily: 'var(--font-display)' }}>Riders remember good tippers.</strong>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              {[0, 1, 2, 3, 5].map(t => {
                const on = t === tip;
                return (
                  <button key={t} onClick={() => setTip(t)} style={{
                    flex: 1, padding: '11px 4px', borderRadius: 12, cursor: 'pointer',
                    background: on ? 'var(--dark-chocolate)' : 'var(--bg-app)',
                    color: on ? 'var(--dust-cream)' : 'var(--fg-primary)',
                    border: '1.5px solid ' + (on ? 'var(--dark-chocolate)' : 'var(--soft-line)'),
                    fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 14,
                    transition: 'all 160ms var(--ease-out)', transform: on ? 'scale(1.05)' : 'scale(1)',
                  }}>{t === 0 ? 'None' : `£${t}`}</button>
                );
              })}
            </div>
            {tip >= 3 && <div style={{ marginTop: 10, fontFamily: 'var(--font-body)', fontSize: 11.5, color: 'var(--live-green)', fontWeight: 600 }}>Generous, partner — that’s top 10% of tippers tonight.</div>}
          </div>
        </Section>

        {/* Order summary */}
        <Section title="Order summary">
          <div style={{ background: 'var(--bg-surface)', borderRadius: 16, padding: 14, border: '1.5px solid var(--soft-line)', display: 'flex', flexDirection: 'column', gap: 12 }}>
            {/* From */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, overflow: 'hidden' }}>
                <FoodPh height={36} hue={r.hue} radius={10}/>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 13.5, color: 'var(--fg-primary)' }}>{r.name}</div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, color: 'var(--warm-stone)' }}>{r.area} · {r.etaShort}</div>
              </div>
            </div>
            <div style={{ height: 1, background: 'var(--soft-line)' }}/>

            {/* Items */}
            {app.cart.map(ci => (
              <div key={ci.cart_id} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--fg-primary)', flex: 1, minWidth: 0 }}>
                  <strong style={{ fontFamily: 'var(--font-display)', fontWeight: 800 }}>{ci.quantity}× </strong>{ci.item_name}
                  {(ci.modifiers || []).length > 0 && (
                    <span style={{ color: 'var(--warm-stone)', fontSize: 11.5 }}> · {ci.modifiers.slice(0,2).map(m=>m.name).join(', ')}</span>
                  )}
                </div>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 13, color: 'var(--fg-primary)' }}>£{(ci.price * ci.quantity).toFixed(2)}</div>
              </div>
            ))}
            <div style={{ height: 1, background: 'var(--soft-line)' }}/>

            {/* Totals */}
            <Line label="Subtotal" value={`£${subtotal.toFixed(2)}`}/>
            <Line label="Delivery fee" value={`£${delivery.toFixed(2)}`}/>
            {tip > 0 && <Line label="Rider tip" value={`£${tip.toFixed(2)}`}/>}
            {promoApplied && <Line label="Promo discount" value={`−£${promoDiscount.toFixed(2)}`} color="var(--live-green)"/>}
            {walletApplied > 0 && <Line label="Wallet credit" value={`−£${walletApplied.toFixed(2)}`} color="var(--live-green)"/>}
            <div style={{ height: 1, background: 'var(--soft-line)' }}/>
            <Line label="Total" value={`£${total.toFixed(2)}`} bold/>
          </div>
        </Section>
      </div>

      {/* Sticky CTA */}
      <div style={{ padding: '12px 20px 16px', background: 'var(--bg-app)', borderTop: '1px solid var(--soft-line)' }}>
        <Button kind="accent" full size="lg" onClick={placeOrder} disabled={placing}>
          {placing ? 'Placing your order…' : `Place order · £${total.toFixed(2)}`}
        </Button>
      </div>

      {/* Address picker */}
      <BottomSheet open={addressOpen} onClose={() => setAddressOpen(false)} title="Saved addresses">
        <div style={{ padding: '0 20px 30px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {ADDRESSES.map(a => (
            <button key={a.id} onClick={() => { setSelectedAddress(a.id); setAddressOpen(false); }} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: 14, borderRadius: 14, cursor: 'pointer',
              background: selectedAddress === a.id ? 'var(--bg-warm)' : 'var(--bg-surface)',
              border: '1.5px solid ' + (selectedAddress === a.id ? 'var(--brand-orange)' : 'var(--soft-line)'),
              textAlign: 'left',
            }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Ico.pin c="var(--brand-orange)" s={18}/>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 14, color: 'var(--fg-primary)' }}>{a.label}</div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--warm-stone)', marginTop: 2 }}>{a.line1}{a.line2 ? `, ${a.line2}` : ''}, {a.city}</div>
              </div>
              {selectedAddress === a.id && <Ico.check c="var(--brand-orange)" s={18}/>}
            </button>
          ))}
          <button style={{
            display: 'flex', alignItems: 'center', gap: 12, padding: 14, borderRadius: 14, cursor: 'pointer',
            background: 'transparent', border: '1.5px dashed var(--soft-line)', textAlign: 'left',
          }}>
            <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--bg-warm)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Ico.plus c="var(--horse-brown)" s={18}/>
            </div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 14, color: 'var(--fg-primary)' }}>Add new address</div>
          </button>
        </div>
      </BottomSheet>

      {/* Payment picker */}
      <BottomSheet open={paymentOpen} onClose={() => setPaymentOpen(false)} title="Payment method">
        <div style={{ padding: '0 20px 30px', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {[
            { id: 'card', label: 'Visa · ending 4242', sub: 'Default', icon: <Ico.card c="var(--fg-primary)" s={18}/> },
            { id: 'apple', label: 'Apple Pay', sub: 'iPhone', icon: <span style={{ fontFamily: 'system-ui', fontWeight: 600, fontSize: 16 }}></span> },
            { id: 'google', label: 'Google Pay', sub: 'Linked account', icon: <Ico.google s={18}/> },
            { id: 'cash', label: 'Cash on delivery', sub: 'Rider takes payment', icon: <Ico.wallet c="var(--fg-primary)" s={18}/> },
          ].map(p => (
            <button key={p.id} onClick={() => { setPaymentMethod(p.id); setPaymentOpen(false); }} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: 14, borderRadius: 14, cursor: 'pointer',
              background: paymentMethod === p.id ? 'var(--bg-warm)' : 'var(--bg-surface)',
              border: '1.5px solid ' + (paymentMethod === p.id ? 'var(--brand-orange)' : 'var(--soft-line)'),
              textAlign: 'left',
            }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {p.icon}
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 14, color: 'var(--fg-primary)' }}>{p.label}</div>
                <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--warm-stone)', marginTop: 2 }}>{p.sub}</div>
              </div>
              {paymentMethod === p.id && <Ico.check c="var(--brand-orange)" s={18}/>}
            </button>
          ))}
        </div>
      </BottomSheet>
    </Screen>
  );
}

function CheckoutHeader({ app }) {
  return (
    <div style={{ padding: '12px 20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
      <button onClick={() => app.back()} style={{
        width: 40, height: 40, borderRadius: 14, border: '1.5px solid var(--soft-line)',
        background: 'var(--bg-surface)', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
      }}><Ico.chevL c="var(--fg-primary)" s={20}/></button>
      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 17, color: 'var(--fg-primary)' }}>Checkout</div>
      <div style={{ width: 40 }}/>
    </div>
  );
}

function Section({ title, action, children }) {
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', padding: '0 4px 8px' }}>
        <Eyebrow>{title}</Eyebrow>
        {action}
      </div>
      {children}
    </div>
  );
}

function Line({ label, value, bold, color }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
      <span style={{ fontFamily: 'var(--font-body)', fontSize: bold ? 14 : 13, color: color || (bold ? 'var(--fg-primary)' : 'var(--warm-stone)'), fontWeight: bold ? 700 : 400 }}>{label}</span>
      <span style={{ fontFamily: 'var(--font-display)', fontWeight: bold ? 900 : 700, fontSize: bold ? 16 : 13, color: color || 'var(--fg-primary)' }}>{value}</span>
    </div>
  );
}

function ScheduleChip({ active, onClick, label, sub }) {
  return (
    <button onClick={onClick} style={{
      flex: 1, padding: '12px 16px', borderRadius: 14, cursor: 'pointer',
      background: active ? 'var(--dark-chocolate)' : 'var(--bg-surface)',
      color: active ? 'var(--dust-cream)' : 'var(--fg-primary)',
      border: '1.5px solid ' + (active ? 'var(--dark-chocolate)' : 'var(--soft-line)'),
      textAlign: 'left',
    }}>
      <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 13 }}>{label}</div>
      <div style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, color: active ? '#9F8979' : 'var(--warm-stone)', marginTop: 2 }}>{sub}</div>
    </button>
  );
}

function PaymentRow({ method, onClick }) {
  const display = {
    card: { label: 'Visa · 4242', sub: 'Expires 09/27', icon: <Ico.card c="var(--fg-primary)" s={18}/> },
    apple: { label: 'Apple Pay', sub: 'iPhone', icon: <span style={{ fontFamily: 'system-ui', fontWeight: 600, fontSize: 16 }}></span> },
    google: { label: 'Google Pay', sub: 'Linked account', icon: <Ico.google s={18}/> },
    cash: { label: 'Cash on delivery', sub: 'Rider takes payment', icon: <Ico.wallet c="var(--fg-primary)" s={18}/> },
  }[method];
  return (
    <div onClick={onClick} style={{
      display: 'flex', gap: 12, padding: 14, background: 'var(--bg-surface)', borderRadius: 14,
      border: '1.5px solid var(--soft-line)', cursor: 'pointer', alignItems: 'center',
    }}>
      <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--bg-warm)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {display.icon}
      </div>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 14, color: 'var(--fg-primary)' }}>{display.label}</div>
        <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--warm-stone)', marginTop: 2 }}>{display.sub}</div>
      </div>
      <Ico.chev c="var(--warm-stone)" s={16}/>
    </div>
  );
}

function Toggle({ on, onChange }) {
  return (
    <button onClick={() => onChange(!on)} style={{
      width: 44, height: 26, borderRadius: 999, border: 'none', cursor: 'pointer',
      background: on ? 'var(--brand-orange)' : 'var(--soft-line)',
      position: 'relative', transition: 'background 220ms var(--ease-out)',
    }}>
      <span style={{
        position: 'absolute', top: 3, left: on ? 21 : 3, width: 20, height: 20, borderRadius: '50%', background: '#fff',
        transition: 'left 220ms var(--ease-out)', boxShadow: '0 2px 4px rgba(0,0,0,0.18)',
      }}/>
    </button>
  );
}

// ─── Confirmation screen ────────────────────────────────────────────
function ConfirmationScreen({ app }) {
  const order = app.activeOrder;
  const paymentPending = order?.status === 'payment_pending';
  const [pulse, setPulse] = React.useState(false);
  React.useEffect(() => { setTimeout(() => setPulse(true), 50); }, []);

  // Lucky Strike prompt — only after payment is actually confirmed.
  React.useEffect(() => {
    if (paymentPending) return;
    if (app.lsJoined) return;
    let seen = false;
    try { seen = localStorage.getItem('lasso_ls_prompt_seen_v1') === '1'; } catch (e) {}
    if (seen) return;
    const t = setTimeout(() => {
      try { localStorage.setItem('lasso_ls_prompt_seen_v1', '1'); } catch (e) {}
      app.openLuckyStrike('confirmation');
    }, 2200);
    return () => clearTimeout(t);
  }, [paymentPending]);

  if (!order) {
    return (
      <Screen>
        <EmptyState title="No order found" body="Your order could not be loaded." cta="Back home" onAction={() => app.nav('home')}/>
      </Screen>
    );
  }

  const r = RESTAURANT_LOOKUP[order.restaurantId];
  const earn = app.lastEarn || { gained: Math.max(10, Math.round(order.total * 2)), streak: PROFILE.streak_current + 1 };
  return (
    <Screen>
      <div style={{ flex: 1, overflow: 'auto', padding: '40px 20px 30px', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 18, textAlign: 'center', position: 'relative' }}>

        {/* Confetti burst */}
        <style>{`
          @keyframes lassoConfetti {
            0% { transform: translateY(0) rotate(0deg); opacity: 1; }
            100% { transform: translateY(340px) rotate(540deg); opacity: 0; }
          }
        `}</style>
        <div aria-hidden="true" style={{ position: 'absolute', top: 0, left: 0, right: 0, height: 0, pointerEvents: 'none', zIndex: 2 }}>
          {['#D85A14','#F28C1B','#F4E1C1','#5B240A','#2E8B4E','#D85A14','#F28C1B','#F4E1C1','#F28C1B','#D85A14','#F4E1C1','#2E8B4E'].map((c, i) => (
            <span key={i} style={{
              position: 'absolute', top: -10, left: `${6 + i * 8}%`,
              width: i % 3 === 0 ? 10 : 7, height: i % 2 === 0 ? 12 : 8,
              background: c, borderRadius: i % 3 === 0 ? '50%' : 2,
              animation: `lassoConfetti ${1.6 + (i % 5) * 0.35}s ${0.05 + (i % 4) * 0.18}s cubic-bezier(.2,.6,.4,1) forwards`,
              opacity: 0,
            }}/>
          ))}
        </div>

        {/* Success badge */}
        <div style={{
          width: 110, height: 110, borderRadius: '50%',
          background: 'radial-gradient(circle at 50% 40%, #F28C1B, #D85A14)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: '0 20px 40px -10px rgba(216,90,20,0.55)',
          transform: pulse ? 'scale(1)' : 'scale(0.6)',
          transition: 'transform 600ms var(--ease-out)',
        }}>
          <Bull size={68} variant="twotone"/>
        </div>

        <div>
          <Eyebrow color="var(--brand-orange)">{paymentPending ? 'Payment pending' : 'Order placed'}</Eyebrow>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 32, letterSpacing: '-0.01em', lineHeight: 1.0, marginTop: 8 }}>{paymentPending ? 'Hold your horses.' : "You're in the saddle."}</div>
          <div style={{ fontFamily: 'var(--font-body)', fontSize: 14, color: 'var(--warm-stone)', marginTop: 8, lineHeight: 1.5 }}>
            {paymentPending ? 'Your order is held until payment is confirmed. We have not sent it to the kitchen.' : `We've sent the order to ${r?.name}. The kitchen's already on it.`}
          </div>
          {!paymentPending && <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, marginTop: 14 }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 16px', borderRadius: 999, background: 'var(--dark-chocolate)', animation: 'lasso-bag-pop 420ms 300ms var(--ease-out) backwards', position: 'relative', overflow: 'hidden' }}>
              <span className="lv-sweep-once" aria-hidden="true" style={{
                position: 'absolute', inset: 0, borderRadius: 999, pointerEvents: 'none',
                background: 'linear-gradient(105deg, transparent 40%, rgba(242,140,27,0.5) 50%, transparent 60%)',
                backgroundSize: '260% 100%', backgroundRepeat: 'no-repeat', backgroundPosition: '-140% 0',
              }}/>
              <Ico.badge c="var(--sun-orange)" s={15}/>
              <span data-lasso="xp-earned" style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 13, color: 'var(--dust-cream)', position: 'relative' }}>+<CountUp to={earn.gained} duration={900}/> XP</span>
              <span style={{ fontFamily: 'var(--font-body)', fontSize: 11.5, color: '#9F8979' }}>· streak day {earn.streak} secured</span>
            </div>
            {earn.challenge && (earn.challenge.completed ? (
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 16px', borderRadius: 999, background: 'rgba(46,139,78,0.12)', animation: 'lasso-bag-pop 420ms 480ms var(--ease-out) backwards' }}>
                <Ico.check c="var(--live-green)" s={14}/>
                <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 12, color: 'var(--live-green)' }}>Challenge done — {earn.challenge.title} · +{earn.challenge.xp} XP</span>
              </div>
            ) : (
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 7, padding: '7px 14px', borderRadius: 999, background: 'var(--bg-warm)', border: '1.5px solid var(--soft-line)', animation: 'lasso-bag-pop 420ms 480ms var(--ease-out) backwards' }}>
                <Ico.flame c="var(--brand-orange)" s={13}/>
                <span style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 12, color: 'var(--horse-brown)' }}>{earn.challenge.title} · {earn.challenge.progress}/{earn.challenge.total}</span>
              </div>
            ))}
          </div>}
        </div>

        {/* Card */}
        <div style={{
          width: '100%', background: 'var(--bg-surface)', borderRadius: 22, padding: 18,
          border: '1.5px solid var(--soft-line)', display: 'flex', flexDirection: 'column', gap: 14, textAlign: 'left',
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <Eyebrow>Order</Eyebrow>
            <div data-lasso="order-id" style={{ fontFamily: 'var(--font-mono)', fontWeight: 500, fontSize: 12, color: 'var(--fg-secondary)' }}>{order.id}</div>
          </div>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <div style={{ width: 48, height: 48, borderRadius: 12, overflow: 'hidden' }}>
              <FoodPh height={48} hue={r.hue} radius={12}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 16, color: 'var(--fg-primary)' }}>{r.name}</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--warm-stone)' }}>{order.items.length} {order.items.length === 1 ? 'item' : 'items'} · £{order.total.toFixed(2)}</div>
            </div>
          </div>

          <div style={{ height: 1, background: 'var(--soft-line)' }}/>

          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 10.5, color: 'var(--warm-stone)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600 }}>{paymentPending ? 'Next step' : 'Arriving'}</div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 900, fontSize: 20, color: 'var(--brand-orange)', marginTop: 2 }}>{paymentPending ? 'Confirm payment' : r.etaShort}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 10.5, color: 'var(--warm-stone)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600 }}>Deliver to</div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 800, fontSize: 13, color: 'var(--fg-primary)', marginTop: 2 }}>{order.address.label}</div>
              <div style={{ fontFamily: 'var(--font-body)', fontSize: 11, color: 'var(--warm-stone)' }}>{order.address.line1}</div>
            </div>
          </div>

          <div style={{ height: 1, background: 'var(--soft-line)' }}/>

          <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', background: paymentPending ? 'rgba(242,140,27,0.12)' : 'rgba(46,139,78,0.1)', borderRadius: 12 }}>
            <div style={{ width: 8, height: 8, borderRadius: '50%', background: paymentPending ? 'var(--sun-orange)' : 'var(--live-green)' }}/>
            <div style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: paymentPending ? 'var(--horse-brown)' : 'var(--live-green)', flex: 1, fontWeight: 600 }}>{paymentPending ? 'Payment confirmation required' : 'Payment confirmed'}</div>
            {paymentPending ? <Ico.card c="var(--horse-brown)" s={16}/> : <Ico.check c="var(--live-green)" s={16}/>}
          </div>
        </div>

        <div style={{ width: '100%', display: 'flex', flexDirection: 'column', gap: 10 }}>
          <Button kind="accent" full size="lg" onClick={() => app.nav(paymentPending ? 'checkout' : 'tracking')}>{paymentPending ? 'Return to payment' : 'Track my order'}</Button>
          <Button kind="cream" full size="md" onClick={() => app.nav('home')}>Back to home</Button>
        </div>
      </div>
    </Screen>
  );
}

Object.assign(window, { CheckoutScreen, ConfirmationScreen, Toggle });
