/* OrderFlow — standalone screens for menu picking, pickup, confirm, ready. */

const PICKUP_SLOTS = [
  { time: '12:18 PM', mins: 4,  label: 'In 4 min',   ready: true,  badge: 'Soonest' },
  { time: '12:24 PM', mins: 10, label: 'In 10 min',  ready: true },
  { time: '12:30 PM', mins: 16, label: 'In 16 min',  ready: true },
  { time: '12:36 PM', mins: 22, label: 'In 22 min',  ready: true },
  { time: '12:45 PM', mins: 31, label: 'In 31 min',  ready: true },
  { time: '12:55 PM', mins: 41, label: 'In 41 min',  ready: true },
  { time: '1:05 PM',  mins: 51, label: 'In 51 min',  ready: false, badge: 'Likely sold out' },
];

function OrderHeader({ title, onBack, dark, step, total }) {
  return (
    <div style={{
      position: 'sticky', top: 0, zIndex: 5,
      background: dark ? 'rgba(15,13,10,0.92)' : 'rgba(245,243,238,0.92)',
      backdropFilter: 'blur(20px) saturate(180%)',
      WebkitBackdropFilter: 'blur(20px) saturate(180%)',
      borderBottom: dark ? '0.5px solid rgba(255,255,255,0.06)' : '0.5px solid rgba(31,27,22,0.06)',
      paddingTop: 56,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', padding: '12px 16px 14px', gap: 14 }}>
        <button onClick={onBack} style={{
          width: 36, height: 36, borderRadius: 18,
          border: 'none', cursor: 'pointer',
          background: dark ? 'rgba(255,255,255,0.08)' : 'rgba(31,27,22,0.06)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--ink)',
        }}>
          <Ic.Chevron s={16} c="var(--ink)" r={180}/>
        </button>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontFamily: 'var(--font-mono)', fontSize: 10,
            letterSpacing: '0.16em', textTransform: 'uppercase',
            color: 'var(--ink-3)',
          }}>Step {step} of {total}</div>
          <div style={{
            fontFamily: 'var(--font-display)',
            fontSize: 22, lineHeight: 1.05, letterSpacing: '-0.005em',
            color: 'var(--ink)',
          }}>{title}</div>
        </div>
      </div>
      {/* Progress dots */}
      <div style={{ display: 'flex', gap: 4, padding: '0 16px 12px' }}>
        {Array.from({ length: total }, (_, i) => (
          <div key={i} style={{
            flex: 1, height: 3, borderRadius: 999,
            background: i < step
              ? 'var(--ink)'
              : (dark ? 'rgba(255,255,255,0.10)' : 'rgba(31,27,22,0.10)'),
            transition: 'background 220ms ease',
          }}/>
        ))}
      </div>
    </div>
  );
}

