// Checkout, Tracking, Pantry screens.

/* ============================================
   CHECKOUT
   ============================================ */
const Checkout = ({ basket, quantities, onPlace, onBack }) => {
  const [slot, setSlot] = useS('thu-6');
  const [pay, setPay] = useS('apple');
  const items = Array.from(basket).map((id) => ({ p: BLYZR.productById[id], q: quantities[id] || 1 }));
  const subtotal = items.reduce((s, { p, q }) => s + p.price * q, 0);

  const slots = [
    { id: 'thu-3', day: 'Thu', when: '3–4pm',   price: 2.50, label: 'today' },
    { id: 'thu-6', day: 'Thu', when: '6–7pm',   price: 0,    label: 'free · today' },
    { id: 'thu-9', day: 'Thu', when: '9–10pm',  price: 1.50, label: 'late' },
    { id: 'fri-8', day: 'Fri', when: '8–9am',   price: 2.00, label: 'tomorrow' },
  ];

  return (
    <>
      <CanvasHeader
        crumb="05 — checkout"
        title="Almost <em>at the door.</em>"
        subtitle="Choose a slot and confirm — Blyzr handles the rest."
      />

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 28 }}>
        <div className="col gap-6">
          <section>
            <div className="sec-head"><h3>Delivery</h3><span className="meta">postcode · E8 4PB · same-day</span></div>
            <div className="grid-2" style={{ gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
              {slots.map((s) => (
                <button key={s.id} className={`slot ${slot === s.id ? 'selected' : ''}`} onClick={() => setSlot(s.id)}>
                  <div className="span">{s.day} · {s.label}</div>
                  <div className="when">{s.when}</div>
                  <div className="price">{s.price === 0 ? 'Free' : `$${s.price.toFixed(2)}`}</div>
                </button>
              ))}
            </div>
          </section>

          <section>
            <div className="sec-head"><h3>Address</h3><span className="meta">default</span></div>
            <div style={{ background: 'var(--bg)', border: '1px solid var(--border-soft)', borderRadius: 'var(--r-md)', padding: 18, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ fontSize: 14, marginBottom: 2 }}>Maya Okafor</div>
                <div className="muted" style={{ fontSize: 13 }}>Flat 4B, 27 Mare Street · London E8 4PB</div>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-4)', marginTop: 8 }}>leave with concierge if out</div>
              </div>
              <button className="btn btn-outline">Change</button>
            </div>
          </section>

          <section>
            <div className="sec-head"><h3>Payment</h3><span className="meta">encrypted</span></div>
            <div className="col gap-2">
              {[
                { id: 'apple', label: 'Apple Pay', sub: 'tap to confirm with Face ID' },
                { id: 'card',  label: 'Visa · 4242', sub: 'expires 02/29 · saved' },
                { id: 'blzr',  label: 'Blyzr+ credit', sub: 'balance $18.50' },
              ].map((m) => (
                <button key={m.id} className={`slot ${pay === m.id ? 'selected' : ''}`} onClick={() => setPay(m.id)} style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
                  <div>
                    <div style={{ fontSize: 14, marginBottom: 2 }}>{m.label}</div>
                    <div className="muted" style={{ fontSize: 12 }}>{m.sub}</div>
                  </div>
                  <div style={{ width: 16, height: 16, borderRadius: '50%', border: '1.5px solid var(--border-strong)', display: 'grid', placeItems: 'center' }}>
                    {pay === m.id && <div style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--accent)' }}/>}
                  </div>
                </button>
              ))}
            </div>
          </section>
        </div>

        <div>
          <div className="totals" style={{ position: 'sticky', top: 20 }}>
            <div className="eyebrow" style={{ marginBottom: 14 }}>Order · {items.length} items</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, paddingBottom: 14, borderBottom: '1px solid var(--border)' }}>
              {items.slice(0, 5).map(({ p, q }) => (
                <div key={p.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: 'var(--ink-2)' }}>
                  <span>{q}× {p.name}</span>
                  <span className="mono">${(p.price * q).toFixed(2)}</span>
                </div>
              ))}
              {items.length > 5 && <div className="muted mono" style={{ fontSize: 11, letterSpacing: '0.1em' }}>+ {items.length - 5} more</div>}
            </div>
            <div className="totals-line" style={{ paddingTop: 12 }}><span>Subtotal</span><span className="v">${subtotal.toFixed(2)}</span></div>
            <div className="totals-line"><span>Delivery</span><span className="v">{slots.find((s) => s.id === slot).price === 0 ? 'Free' : `$${slots.find((s) => s.id === slot).price.toFixed(2)}`}</span></div>
            <div className="totals-line total"><span>Pay now</span><span className="v">${(subtotal + slots.find((s) => s.id === slot).price).toFixed(2)}</span></div>

            <button className="btn btn-accent btn-lg" style={{ width: '100%', justifyContent: 'center', marginTop: 18 }} onClick={onPlace}>
              Place order with Face ID
            </button>
            <button className="btn btn-ghost" style={{ marginTop: 6, width: '100%', justifyContent: 'center' }} onClick={onBack}>
              Back to basket
            </button>
          </div>
        </div>
      </div>
    </>
  );
};

