// W2Go screens — Checkout, Tracking, Order Done, Orders list, Account

const { useState: useStateC, useEffect: useEffectC, useRef: useRefC } = React;

// ───────────────────────────────────────────────────────────────
// 9. CHECKOUT
// ───────────────────────────────────────────────────────────────
function CheckoutScreen({ go, cart, address, placeOrder }) {
  const [dropoff, setDropoff] = useStateC('door'); // door | hand | leave
  const [pay, setPay] = useStateC('applepay');
  const [tip, setTip] = useStateC(10);
  const [notes, setNotes] = useStateC('');

  const sub = cart.reduce((a, c) => a + c.unitPrice * c.qty, 0);
  const delivery = 8, fee = 4;
  const total = sub + delivery + fee + tip;

  const tips = [0, 5, 10, 15, 20];

  return (
    <div style={{ position: 'absolute', inset: 0, paddingTop: 50, boxSizing: 'border-box', background: 'var(--w-cream)', display: 'flex', flexDirection: 'column' }}>
      <TopBar onBack={() => go('cart')} title="Checkout"/>
      <Scroll pad={140} style={{ padding: '8px 20px 0' }}>
        {/* Address */}
        <Block title="Delivery address" action={<button onClick={() => go('location')} style={btnLink}>Change</button>}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
            <div style={{ width: 40, height: 40, borderRadius: 12, background: 'rgba(0,76,75,0.1)', color: 'var(--w-green)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Ic.Home size={20}/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 700 }}>{address?.label || 'Home'}</div>
              <div style={{ fontSize: 12.5, opacity: 0.65 }}>{address?.line || 'Tower 2, The Pearl'} · {address?.city || 'Doha, Qatar'}</div>
            </div>
          </div>
        </Block>

        {/* Drop-off */}
        <Block title="Drop-off">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[
              { id: 'door',  label: 'Hand it to me at the door', icon: Ic.Door },
              { id: 'leave', label: 'Leave at the door',         icon: Ic.Box  },
              { id: 'hand',  label: 'Meet outside',              icon: Ic.User },
            ].map(o => {
              const I = o.icon; const on = dropoff === o.id;
              return (
                <button key={o.id} onClick={() => setDropoff(o.id)} style={{
                  display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderRadius: 14,
                  border: on ? '2px solid var(--w-green)' : '1.5px solid rgba(23,25,25,0.08)',
                  background: on ? 'rgba(0,76,75,0.04)' : '#fff', cursor: 'pointer',
                  fontFamily: 'inherit', textAlign: 'left'
                }}>
                  <I size={20} style={{ color: 'var(--w-onyx)' }}/>
                  <div style={{ flex: 1, fontSize: 14, fontWeight: 600 }}>{o.label}</div>
                  <div style={{
                    width: 20, height: 20, borderRadius: 999,
                    border: '2px solid ' + (on ? 'var(--w-green)' : 'rgba(23,25,25,0.18)'),
                    display: 'flex', alignItems: 'center', justifyContent: 'center'
                  }}>{on && <div style={{ width: 10, height: 10, borderRadius: 999, background: 'var(--w-green)' }}/>}</div>
                </button>
              );
            })}
            <input value={notes} onChange={e => setNotes(e.target.value)}
                   placeholder="Note to rider (apt buzzer, gate code…)"
                   style={{
                     marginTop: 4, padding: '12px 14px', borderRadius: 12, fontSize: 13,
                     border: '1.5px solid rgba(23,25,25,0.08)', background: '#fff', outline: 'none',
                     fontFamily: 'inherit'
                   }}/>
          </div>
        </Block>

        {/* Payment */}
        <Block title="Payment">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[
              { id: 'applepay', label: 'Apple Pay',   sub: 'Touch ID', icon: Ic.Apple, bg: '#000', fg: '#fff' },
              { id: 'card',     label: 'Visa ••4821', sub: 'Default',  icon: Ic.Card,  bg: 'var(--w-green)', fg: 'var(--w-cream)' },
              { id: 'cash',     label: 'Cash on delivery', sub: 'Exact change preferred', icon: Ic.Wallet, bg: 'var(--w-onyx)', fg: 'var(--w-cream)' },
            ].map(p => {
              const I = p.icon; const on = pay === p.id;
              return (
                <button key={p.id} onClick={() => setPay(p.id)} style={{
                  display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px', borderRadius: 14,
                  border: on ? '2px solid var(--w-green)' : '1.5px solid rgba(23,25,25,0.08)',
                  background: on ? 'rgba(0,76,75,0.04)' : '#fff', cursor: 'pointer',
                  fontFamily: 'inherit', textAlign: 'left'
                }}>
                  <div style={{
                    width: 40, height: 28, borderRadius: 6, background: p.bg, color: p.fg,
                    display: 'flex', alignItems: 'center', justifyContent: 'center'
                  }}><I size={16}/></div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 700 }}>{p.label}</div>
                    <div style={{ fontSize: 11.5, opacity: 0.55 }}>{p.sub}</div>
                  </div>
                  <div style={{
                    width: 20, height: 20, borderRadius: 999,
                    border: '2px solid ' + (on ? 'var(--w-green)' : 'rgba(23,25,25,0.18)'),
                    display: 'flex', alignItems: 'center', justifyContent: 'center'
                  }}>{on && <div style={{ width: 10, height: 10, borderRadius: 999, background: 'var(--w-green)' }}/>}</div>
                </button>
              );
            })}
          </div>
        </Block>

        {/* Tip */}
        <Block title="Tip your rider"
               action={<span style={{ fontSize: 11, opacity: 0.55, fontWeight: 700, letterSpacing: 1.2 }}>100% TO RIDER</span>}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8 }}>
            {tips.map(t => (
              <button key={t} onClick={() => setTip(t)} style={{
                padding: '12px 4px', borderRadius: 12,
                border: tip === t ? '2px solid var(--w-green)' : '1.5px solid rgba(23,25,25,0.1)',
                background: tip === t ? 'rgba(0,76,75,0.06)' : '#fff',
                fontFamily: 'inherit', cursor: 'pointer',
              }}>
                <div style={{ fontWeight: 800, fontSize: 14, color: 'var(--w-onyx)' }}>{t === 0 ? '—' : W2_money(t)}</div>
                <div style={{ fontSize: 10, opacity: 0.55, marginTop: 2, fontWeight: 600 }}>
                  {t === 0 ? 'None' : t < 8 ? 'Tap' : t < 12 ? 'Solid' : t < 18 ? 'Big up' : 'Hero'}
                </div>
              </button>
            ))}
          </div>
        </Block>

        {/* Summary */}
        <Block title="Order summary">
          {cart.map((l, i) => (
            <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', fontSize: 13.5 }}>
              <span><b style={{ marginRight: 6 }}>{l.qty}×</b>{l.item.name}</span>
              <span style={{ fontWeight: 700 }}>{W2_money(l.unitPrice * l.qty)}</span>
            </div>
          ))}
          <div style={{ height: 1, background: 'rgba(23,25,25,0.1)', margin: '12px 0' }}/>
          <Row label="Subtotal" value={W2_money(sub)}/>
          <Row label="Delivery" value={W2_money(delivery)}/>
          <Row label="Service fee" value={W2_money(fee)}/>
          <Row label="Rider tip" value={W2_money(tip)}/>
          <div style={{ height: 1, background: 'rgba(23,25,25,0.1)', margin: '8px 0' }}/>
          <Row big label="Total" value={W2_money(total)}/>
        </Block>

        <div style={{ height: 16 }}/>
      </Scroll>

      <BottomDock>
        <Btn full onClick={() => placeOrder({ dropoff, pay, tip, notes, total })}
             iconRight={<Ic.Arrow size={18}/>}>Place order · {W2_money(total)}</Btn>
        <div style={{ marginTop: 8, fontSize: 11, opacity: 0.45, textAlign: 'center' }}>
          Tap to confirm — you can cancel for free for the first 2 minutes.
        </div>
      </BottomDock>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────