/* ─── 1. Item picker ─── */
function OrderItemPicker({ vendor: v, cart, setCart, onBack, onNext, dark }) {
  const liveTicket = useTickingMinute(v.ticket || 7);
  const cartCount = Object.values(cart).reduce((a, b) => a + b, 0);
  const cartTotal = (v.menu || []).reduce((sum, m) => sum + (cart[m.name] || 0) * m.price, 0);
  return (
    <div style={{ position: 'absolute', inset: 0, background: dark ? '#0F0D0A' : 'var(--cream)', overflow: 'auto', zIndex: 70 }} className="no-scrollbar">
      <OrderHeader title={`Today at ${v.name}`} onBack={onBack} dark={dark} step={1} total={4}/>
      <div style={{ padding: '16px 16px 140px' }}>
        <div style={{
          display: 'flex', gap: 6, marginBottom: 14, flexWrap: 'wrap',
        }}>
          <OpChip tone="good" icon={<Ic.Check s={11}/>} label="Accepting orders" />
          <OpChip tone="default" icon={<Ic.Clock s={11}/>} label="Ticket" value={bucketTicketCompact(liveTicket)} />
          <OpChip tone="default" icon={<Ic.Pin s={11}/>} label="On-site" />
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {(v.menu || []).map((item) => (
            <MenuItem
              key={item.name}
              item={item}
              count={cart[item.name] || 0}
              onAdd={() => setCart(c => ({ ...c, [item.name]: (c[item.name] || 0) + 1 }))}
              onRemove={() => setCart(c => {
                const n = { ...c, [item.name]: Math.max(0, (c[item.name] || 0) - 1) };
                if (n[item.name] === 0) delete n[item.name];
                return n;
              })}
              dark={dark}
            />
          ))}
        </div>
      </div>
      {/* Sticky CTA */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        padding: '12px 16px 32px',
        background: dark
          ? 'linear-gradient(180deg, rgba(15,13,10,0) 0%, rgba(15,13,10,0.95) 30%, rgba(15,13,10,1) 100%)'
          : 'linear-gradient(180deg, rgba(245,243,238,0) 0%, rgba(245,243,238,0.96) 30%, rgba(245,243,238,1) 100%)',
      }}>
        <button
          disabled={cartCount === 0}
          onClick={onNext}
          style={{
            width: '100%', height: 56, borderRadius: 18,
            border: 'none', cursor: cartCount > 0 ? 'pointer' : 'not-allowed',
            background: cartCount > 0 ? 'var(--ink)' : (dark ? 'rgba(255,255,255,0.10)' : 'rgba(31,27,22,0.12)'),
            color: cartCount > 0 ? 'var(--cream)' : 'var(--ink-3)',
            fontFamily: 'var(--font-body)', fontSize: 16, fontWeight: 600,
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            padding: '0 18px 0 22px',
            boxShadow: cartCount > 0 ? '0 6px 18px rgba(31,27,22,0.20)' : 'none',
          }}
        >
          <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <Ic.Bag s={16} c={cartCount > 0 ? 'var(--cream)' : 'var(--ink-3)'} />
            {cartCount > 0 ? `Continue · ${cartCount} item${cartCount > 1 ? 's' : ''}` : 'Add an item to continue'}
          </span>
          <span style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            {cartCount > 0 && <span className="mono" style={{ fontSize: 14 }}>${cartTotal.toFixed(2)}</span>}
            {cartCount > 0 && <span style={{
              fontFamily: 'var(--font-mono)', fontSize: 11.5,
              background: 'rgba(255,253,248,0.14)', padding: '4px 8px', borderRadius: 999,
            }}>{bucketTicketCompact(liveTicket)}</span>}
          </span>
        </button>
      </div>
    </div>
  );
}

/* ─── 2. Pickup window ─── */
function OrderPickup({ vendor: v, slot, setSlot, onBack, onNext, dark }) {
  return (
    <div style={{ position: 'absolute', inset: 0, background: dark ? '#0F0D0A' : 'var(--cream)', overflow: 'auto', zIndex: 70 }} className="no-scrollbar">
      <OrderHeader title="Pick a window" onBack={onBack} dark={dark} step={2} total={4}/>
      <div style={{ padding: '4px 16px 8px', fontSize: 13, color: 'var(--ink-3)' }}>
        Live windows from {v.name}. Times update with ticket throughput.
      </div>
      <div style={{ padding: '12px 16px 140px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {PICKUP_SLOTS.map((s, i) => {
          const active = slot === s.time;
          return (
            <button
              key={s.time}
              disabled={!s.ready}
              onClick={() => setSlot(s.time)}
              style={{
                display: 'flex', alignItems: 'center', gap: 14,
                padding: '14px 16px',
                borderRadius: 16,
                border: 'none', textAlign: 'left',
                cursor: s.ready ? 'pointer' : 'not-allowed',
                background: active
                  ? 'var(--ink)'
                  : (dark ? 'rgba(255,255,255,0.04)' : '#fff'),
                color: active ? 'var(--cream)' : 'var(--ink)',
                opacity: s.ready ? 1 : 0.5,
                boxShadow: active ? '0 6px 18px rgba(31,27,22,0.18)' : (dark ? '0 0 0 0.5px rgba(255,255,255,0.07)' : '0 0 0 0.5px rgba(31,27,22,0.06)'),
                transition: 'background 160ms, color 160ms',
              }}
            >
              <div style={{
                width: 44, height: 44, borderRadius: 12,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                background: active ? 'rgba(255,253,248,0.12)' : (dark ? 'rgba(255,255,255,0.05)' : 'rgba(31,27,22,0.04)'),
                flexShrink: 0,
              }}>
                <Ic.Clock s={18} c={active ? 'var(--cream)' : 'var(--ink-2)'} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, lineHeight: 1.0, letterSpacing: '-0.005em' }}>{s.time}</div>
                <div style={{ fontSize: 12.5, color: active ? 'rgba(245,243,238,0.7)' : 'var(--ink-3)', marginTop: 3 }}>
                  {s.label}
                  {s.badge && <span style={{
                    marginLeft: 8,
                    fontFamily: 'var(--font-mono)', fontSize: 10,
                    letterSpacing: '0.08em', textTransform: 'uppercase',
                    color: active ? 'rgba(245,243,238,0.7)' : (s.ready ? 'var(--accent)' : '#9B7220'),
                  }}>· {s.badge}</span>}
                </div>
              </div>
              {active && <Ic.Check s={18} c="var(--cream)"/>}
            </button>
          );
        })}
      </div>
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        padding: '12px 16px 32px',
        background: dark
          ? 'linear-gradient(180deg, rgba(15,13,10,0) 0%, rgba(15,13,10,0.95) 30%, rgba(15,13,10,1) 100%)'
          : 'linear-gradient(180deg, rgba(245,243,238,0) 0%, rgba(245,243,238,0.96) 30%, rgba(245,243,238,1) 100%)',
      }}>
        <button
          disabled={!slot}
          onClick={onNext}
          style={{
            width: '100%', height: 56, borderRadius: 18, border: 'none',
            cursor: slot ? 'pointer' : 'not-allowed',
            background: slot ? 'var(--ink)' : (dark ? 'rgba(255,255,255,0.10)' : 'rgba(31,27,22,0.12)'),
            color: slot ? 'var(--cream)' : 'var(--ink-3)',
            fontFamily: 'var(--font-body)', fontSize: 16, fontWeight: 600,
            boxShadow: slot ? '0 6px 18px rgba(31,27,22,0.20)' : 'none',
          }}
        >{slot ? `Confirm pickup at ${slot}` : 'Pick a time to continue'}</button>
      </div>
    </div>
  );
}