/* ============================================
   ORDER TRACKING
   ============================================ */
const Tracking = ({ onSend }) => {
  const [eta, setEta] = useS(7);

  useE(() => {
    const i = setInterval(() => setEta((e) => Math.max(1, e - 1)), 4000);
    return () => clearInterval(i);
  }, []);

  const steps = [
    { time: '14:32', label: 'Order placed', sub: 'Payment confirmed · Apple Pay', state: 'done' },
    { time: '14:34', label: 'Picking', sub: 'Sam at the Hackney hub', state: 'done' },
    { time: '14:51', label: 'Cold bag sealed', sub: '4°C — burrata, milk', state: 'done' },
    { time: '15:08', label: 'En route to E8 4PB', sub: `${eta} min away`, state: 'current' },
    { time: '—',     label: 'Handover', sub: 'Tap to unlock when Sam arrives', state: 'next' },
  ];

  return (
    <>
      <CanvasHeader
        crumb="06 — on the way"
        title={`Sam is <em>${eta} minutes</em> out.`}
        subtitle="Order #BLZ-49-2A48 · burrata is behaving."
        right={(
          <div className="col gap-2" style={{ alignItems: 'flex-end' }}>
            <div className="mono" style={{ fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>est. arrival</div>
            <div style={{ fontFamily: 'var(--f-display)', fontStyle: 'italic', fontSize: 26 }}>15:{(8 + eta).toString().padStart(2, '0')}</div>
          </div>
        )}
      />

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 28, alignItems: 'start' }}>
        <div>
          {/* Map */}
          <div className="delivery-map">
            <div className="grid-overlay"/>
            <svg className="route" viewBox="0 0 600 220" preserveAspectRatio="none">
              <defs>
                <linearGradient id="rg" x1="0" x2="1">
                  <stop offset="0" stopColor="oklch(0.85 0.22 135)" stopOpacity="0"/>
                  <stop offset="0.5" stopColor="oklch(0.78 0.22 135)" stopOpacity="0.9"/>
                  <stop offset="1" stopColor="oklch(0.78 0.22 135)"/>
                </linearGradient>
              </defs>
              <path d="M 60 170 Q 180 180, 240 130 T 380 90 Q 460 70, 540 50" stroke="url(#rg)" strokeWidth="3" fill="none" strokeLinecap="round" strokeDasharray="0 0"/>
              <circle cx="60" cy="170" r="6" fill="oklch(0.85 0.008 90)" stroke="oklch(0.99 0.003 100)" strokeWidth="2"/>
              <circle cx="540" cy="50" r="8" fill="oklch(0.18 0.012 80)" stroke="oklch(0.99 0.003 100)" strokeWidth="2"/>

              {/* moving courier dot */}
              <circle r="9" fill="oklch(0.78 0.22 135)" stroke="oklch(0.99 0.003 100)" strokeWidth="3">
                <animateMotion dur="6s" repeatCount="indefinite" path="M 60 170 Q 180 180, 240 130 T 380 90 Q 460 70, 540 50"/>
              </circle>
              <circle r="20" fill="oklch(0.85 0.22 135 / 0.25)">
                <animateMotion dur="6s" repeatCount="indefinite" path="M 60 170 Q 180 180, 240 130 T 380 90 Q 460 70, 540 50"/>
                <animate attributeName="r" values="14;24;14" dur="2s" repeatCount="indefinite"/>
              </circle>
            </svg>
            <div style={{ position: 'absolute', top: 16, left: 16, padding: '6px 10px', background: 'oklch(0.99 0.003 100 / 0.85)', backdropFilter: 'blur(10px)', border: '1px solid var(--border)', borderRadius: 999, fontFamily: 'var(--f-mono)', fontSize: 10.5, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-2)' }}>
              ◉ live · sam · electric van · 3°C cold bag
            </div>
            <div style={{ position: 'absolute', bottom: 14, right: 16, padding: '6px 10px', background: 'oklch(0.99 0.003 100 / 0.85)', backdropFilter: 'blur(10px)', border: '1px solid var(--border)', borderRadius: 999, fontFamily: 'var(--f-mono)', fontSize: 10.5, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-2)' }}>
              you · 27 mare st
            </div>
          </div>

          <div className="sec-head" style={{ marginTop: 32 }}>
            <h3>Timeline</h3>
            <span className="meta">tap to expand</span>
          </div>
          <div className="timeline" style={{ background: 'var(--bg)', border: '1px solid var(--border-soft)', borderRadius: 'var(--r-lg)', padding: '4px 24px' }}>
            {steps.map((s, i) => (
              <div key={i} className={`timeline-row ${s.state}`}>
                <div className="timeline-time">{s.time}</div>
                <div className="timeline-node"/>
                <div className="timeline-label">
                  <div className="title">{s.label}</div>
                  <div className="sub">{s.sub}</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div className="col gap-4">
          <div className="glass" style={{ padding: 20 }}>
            <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 14 }}>
              <div style={{ width: 44, height: 44, borderRadius: '50%', background: 'linear-gradient(135deg, var(--warm), var(--accent))', display: 'grid', placeItems: 'center', color: 'white', fontSize: 14, fontWeight: 600 }}>S</div>
              <div>
                <div style={{ fontSize: 14 }}>Sam · 4.97★</div>
                <div className="muted mono" style={{ fontSize: 11, letterSpacing: '0.08em' }}>312 deliveries</div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <button className="btn btn-outline" style={{ flex: 1, justifyContent: 'center' }}>Message</button>
              <button className="btn btn-outline" style={{ flex: 1, justifyContent: 'center' }}>Call</button>
            </div>
          </div>

          <div style={{ background: 'var(--bg)', border: '1px solid var(--border-soft)', borderRadius: 'var(--r-lg)', padding: 18 }}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>Drop-off note</div>
            <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.5 }}>Leave with concierge if I don't answer in 2 minutes.</div>
            <button className="btn btn-ghost" style={{ marginTop: 8, padding: 0, color: 'var(--ink-3)' }}>Edit</button>
          </div>

          <button className="btn btn-outline btn-lg" style={{ justifyContent: 'center' }} onClick={() => onSend('what should i make tonight')}>
            What should I make? <Icon.arrow style={{ width: 14, height: 14 }}/>
          </button>
        </div>
      </div>
    </>
  );
};

/* ============================================
   PANTRY
   ============================================ */
const Pantry = ({ onAdd, basket, onSend }) => {
  return (
    <>
      <CanvasHeader
        crumb="07 — pantry"
        title="Everything you <em>already have.</em>"
        subtitle="Blyzr learns from what you buy and tracks how fast you go through it. Bars below estimate what's left."
      />

      <div className="sec-head">
        <h3>Running low</h3>
        <span className="meta">04 items · auto-top-up available</span>
      </div>
      <div className="grid-4" style={{ marginBottom: 32 }}>
        {BLYZR.pantry.filter((it) => it.level <= 0.4).map((it) => {
          const p = BLYZR.productById[it.id];
          const status = it.level <= 0.15 ? 'empty' : 'low';
          return (
            <div key={it.id} className="pantry-item">
              <div style={{ aspectRatio: 1.1, background: 'var(--surface-2)', borderRadius: 'var(--r-sm)', border: '1px solid var(--border-soft)', display: 'grid', placeItems: 'center', color: 'var(--ink-3)', backgroundImage: 'repeating-linear-gradient(135deg, transparent 0, transparent 6px, oklch(0.93 0.005 95) 6px, oklch(0.93 0.005 95) 7px)' }}>
                <Glyph kind={p.glyph} style={{ width: '50%', height: '50%' }}/>
              </div>
              <div>
                <div style={{ fontSize: 14 }}>{p.name}</div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--ink-4)', letterSpacing: '0.06em', marginTop: 2 }}>{it.lastBought}</div>
              </div>
              <div className={`pantry-bar ${status}`}><span style={{ width: `${it.level * 100}%` }}/></div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: status === 'empty' ? 'var(--danger)' : 'var(--warm)' }}>
                  {status === 'empty' ? 'nearly out' : 'running low'} · {Math.round(it.level * 100)}%
                </span>
                <button className="product-add" onClick={() => onAdd(p.id)}>
                  {basket.has(p.id) ? <Icon.check/> : <Icon.plus/>}
                </button>
              </div>
            </div>
          );
        })}
      </div>

      <div className="sec-head">
        <h3>Well stocked</h3>
        <span className="meta">04 items · you're good</span>
      </div>
      <div className="grid-4">
        {BLYZR.pantry.filter((it) => it.level > 0.4).map((it) => {
          const p = BLYZR.productById[it.id];
          return (
            <div key={it.id} className="pantry-item">
              <div style={{ aspectRatio: 1.1, background: 'var(--surface-2)', borderRadius: 'var(--r-sm)', border: '1px solid var(--border-soft)', display: 'grid', placeItems: 'center', color: 'var(--ink-3)', backgroundImage: 'repeating-linear-gradient(135deg, transparent 0, transparent 6px, oklch(0.93 0.005 95) 6px, oklch(0.93 0.005 95) 7px)' }}>
                <Glyph kind={p.glyph} style={{ width: '50%', height: '50%' }}/>
              </div>
              <div>
                <div style={{ fontSize: 14 }}>{p.name}</div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--ink-4)', letterSpacing: '0.06em', marginTop: 2 }}>{it.lastBought}</div>
              </div>
              <div className="pantry-bar"><span style={{ width: `${it.level * 100}%` }}/></div>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-3)' }}>{Math.round(it.level * 100)}% remaining</div>
            </div>
          );
        })}
      </div>

      <div className="glass" style={{ marginTop: 28, padding: 20, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16, flexWrap: 'wrap' }}>
        <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
          <OrbMini/>
          <div>
            <div style={{ fontFamily: 'var(--f-display)', fontStyle: 'italic', fontSize: 22 }}>One tap, four essentials topped up</div>
            <div className="muted" style={{ fontSize: 13, marginTop: 2 }}>$11.40 · eggs, milk, red onion, single-origin coffee</div>
          </div>
        </div>
        <button className="btn btn-accent" onClick={() => onSend('top up pantry')}>
          Top me up <Icon.arrow style={{ width: 14, height: 14 }}/>
        </button>
      </div>
    </>
  );
};