// 9.5  PAYMENT — Apple Pay-style sheet → success → tracking
// ───────────────────────────────────────────────────────────────
function PaymentScreen({ go, order, paymentComplete }) {
  const [stage, setStage] = useStateC('ready'); // ready | auth | processing | success
  const total = order?.total || 0;
  const pay = order?.pay || 'applepay';
  const tip = order?.tip || 0;
  const items = order?.items || [];

  useEffectC(() => {
    if (stage === 'auth') {
      const t = setTimeout(() => setStage('processing'), 1400);
      return () => clearTimeout(t);
    }
    if (stage === 'processing') {
      const t = setTimeout(() => setStage('success'), 1600);
      return () => clearTimeout(t);
    }
    if (stage === 'success') {
      const t = setTimeout(() => paymentComplete(), 1200);
      return () => clearTimeout(t);
    }
  }, [stage]);

  const payMeta = {
    applepay: { label: 'Apple Pay',         sub: 'Face ID',    bg: '#000',         fg: '#fff', icon: Ic.Apple },
    card:     { label: 'Visa •• 4821',      sub: 'Card',       bg: 'var(--w-green)', fg: 'var(--w-cream)', icon: Ic.Card },
    cash:     { label: 'Cash on delivery',  sub: 'Pay rider',  bg: 'var(--w-onyx)', fg: 'var(--w-cream)', icon: Ic.Wallet },
  }[pay] || {};

  // Cash: skip processing — just confirm
  const isCash = pay === 'cash';

  return (
    <div style={{
      position: 'absolute', inset: 0, paddingTop: 50, boxSizing: 'border-box',
      background: 'var(--w-onyx)', color: 'var(--w-cream)',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      {/* dim photographic bg */}
      <img src="assets/box-3d.jpg" alt="" style={{
        position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover',
        opacity: 0.18, mixBlendMode: 'screen', filter: 'blur(3px)'
      }}/>
      <div style={{
        position: 'absolute', inset: 0,
        background: 'radial-gradient(80% 60% at 50% 30%, rgba(0,76,75,0.25) 0%, rgba(11,15,15,0.95) 75%)'
      }}/>

      {/* close */}
      <div style={{ position: 'relative', padding: '16px 16px 0' }}>
        <button onClick={() => go('checkout')} style={{
          width: 40, height: 40, borderRadius: 999, background: 'rgba(255,255,255,0.08)', border: 'none',
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: 'var(--w-cream)'
        }} disabled={stage !== 'ready'}><Ic.Close size={18}/></button>
      </div>

      <div style={{ position: 'relative', flex: 1, padding: '8px 24px 24px', display: 'flex', flexDirection: 'column' }}>
        {/* Brand */}
        <Wordmark size={28} color="var(--w-cream)" sub={null}/>

        <div style={{ fontSize: 11, letterSpacing: 2.4, fontWeight: 700, opacity: 0.55, marginTop: 28 }}>
          {stage === 'success' ? 'PAYMENT CONFIRMED' : 'PAY WITH'}
        </div>

        {/* Payment card */}
        <div style={{
          marginTop: 12, padding: '20px 18px', borderRadius: 18,
          background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.08)',
          display: 'flex', alignItems: 'center', gap: 14,
        }}>
          <div style={{
            width: 56, height: 40, borderRadius: 8, background: payMeta.bg, color: payMeta.fg,
            display: 'flex', alignItems: 'center', justifyContent: 'center'
          }}><payMeta.icon size={20}/></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 16, fontWeight: 800, letterSpacing: -0.2 }}>{payMeta.label}</div>
            <div style={{ fontSize: 12, opacity: 0.6, marginTop: 2 }}>{payMeta.sub}</div>
          </div>
          <div style={{
            fontSize: 22, fontWeight: 800, letterSpacing: -0.5, color: 'var(--w-cream)'
          }}>{W2_money(total)}</div>
        </div>

        {/* Bill stub */}
        <div style={{ marginTop: 18, padding: '14px 16px', borderRadius: 14,
                      background: 'rgba(255,255,255,0.04)', border: '1px dashed rgba(255,255,255,0.10)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
            <span style={{ fontSize: 11, letterSpacing: 1.4, fontWeight: 700, opacity: 0.55 }}>ORDER · W2-{Math.floor(Math.random()*9000+1000)}</span>
            <span style={{ fontSize: 11, opacity: 0.55 }}>{items.length} {items.length === 1 ? 'item' : 'items'}</span>
          </div>
          {items.slice(0, 3).map((l, i) => (
            <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '3px 0', fontSize: 13 }}>
              <span style={{ opacity: 0.85 }}><b style={{ opacity: 0.6, marginRight: 6 }}>{l.qty}×</b>{l.item.name}</span>
              <span style={{ fontWeight: 600 }}>{W2_money(l.unitPrice * l.qty)}</span>
            </div>
          ))}
          {items.length > 3 && (
            <div style={{ fontSize: 12, opacity: 0.55, padding: '4px 0' }}>+ {items.length - 3} more</div>
          )}
          <div style={{ height: 1, background: 'rgba(255,255,255,0.10)', margin: '10px 0' }}/>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, opacity: 0.7, padding: '2px 0' }}>
            <span>Delivery · service</span><span>{W2_money(12)}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, opacity: 0.7, padding: '2px 0' }}>
            <span>Rider tip</span><span>{W2_money(tip)}</span>
          </div>
        </div>

        {/* Center action: face-id / spinner / check */}
        <div style={{
          marginTop: 32, display: 'flex', flexDirection: 'column', alignItems: 'center',
          gap: 14, minHeight: 180
        }}>
          {stage === 'ready' && (
            <>
              <div style={{
                width: 96, height: 96, borderRadius: 28,
                background: 'rgba(255,255,255,0.08)', border: '1.5px solid rgba(255,255,255,0.12)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>
                {pay === 'applepay' ? <FaceID/> : (pay === 'card' ? <Ic.Lock size={36}/> : <Ic.Wallet size={36}/>)}
              </div>
              <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: -0.2, textAlign: 'center' }}>
                {pay === 'applepay' && 'Double-click side button'}
                {pay === 'card' && 'Confirm with card'}
                {pay === 'cash' && 'Confirm cash order'}
              </div>
              <div style={{ fontSize: 13, opacity: 0.55, textAlign: 'center', maxWidth: 260, lineHeight: 1.4 }}>
                {pay === 'applepay' && 'Then Face ID will authorize the payment.'}
                {pay === 'card' && 'Your card will be charged once the rider picks up.'}
                {pay === 'cash' && 'Hand the rider exact change if possible.'}
              </div>
            </>
          )}

          {stage === 'auth' && (
            <>
              <div style={{
                width: 96, height: 96, borderRadius: 28,
                background: 'rgba(0,76,75,0.25)', border: '1.5px solid rgba(0,76,75,0.5)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                animation: 'w-pulse-scale 1.4s ease-in-out infinite'
              }}>
                <FaceID color="var(--w-cream)"/>
              </div>
              <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: -0.2 }}>Authorizing…</div>
              <div style={{ fontSize: 13, opacity: 0.55 }}>Hold still, just a moment.</div>
            </>
          )}

          {stage === 'processing' && (
            <>
              <Spinner size={88}/>
              <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: -0.2 }}>Sending to kitchen…</div>
              <div style={{ fontSize: 13, opacity: 0.55 }}>{isCash ? 'Order locked in.' : 'Payment cleared.'} Cooking starts now.</div>
            </>
          )}

          {stage === 'success' && (
            <>
              <div style={{
                width: 96, height: 96, borderRadius: 999,
                background: 'var(--w-green)', display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: 'var(--w-cream)', animation: 'w-pop 400ms cubic-bezier(.2,.9,.3,1.2) both'
              }}>
                <Ic.Check size={48} stroke={3.5}/>
              </div>
              <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: -0.4, textAlign: 'center' }}>
                Cravings locked.
              </div>
              <div style={{ fontSize: 13, opacity: 0.7, textAlign: 'center', maxWidth: 280, lineHeight: 1.4 }}>
                Your order is in the W Doha kitchen.<br/>We'll text you when the rider's rolling.
              </div>
            </>
          )}
        </div>

        <div style={{ marginTop: 'auto', paddingTop: 14 }}>
          {stage === 'ready' && (
            <Btn full kind="cream" onClick={() => setStage(isCash ? 'processing' : 'auth')}
                 iconRight={<Ic.Arrow size={18}/>}>
              {pay === 'applepay' && 'Pay ' + W2_money(total)}
              {pay === 'card' && 'Confirm ' + W2_money(total)}
              {pay === 'cash' && 'Place order'}
            </Btn>
          )}
          {(stage === 'auth' || stage === 'processing') && (
            <Btn full kind="ghostInv" disabled>Please wait…</Btn>
          )}
          {stage === 'success' && (
            <Btn full kind="cream" onClick={paymentComplete} iconRight={<Ic.Arrow size={18}/>}>
              Track your order
            </Btn>
          )}
          <div style={{ marginTop: 10, fontSize: 11, opacity: 0.4, textAlign: 'center' }}>
            Secured by W2GO · 256-bit TLS · Doha, Qatar
          </div>
        </div>
      </div>

      <style>{`
        @keyframes w-pulse-scale {
          0%, 100% { transform: scale(1); }
          50% { transform: scale(1.05); }
        }
        @keyframes w-pop {
          0% { transform: scale(0); opacity: 0; }
          60% { transform: scale(1.15); opacity: 1; }
          100% { transform: scale(1); opacity: 1; }
        }
        @keyframes w-spin {
          to { transform: rotate(360deg); }
        }
      `}</style>
    </div>
  );
}