/* ─── 3. Confirm ─── */
function OrderConfirm({ vendor: v, cart, slot, onBack, onPlace, dark }) {
  const items = (v.menu || []).filter(m => cart[m.name] > 0);
  const subtotal = items.reduce((s, m) => s + cart[m.name] * m.price, 0);
  const tax = subtotal * 0.0875;
  const total = subtotal + tax;
  return (
    <div style={{ position: 'absolute', inset: 0, background: dark ? '#0F0D0A' : 'var(--cream)', overflow: 'auto', zIndex: 70 }} className="no-scrollbar">
      <OrderHeader title="Review order" onBack={onBack} dark={dark} step={3} total={4}/>
      <div style={{ padding: '14px 16px 140px', display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* Vendor strip */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '12px 14px', borderRadius: 16,
          background: dark ? 'rgba(255,255,255,0.04)' : '#fff',
          border: dark ? '0.5px solid rgba(255,255,255,0.07)' : '0.5px solid rgba(31,27,22,0.06)',
        }}>
          <div style={{
            width: 44, height: 44, borderRadius: 12,
            background: v.blockTone, flexShrink: 0,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'rgba(255,253,248,0.92)', fontFamily: 'var(--font-display)',
            fontSize: 16, fontStyle: 'italic',
          }}>{v.name.split(' ').map(w => w[0]).join('').slice(0,2)}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, lineHeight: 1.05, color: 'var(--ink)' }}>{v.name}</div>
            <div style={{ fontSize: 12.5, color: 'var(--ink-3)' }}>{v.kind} · {v.neighborhood}</div>
          </div>
        </div>

        {/* Items */}
        <div style={{
          background: dark ? 'rgba(255,255,255,0.04)' : '#fff', borderRadius: 16,
          border: dark ? '0.5px solid rgba(255,255,255,0.07)' : '0.5px solid rgba(31,27,22,0.06)',
          overflow: 'hidden',
        }}>
          {items.map((m, i) => (
            <div key={m.name} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '12px 14px',
              borderTop: i > 0 ? (dark ? '0.5px solid rgba(255,255,255,0.06)' : '0.5px solid rgba(31,27,22,0.06)') : 'none',
            }}>
              <div className="mono" style={{ width: 22, color: 'var(--ink-3)', fontSize: 13 }}>{cart[m.name]}×</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{m.name}</div>
                {m.desc && <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{m.desc}</div>}
              </div>
              <div className="mono" style={{ fontSize: 13, color: 'var(--ink-2)' }}>${(m.price * cart[m.name]).toFixed(2)}</div>
            </div>
          ))}
        </div>

        {/* Pickup slot card */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '12px 14px', borderRadius: 16,
          background: dark ? 'rgba(255,255,255,0.04)' : '#fff',
          border: dark ? '0.5px solid rgba(255,255,255,0.07)' : '0.5px solid rgba(31,27,22,0.06)',
        }}>
          <div style={{
            width: 44, height: 44, borderRadius: 12,
            background: dark ? 'rgba(217,83,30,0.18)' : 'rgba(217,83,30,0.10)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
          }}>
            <Ic.Clock s={18} c="var(--accent)"/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{
              fontFamily: 'var(--font-mono)', fontSize: 10,
              letterSpacing: '0.16em', textTransform: 'uppercase',
              color: 'var(--ink-3)',
            }}>Pickup window</div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, color: 'var(--ink)' }}>{slot || '—'}</div>
          </div>
        </div>

        {/* Payment */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          padding: '12px 14px', borderRadius: 16,
          background: dark ? 'rgba(255,255,255,0.04)' : '#fff',
          border: dark ? '0.5px solid rgba(255,255,255,0.07)' : '0.5px solid rgba(31,27,22,0.06)',
        }}>
          <div style={{
            width: 44, height: 28, borderRadius: 5,
            background: 'linear-gradient(135deg, #1F1B16 0%, #3A332B 100%)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
            fontFamily: 'var(--font-mono)', fontSize: 8.5, fontWeight: 600,
            color: '#E8B04C', letterSpacing: '0.12em',
          }}>VISA</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>Card on file</div>
            <div className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>•••• 4242</div>
          </div>
          <Ic.Chevron s={14} c="var(--ink-4)"/>
        </div>

        {/* Totals */}
        <div style={{
          padding: '14px 16px', borderRadius: 16,
          background: dark ? 'rgba(255,255,255,0.03)' : 'rgba(31,27,22,0.03)',
          fontSize: 14, color: 'var(--ink-2)',
        }}>
          <Row label="Subtotal" value={`$${subtotal.toFixed(2)}`} />
          <Row label="Tax" value={`$${tax.toFixed(2)}`} muted />
          <div style={{ height: 1, background: dark ? 'rgba(255,255,255,0.08)' : 'rgba(31,27,22,0.08)', margin: '10px 0' }}/>
          <Row label="Total" value={`$${total.toFixed(2)}`} bold />
        </div>
      </div>
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 0,
        padding: '12px 16px 32px',
        background: dark
          ? 'linear-gradient(180deg, rgba(15,13,10,0) 0%, rgba(15,13,10,0.95) 30%, rgba(15,13,10,1) 100%)'
          : 'linear-gradient(180deg, rgba(245,243,238,0) 0%, rgba(245,243,238,0.96) 30%, rgba(245,243,238,1) 100%)',
      }}>
        <button onClick={onPlace} style={{
          width: '100%', height: 56, borderRadius: 18, border: 'none', cursor: 'pointer',
          background: 'var(--accent)', color: 'var(--cream)',
          fontFamily: 'var(--font-body)', fontSize: 16, fontWeight: 600,
          boxShadow: '0 6px 18px rgba(217,83,30,0.30)',
          letterSpacing: '-0.005em',
        }}>Place order · ${total.toFixed(2)}</button>
        <div style={{
          marginTop: 8, textAlign: 'center',
          fontFamily: 'var(--font-mono)', fontSize: 10.5,
          letterSpacing: '0.10em', textTransform: 'uppercase',
          color: 'var(--ink-4)',
        }}>You'll get a ping when it's ready</div>
      </div>
    </div>
  );
}