/* ============================================
   ORDER PLACED (intermediate)
   ============================================ */
const OrderPlaced = ({ onContinue }) => {
  useE(() => {
    const t = setTimeout(onContinue, 2200);
    return () => clearTimeout(t);
  }, []);

  return (
    <div className="welcome" style={{ minHeight: 'calc(100vh - 100px)' }}>
      <div style={{ position: 'relative' }}>
        <Orb size={180}/>
        <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center' }}>
          <div style={{ width: 64, height: 64, borderRadius: '50%', background: 'oklch(0.99 0.003 100 / 0.9)', display: 'grid', placeItems: 'center', backdropFilter: 'blur(20px)', color: 'var(--ink)', border: '1px solid var(--border)', animation: 'fade-up 0.6s 0.3s both' }}>
            <Icon.check style={{ width: 32, height: 32 }}/>
          </div>
        </div>
      </div>
      <div>
        <h1>Order placed.<br/><em>thursday, 6–7pm.</em></h1>
        <p>I'll ping you when Sam picks it up. Anything for the meantime?</p>
      </div>
      <div className="mono" style={{ fontSize: 10.5, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>
        order · blz-49-2a48 · receipt sent
      </div>
    </div>
  );
};

window.Checkout = Checkout;
window.Tracking = Tracking;
window.Pantry = Pantry;
window.OrderPlaced = OrderPlaced;