// Face-ID style icon
function FaceID({ color = 'currentColor' }) {
  return (
    <svg width="48" height="48" viewBox="0 0 48 48" fill="none" stroke={color} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14 6h-4a4 4 0 00-4 4v4M34 6h4a4 4 0 014 4v4M34 42h4a4 4 0 004-4v-4M14 42h-4a4 4 0 01-4-4v-4"/>
      <path d="M18 20v3M30 20v3"/>
      <path d="M24 20v8l-3 2M20 32c1.5 1.5 2.5 2 4 2s2.5-.5 4-2"/>
    </svg>
  );
}

// Spinner
function Spinner({ size = 56, color = 'var(--w-cream)' }) {
  return (
    <div style={{
      width: size, height: size, borderRadius: 999,
      border: `3px solid rgba(255,255,255,0.12)`,
      borderTopColor: color, borderRightColor: color,
      animation: 'w-spin 0.9s linear infinite',
    }}/>
  );
}

const btnLink = {
  background: 'none', border: 'none', color: 'var(--w-green)', fontWeight: 700,
  fontSize: 12, cursor: 'pointer', fontFamily: 'inherit'
};

function Block({ title, action, children }) {
  return (
    <div style={{
      background: '#fff', border: '1px solid rgba(23,25,25,0.06)', borderRadius: 18,
      padding: 16, marginTop: 12
    }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
        <div style={{ fontSize: 15, fontWeight: 800, letterSpacing: -0.2 }}>{title}</div>
        {action}
      </div>
      {children}
    </div>
  );
}

// ───────────────────────────────────────────────────────────────
// 10. TRACKING
// ───────────────────────────────────────────────────────────────
const TRACK_STAGES = [
  { id: 'placed',   label: 'Order placed',   sub: 'We got it.',           t: 0 },
  { id: 'cook',     label: 'Cooking',        sub: 'Pans on, heat up.',    t: 4 },
  { id: 'pack',     label: 'Packed',         sub: 'Sealed & rider-ready', t: 9 },
  { id: 'rider',   label: 'Rider on the way', sub: 'Heading to you',      t: 14 },
  { id: 'delivered', label: 'Delivered',      sub: 'Eat the vibe.',       t: 23 },
];

function TrackingScreen({ go, order, finishOrder }) {
  const [t, setT] = useStateC(0); // 0..23
  useEffectC(() => {
    const iv = setInterval(() => setT(x => Math.min(x + 1, 23)), 1400);
    return () => clearInterval(iv);
  }, []);
  const stageIdx = TRACK_STAGES.findIndex((s, i) => i === TRACK_STAGES.length - 1 || t < TRACK_STAGES[i + 1].t);
  const stage = TRACK_STAGES[stageIdx];
  const minsLeft = Math.max(0, 23 - t);
  const rider = W2_RIDERS[0];

  return (
    <div style={{ position: 'absolute', inset: 0, paddingTop: 50, boxSizing: 'border-box', background: 'var(--w-onyx)', display: 'flex', flexDirection: 'column' }}>
      {/* Map */}
      <div style={{ position: 'relative', flex: 1, minHeight: 320 }}>
        <Photo tone="green" tag="map · rider en route" height="100%" radius={0} stripes={true}/>
        {/* roads */}
        <svg width="100%" height="100%" style={{ position: 'absolute', inset: 0 }}>
          <path d="M30,360 Q140,300 220,330 T380,260 L380,82" stroke="rgba(249,242,232,0.22)" strokeWidth="22" fill="none" strokeLinecap="round"/>
          <path d="M30,360 Q140,300 220,330 T380,260 L380,82" stroke="rgba(249,242,232,0.45)" strokeWidth="2" strokeDasharray="6 8" fill="none"/>
          {/* origin */}
          <circle cx="40" cy="358" r="9" fill="#F9F2E8"/>
          <text x="56" y="362" fill="#F9F2E8" fontSize="11" fontWeight="700" fontFamily="inherit">W2GO Kitchen</text>
          {/* destination */}
          <circle cx="378" cy="82" r="9" fill="#F9F2E8"/>
          <text x="368" y="76" fill="#F9F2E8" fontSize="11" fontWeight="700" fontFamily="inherit" textAnchor="end">You · The Pearl</text>
        </svg>
        {/* rider position — interp along path */}
        {(() => {
          const p = Math.min(1, t / 23);
          const x = 40 + (378 - 40) * p;
          const y = 358 - (358 - 82) * (p ** 0.7);
          return (
            <div style={{
              position: 'absolute', left: x - 22, top: y - 22, width: 44, height: 44, borderRadius: 999,
              background: 'var(--w-cream)', color: 'var(--w-green)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '0 8px 20px rgba(0,0,0,0.35)', transition: 'left 1.2s linear, top 1.2s linear'
            }}>
              <Ic.Bike size={22}/>
            </div>
          );
        })()}
        {/* back */}
        <button onClick={() => go('home')} style={{
          position: 'absolute', top: 14, left: 14, width: 44, height: 44, borderRadius: 999,
          background: 'rgba(249,242,232,0.92)', backdropFilter: 'blur(10px)', border: 'none',
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: 'var(--w-onyx)'
        }}><Ic.Back size={20}/></button>
      </div>

      {/* Sheet */}
      <div style={{
        background: 'var(--w-cream)', borderRadius: '24px 24px 0 0', padding: '22px 20px 30px',
        boxShadow: '0 -12px 30px rgba(0,0,0,0.15)', marginTop: -22, position: 'relative', zIndex: 2,
        maxHeight: '60%', overflowY: 'auto'
      }}>
        <div style={{ width: 40, height: 4, background: 'rgba(23,25,25,0.15)', borderRadius: 4, margin: '0 auto 18px' }}/>

        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--w-green)', letterSpacing: 1.6 }}>ARRIVING IN</div>
            <div style={{ fontSize: 38, fontWeight: 800, letterSpacing: -1, lineHeight: 1 }}>{minsLeft} min</div>
            <div style={{ marginTop: 4, fontSize: 13, opacity: 0.6 }}>{stage.label} · {stage.sub}</div>
          </div>
          <button onClick={finishOrder} style={btnLink}>Skip ahead →</button>
        </div>

        {/* progress bar */}
        <div style={{ marginTop: 18, display: 'flex', gap: 6 }}>
          {TRACK_STAGES.map((s, i) => (
            <div key={s.id} style={{
              flex: 1, height: 5, borderRadius: 4,
              background: i <= stageIdx ? 'var(--w-green)' : 'rgba(23,25,25,0.12)',
              transition: 'background .3s'
            }}/>
          ))}
        </div>

        {/* timeline */}
        <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 12 }}>
          {TRACK_STAGES.map((s, i) => {
            const done = i < stageIdx;
            const live = i === stageIdx;
            return (
              <div key={s.id} style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                <div style={{
                  width: 22, height: 22, borderRadius: 999, flex: 'none',
                  background: done || live ? 'var(--w-green)' : 'rgba(23,25,25,0.1)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: 'var(--w-cream)', position: 'relative'
                }}>
                  {done ? <Ic.Check size={12} stroke={3}/> : null}
                  {live && <span style={{
                    position: 'absolute', inset: -4, borderRadius: 999, border: '2px solid var(--w-green)',
                    opacity: 0.4, animation: 'w-pulse 1.4s ease-in-out infinite'
                  }}/>}
                </div>
                <div style={{ flex: 1, fontSize: 13.5, fontWeight: live ? 800 : 600, color: live || done ? 'var(--w-onyx)' : 'rgba(23,25,25,0.45)' }}>
                  {s.label}
                </div>
                <div style={{ fontSize: 12, opacity: 0.55 }}>{i === stageIdx ? 'now' : (done ? '✓' : `${TRACK_STAGES[i].t} min`)}</div>
              </div>
            );
          })}
        </div>
        <style>{`@keyframes w-pulse { 0%{transform:scale(1);opacity:.6} 100%{transform:scale(1.6);opacity:0} }`}</style>

        {/* Rider card */}
        {stageIdx >= 3 && (
          <div style={{
            marginTop: 18, background: '#fff', borderRadius: 18, padding: 14,
            display: 'flex', gap: 12, alignItems: 'center', border: '1px solid rgba(23,25,25,0.06)'
          }}>
            <div style={{
              width: 50, height: 50, borderRadius: 999, background: 'var(--w-green)', color: 'var(--w-cream)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 16
            }}>{rider.name.slice(0, 1)}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 800 }}>{rider.name}</div>
              <div style={{ fontSize: 12, opacity: 0.65, display: 'flex', alignItems: 'center', gap: 6, marginTop: 2 }}>
                <Ic.Star size={12} style={{ color: '#C24A2C' }}/> {rider.rating} · {rider.vehicle}
              </div>
            </div>
            <button style={{
              width: 40, height: 40, borderRadius: 999, background: 'rgba(0,76,75,0.1)', color: 'var(--w-green)',
              border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer'
            }}><Ic.Phone size={18}/></button>
            <button style={{
              width: 40, height: 40, borderRadius: 999, background: 'var(--w-green)', color: 'var(--w-cream)',
              border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer'
            }}><Ic.Mail size={18}/></button>
          </div>
        )}

        {stageIdx === TRACK_STAGES.length - 1 && (
          <div style={{ marginTop: 18 }}>
            <Btn full onClick={finishOrder}>Rate your delivery</Btn>
          </div>
        )}
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────
// 11. RATE / ORDER DONE
// ───────────────────────────────────────────────────────────────
function RateScreen({ go, doneRating }) {
  const [stars, setStars] = useStateC(0);
  const [tags, setTags] = useStateC([]);
  const toggle = (t) => setTags(tags.includes(t) ? tags.filter(x => x !== t) : [...tags, t]);
  return (
    <div style={{ position: 'absolute', inset: 0, paddingTop: 50, boxSizing: 'border-box', background: 'var(--w-cream)', display: 'flex', flexDirection: 'column' }}>
      <TopBar title="" onBack={() => go('home')}/>
      <div style={{ flex: 1, padding: '8px 24px', display: 'flex', flexDirection: 'column' }}>
        <div style={{ fontSize: 11, letterSpacing: 1.8, fontWeight: 700, color: 'var(--w-green)' }}>DELIVERED · ENJOY</div>
        <div style={{ fontSize: 34, fontWeight: 800, letterSpacing: -0.8, lineHeight: 1.05, marginTop: 6 }}>
          How did<br/>that hit?
        </div>

        <div style={{ marginTop: 28, display: 'flex', justifyContent: 'center', gap: 10 }}>
          {[1,2,3,4,5].map(n => (
            <button key={n} onClick={() => setStars(n)} style={{
              background: 'none', border: 'none', cursor: 'pointer', padding: 4,
              color: n <= stars ? '#C24A2C' : 'rgba(23,25,25,0.15)',
              transform: n <= stars ? 'scale(1.05)' : 'scale(1)',
              transition: 'transform .15s'
            }}><Ic.Star size={48}/></button>
          ))}
        </div>
        <div style={{ textAlign: 'center', marginTop: 8, fontSize: 13, opacity: 0.6, minHeight: 18 }}>
          {stars === 0 ? 'Tap to rate.' : stars < 3 ? 'We can do better.' : stars < 5 ? 'Pretty solid.' : 'Crave Worthy.'}
        </div>

        <div style={{ marginTop: 28, fontSize: 14, fontWeight: 700 }}>What made it good?</div>
        <div style={{ marginTop: 10, display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          {['Tasted fresh', 'Hot on arrival', 'Sealed & tidy', 'Quick rider', 'Portion on point', 'Worth the price'].map(t => (
            <Chip key={t} active={tags.includes(t)} onClick={() => toggle(t)} kind={tags.includes(t) ? 'green' : 'default'}>{t}</Chip>
          ))}
        </div>

        <textarea placeholder="Anything to add for the kitchen?"
                  style={{
                    marginTop: 18, padding: '14px 14px', borderRadius: 14, fontSize: 13, minHeight: 80,
                    border: '1.5px solid rgba(23,25,25,0.08)', background: '#fff', outline: 'none',
                    fontFamily: 'inherit', resize: 'none', boxSizing: 'border-box'
                  }}/>

        <div style={{ marginTop: 'auto', display: 'flex', gap: 10, paddingTop: 14, paddingBottom: 14 }}>
          <Btn kind="ghost" onClick={doneRating}>Skip</Btn>
          <Btn full onClick={doneRating} disabled={stars === 0}>Send rating</Btn>
        </div>
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────
// 12. ORDERS LIST
// ───────────────────────────────────────────────────────────────
const MOCK_ORDERS = [
  { id: 'W2-08412', date: 'Today · 12:42',       items: 'Omakase 12, Dragon Roll, Iced Yuzu Lemonade',          total: 245, status: 'Delivered' },
  { id: 'W2-08193', date: 'Yesterday · 19:08',   items: 'Yuzu Salmon Poké, Matcha Oat Latte',                   total: 80,  status: 'Delivered' },
  { id: 'W2-08055', date: 'Tue 14 · 13:30',      items: 'Rainbow Roll, Tempura Prawns, Edamame',                total: 160, status: 'Delivered' },
  { id: 'W2-07982', date: 'Mon 13 · 20:15',      items: 'Spicy Salmon Maki, Beef Gyoza, Mochi Trio',            total: 132, status: 'Cancelled' },
];

function OrdersScreen({ go }) {
  return (
    <div style={{ position: 'absolute', inset: 0, paddingTop: 50, boxSizing: 'border-box', background: 'var(--w-cream)', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '14px 20px 6px' }}>
        <div style={{ fontSize: 28, fontWeight: 800, letterSpacing: -0.6 }}>Past orders</div>
        <div style={{ fontSize: 13, opacity: 0.6, marginTop: 2 }}>Reorder in two taps.</div>
      </div>
      <Scroll pad={120} style={{ padding: '12px 20px 0' }}>
        {MOCK_ORDERS.map((o, i) => (
          <div key={o.id} style={{
            background: '#fff', borderRadius: 18, border: '1px solid rgba(23,25,25,0.06)',
            padding: 14, marginBottom: 12
          }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
              <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
                <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: 1.4, color: 'var(--w-green)' }}>{o.id}</span>
                <span style={{
                  fontSize: 10, padding: '3px 8px', borderRadius: 4, letterSpacing: 1, fontWeight: 700,
                  background: o.status === 'Delivered' ? 'rgba(0,76,75,0.12)' : 'rgba(194,74,44,0.12)',
                  color: o.status === 'Delivered' ? 'var(--w-green)' : '#C24A2C'
                }}>{o.status.toUpperCase()}</span>
              </div>
              <span style={{ fontSize: 11, opacity: 0.55 }}>{o.date}</span>
            </div>
            <div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.4, textWrap: 'pretty', color: 'var(--w-onyx)' }}>{o.items}</div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 12 }}>
              <span style={{ fontSize: 14, fontWeight: 800, color: 'var(--w-green)' }}>{W2_money(o.total)}</span>
              <div style={{ display: 'flex', gap: 8 }}>
                <Btn size="sm" kind="ghost">View</Btn>
                <Btn size="sm" onClick={() => go('home')}>Reorder</Btn>
              </div>
            </div>
          </div>
        ))}
      </Scroll>
    </div>
  );
}