function Row({ label, value, bold, muted }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0' }}>
      <span style={{ color: muted ? 'var(--ink-3)' : 'var(--ink-2)', fontWeight: bold ? 600 : 400 }}>{label}</span>
      <span className="mono" style={{ color: muted ? 'var(--ink-3)' : 'var(--ink)', fontWeight: bold ? 600 : 400 }}>{value}</span>
    </div>
  );
}

/* ─── 4. Ready notification ─── */
function OrderReady({ vendor: v, slot, cart, onClose, onMap, dark, preset, reducedMotion, intensity }) {
  // Fake ticking ETA
  const [secs, setSecs] = React.useState(7 * 60 + 12);
  React.useEffect(() => {
    const id = setInterval(() => setSecs(s => Math.max(0, s - 1)), 1000);
    return () => clearInterval(id);
  }, []);
  const mm = Math.floor(secs / 60);
  const ss = (secs % 60).toString().padStart(2, '0');
  const totalItems = Object.values(cart).reduce((a, b) => a + b, 0);

  return (
    <div style={{ position: 'absolute', inset: 0, background: dark ? '#0F0D0A' : 'var(--cream)', overflow: 'auto', zIndex: 70 }} className="no-scrollbar">
      <OrderHeader title="On the fire" onBack={onClose} dark={dark} step={4} total={4}/>

      <div style={{ padding: '32px 16px 32px', textAlign: 'center' }}>
        <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 18 }}>
          <Halo tier={4} size={156} preset={preset} reducedMotion={reducedMotion} intensity={intensity} accepting={true}/>
        </div>
        <div style={{
          fontFamily: 'var(--font-mono)', fontSize: 10.5,
          letterSpacing: '0.18em', textTransform: 'uppercase',
          color: 'var(--ink-3)', marginBottom: 6,
        }}>Order placed · {v.name}</div>
        <h1 style={{
          margin: 0,
          fontFamily: 'var(--font-display)',
          fontSize: 44, fontWeight: 400,
          letterSpacing: '-0.015em', color: 'var(--ink)',
          lineHeight: 1.0,
        }}>{mm < 3 ? <span className="serif-i">Almost ready</span> : <>Ready in <span className="serif-i">{bucketTicketLong(mm)}</span></>}</h1>
        <div style={{ fontSize: 14, color: 'var(--ink-3)', marginTop: 10, maxWidth: 280, marginLeft: 'auto', marginRight: 'auto' }}>
          Pickup at <span style={{ color: 'var(--ink-2)', fontWeight: 600 }}>{slot}</span>. We'll ping you when {totalItems > 1 ? 'they hit' : 'it hits'} the window.
        </div>
      </div>

      {/* Live status track */}
      <div style={{ padding: '0 16px 16px' }}>
        <div style={{
          padding: '14px 16px', borderRadius: 16,
          background: dark ? 'rgba(255,255,255,0.04)' : '#fff',
          border: dark ? '0.5px solid rgba(255,255,255,0.07)' : '0.5px solid rgba(31,27,22,0.06)',
        }}>
          {[
            { label: 'Order received',     done: true,  when: 'now' },
            { label: 'Accepted by kitchen', done: true,  when: '12s ago' },
            { label: 'On the grill',        done: secs < 6*60, when: secs < 6*60 ? 'live' : '—' },
            { label: 'Ready for pickup',    done: secs === 0, when: secs === 0 ? 'now' : `~${mm}:${ss}` },
          ].map((row, i, arr) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 14,
              padding: '8px 0',
              borderTop: i > 0 ? (dark ? '0.5px solid rgba(255,255,255,0.05)' : '0.5px solid rgba(31,27,22,0.05)') : 'none',
            }}>
              <div style={{
                width: 20, height: 20, borderRadius: 10,
                background: row.done ? 'var(--accent)' : (dark ? 'rgba(255,255,255,0.08)' : 'rgba(31,27,22,0.08)'),
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                flexShrink: 0,
              }}>
                {row.done && <Ic.Check s={11} c="var(--cream)"/>}
              </div>
              <div style={{ flex: 1, fontSize: 14, color: row.done ? 'var(--ink)' : 'var(--ink-3)', fontWeight: row.done ? 500 : 400 }}>{row.label}</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{row.when}</div>
            </div>
          ))}
        </div>

        <div style={{
          marginTop: 10, padding: '10px 14px', borderRadius: 14,
          background: dark ? 'rgba(232,176,76,0.10)' : 'rgba(232,176,76,0.16)',
          color: dark ? '#E8B04C' : '#9B7220', fontSize: 12.5,
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <Ic.Bell s={14} c="currentColor"/>
          Push notifications on. We'll only ping when there's news.
        </div>
      </div>

      {/* Footer actions */}
      <div style={{ padding: '8px 16px 32px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <button onClick={onMap} style={{
          width: '100%', height: 52, borderRadius: 16, border: 'none', cursor: 'pointer',
          background: 'var(--ink)', color: 'var(--cream)',
          fontFamily: 'var(--font-body)', fontSize: 15, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <Ic.Pin s={14} c="var(--cream)"/>
          See on map · {v.walkMin} min walk
        </button>
        <button onClick={onClose} style={{
          width: '100%', height: 44, borderRadius: 14, border: 'none', cursor: 'pointer',
          background: 'transparent', color: 'var(--ink-2)',
          fontSize: 13.5, fontWeight: 500,
        }}>Back to {v.name}</button>
      </div>
    </div>
  );
}

window.OrderItemPicker = OrderItemPicker;
window.OrderPickup = OrderPickup;
window.OrderConfirm = OrderConfirm;
window.OrderReady = OrderReady;