// ───────────────────────────────────────────────────────────────
// 13. ACCOUNT
// ───────────────────────────────────────────────────────────────
function AccountScreen({ go, user, signOut }) {
  const M = window.W2_MEMBER || {};
  const name = user?.name || M.name || 'Friend';
  const perks = M.perks || [];
  return (
    <div style={{ position: 'absolute', inset: 0, paddingTop: 50, boxSizing: 'border-box', background: 'var(--w-cream)', display: 'flex', flexDirection: 'column' }}>
      <Scroll pad={120}>
        {/* Profile hero */}
        <div style={{ position: 'relative', background: 'var(--w-onyx)', color: 'var(--w-cream)', padding: '24px 20px 64px', borderRadius: '0 0 24px 24px', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', inset: 0, background: 'radial-gradient(110% 90% at 90% 0%, rgba(201,162,75,0.30), transparent 55%)' }}/>
          <div style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{
              width: 64, height: 64, borderRadius: 999, background: 'var(--w-green)', color: 'var(--w-cream)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 800, fontSize: 26,
              border: '2px solid rgba(201,162,75,0.5)'
            }}>{name.slice(0, 1).toUpperCase()}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: -0.4 }}>{name}</div>
                <span style={{ fontSize: 9, letterSpacing: 1.2, fontWeight: 800, padding: '3px 8px', borderRadius: 5,
                               background: 'linear-gradient(135deg, #C9A24B, #9c7a2e)', color: '#fff', textTransform: 'uppercase' }}>
                  {M.tier || 'Gold'} member
                </span>
              </div>
              <div style={{ fontSize: 12.5, opacity: 0.6, marginTop: 2 }}>{user?.phone || M.phone}</div>
            </div>
            <button style={{
              padding: '8px 14px', borderRadius: 999, background: 'rgba(255,255,255,0.1)', border: '1px solid rgba(255,255,255,0.18)',
              color: 'var(--w-cream)', fontFamily: 'inherit', fontWeight: 600, fontSize: 12, cursor: 'pointer'
            }}>Edit</button>
          </div>
          <div style={{
            position: 'relative', marginTop: 18, display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10,
          }}>
            {[
              { l: 'Orders',      v: String(M.orders || 24), sub: 'all time' },
              { l: 'Saved',       v: String(M.saved || 8),   sub: 'favorites' },
              { l: 'Vibe Points', v: (M.points || 2480).toLocaleString(), sub: `${M.pointsToNext || 520} to ${M.nextTier || 'Platinum'}` },
            ].map(s => (
              <div key={s.l} style={{
                background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.08)',
                borderRadius: 14, padding: '12px 10px',
              }}>
                <div style={{ fontSize: 10, opacity: 0.6, letterSpacing: 1.2, fontWeight: 700 }}>{s.l.toUpperCase()}</div>
                <div style={{ fontSize: 21, fontWeight: 800, letterSpacing: -0.5, marginTop: 4 }}>{s.v}</div>
                <div style={{ fontSize: 9.5, opacity: 0.55, marginTop: 2 }}>{s.sub}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Membership card — perks (Soho House exclusivity) */}
        <div style={{ margin: '-44px 20px 0', background: '#fff', borderRadius: 20, border: '1px solid rgba(23,25,25,0.06)',
                      padding: 16, boxShadow: '0 16px 34px -20px rgba(23,25,25,0.25)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4 }}>
            <div style={{ fontSize: 14, fontWeight: 800, letterSpacing: -0.2 }}>Your {M.tier || 'Gold'} perks</div>
            <span style={{ fontSize: 11, opacity: 0.5, fontWeight: 600 }}>Member since {M.memberSince || '2024'}</span>
          </div>
          <div style={{ marginTop: 10, marginBottom: 4, height: 6, borderRadius: 4, background: 'rgba(23,25,25,0.08)', overflow: 'hidden' }}>
            <div style={{ width: `${(M.tierProgress || 0.82) * 100}%`, height: '100%', background: 'linear-gradient(90deg, #C9A24B, #e3c578)' }}/>
          </div>
          <div style={{ fontSize: 11.5, opacity: 0.6, fontWeight: 600, marginBottom: 12 }}>
            {M.pointsToNext || 520} points to {M.nextTier || 'Platinum'}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {perks.map((p, i) => {
              const I = Ic[p.icon] || Ic.Spark;
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div style={{ width: 34, height: 34, borderRadius: 10, background: 'rgba(201,162,75,0.14)',
                                color: '#9c7a2e', display: 'flex', alignItems: 'center', justifyContent: 'center', flex: 'none' }}>
                    <I size={17}/>
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 700, color: 'var(--w-onyx)' }}>{p.label}</div>
                    <div style={{ fontSize: 11.5, opacity: 0.55 }}>{p.sub}</div>
                  </div>
                  <Ic.Check size={16} style={{ color: 'var(--w-green)' }}/>
                </div>
              );
            })}
          </div>
        </div>

        {/* Menu rows */}
        <div style={{ margin: '18px 20px 0', background: '#fff', borderRadius: 20, border: '1px solid rgba(23,25,25,0.06)', overflow: 'hidden' }}>
          {[
            { l: 'Addresses', i: Ic.Pin, cb: () => go('location') },
            { l: 'Payment methods', i: Ic.Card, cb: () => null },
            { l: 'Order history', i: Ic.Receipt, cb: () => go('orders') },
            { l: 'Favorites', i: Ic.Heart, cb: () => null },
            { l: 'Notifications', i: Ic.Bell, cb: () => null },
            { l: 'Help & Support', i: Ic.Spark, cb: () => null },
          ].map((r, i, arr) => {
            const I = r.i;
            return (
              <button key={r.l} onClick={r.cb} style={{
                width: '100%', padding: '16px 16px', display: 'flex', alignItems: 'center', gap: 14,
                background: 'transparent', border: 'none', borderBottom: i < arr.length - 1 ? '1px solid rgba(23,25,25,0.06)' : 'none',
                cursor: 'pointer', fontFamily: 'inherit', textAlign: 'left'
              }}>
                <div style={{
                  width: 36, height: 36, borderRadius: 10, background: 'rgba(0,76,75,0.08)',
                  color: 'var(--w-green)', display: 'flex', alignItems: 'center', justifyContent: 'center'
                }}><I size={18}/></div>
                <div style={{ flex: 1, fontSize: 14, fontWeight: 700, color: 'var(--w-onyx)' }}>{r.l}</div>
                <Ic.ChevronR size={18} style={{ opacity: 0.4 }}/>
              </button>
            );
          })}
        </div>

        <div style={{ padding: '20px 20px 0' }}>
          <Btn full kind="ghost" onClick={signOut}>Sign out</Btn>
        </div>

        <div style={{ textAlign: 'center', padding: '24px 0 8px', fontSize: 10, letterSpacing: 2, opacity: 0.45, fontWeight: 700 }}>
          W2GO · CRAFTED BY W DOHA · v1.0
        </div>
      </Scroll>
    </div>
  );
}

Object.assign(window, { CheckoutScreen, PaymentScreen, TrackingScreen, RateScreen, OrdersScreen, AccountScreen });
