// aerOS Guest v2 — Cart screen + order confirmation/tracking.
const { useState: _ct2S, useEffect: _ct2E } = React;

function G2Cart({ C, t, lang, tw, cart, setCart, onBack, onPlaced, toast, onItem }) {
  const subtotal = cart.reduce((s, it) => s + it.unit * it.qty, 0);
  const serviceFee = Math.round(subtotal * 0.1);
  const total = subtotal + serviceFee;
  const [note, setNote] = _ct2S('');
  const setQty = (id, q) => { if (q <= 0) setCart(c => c.filter(x => x.id !== id)); else setCart(c => c.map(x => x.id === id ? { ...x, qty: q } : x)); };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: C.bg, fontFamily: G2THEME.BODY_FONT }}>
      <div style={{ flexShrink: 0, paddingTop: 50, padding: '50px 16px 14px', display: 'flex', alignItems: 'center', gap: 12, background: C.bg2, borderBottom: `1px solid ${C.line}` }}>
        <button onClick={onBack} style={{ width: 40, height: 40, borderRadius: 12, border: `1px solid ${C.line}`, background: 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: C.ink, flexShrink: 0 }}>{Icon.chevLeft({ size: 21 })}</button>
        <h1 style={{ fontFamily: G2THEME.headFont(tw), fontWeight: 600, fontSize: 24, color: C.ink }}>{t.cart}</h1>
      </div>

      {cart.length === 0 ? (
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 30, textAlign: 'center' }}>
          <div style={{ width: 76, height: 76, borderRadius: 24, background: C.bg2, border: `1px solid ${C.line}`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: C.muted, marginBottom: 16 }}>{Icon.bag({ size: 32 })}</div>
          <div style={{ fontFamily: G2THEME.headFont(tw), fontWeight: 600, fontSize: 21, color: C.ink }}>{t.cartEmpty}</div>
          <div style={{ fontSize: 14, color: C.muted, marginTop: 6, maxWidth: 240 }}>{t.cartEmptyDesc}</div>
          <div style={{ marginTop: 20 }}><G2Btn C={C} onClick={onBack} icon={Icon.utensils}>{t.browseMenu}</G2Btn></div>
        </div>
      ) : (
        <>
          <div className="g2-noscroll" style={{ flex: 1, overflowY: 'auto', padding: '14px 16px' }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
              {cart.map(it => (
                <div key={it.id} style={{ display: 'flex', gap: 12, padding: 12, borderRadius: 16, background: C.bg2, boxShadow: C.cardShadow, border: tw.corners === 'sharp' ? `1px solid ${C.line}` : 'none' }}>
                  <div onClick={() => onItem && onItem(it.pid)} style={{ width: 64, flexShrink: 0, cursor: onItem ? 'pointer' : 'default' }}><G2Photo id={'c-' + it.pid} color={it.color} ratio={1} radius={tw.corners === 'sharp' ? 3 : 11} C={C} t={t} photoMode={tw.photoMode} src={(window.G2DATA.PRODUCTS.find(x => x.id === it.pid) || {}).image} /></div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 10 }}>
                      <div onClick={() => onItem && onItem(it.pid)} style={{ fontWeight: 700, fontSize: 15, color: C.ink, lineHeight: 1.2, cursor: onItem ? 'pointer' : 'default' }}>{it.name}</div>
                      <button onClick={() => setQty(it.id, 0)} style={{ border: 'none', background: 'none', cursor: 'pointer', color: C.muted, display: 'flex', flexShrink: 0, padding: 0 }}>{Icon.trash({ size: 16 })}</button>
                    </div>
                    {(it.portionLabel || it.modLabels?.length || it.note) && (
                      <div style={{ fontSize: 12, color: C.muted, marginTop: 3, lineHeight: 1.4 }}>{[it.portionLabel, ...(it.modLabels || [])].filter(Boolean).join(' · ')}{it.note ? ((it.portionLabel || it.modLabels?.length ? ' · ' : '') + '“' + it.note + '”') : ''}</div>
                    )}
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 9 }}>
                      <G2Stepper value={it.qty} onChange={q => setQty(it.id, q)} C={C} size="sm" min={0} />
                      <span className="tnum" style={{ fontWeight: 800, fontSize: 15.5, color: C.ink }}>{G2THEME.money(it.unit * it.qty, tw.currency)}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>

            <div style={{ marginTop: 16 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: C.ink, marginBottom: 9 }}>{t.cartNote}</div>
              <textarea value={note} onChange={e => setNote(e.target.value)} placeholder={t.orderNotePh} rows={2} style={{ width: '100%', boxSizing: 'border-box', borderRadius: 13, border: `1.5px solid ${C.line2}`, padding: '12px 14px', fontSize: 14, fontFamily: G2THEME.BODY_FONT, resize: 'none', color: C.ink, outline: 'none', background: C.bg2 }} />
            </div>

            <div style={{ marginTop: 16, padding: 16, borderRadius: 16, background: C.bg2, border: `1px solid ${C.line}` }}>
              {[[t.subtotal, subtotal], [t.service, serviceFee]].map(([l, v]) => (
                <div key={l} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, color: C.ink2, marginBottom: 9 }}><span>{l}</span><span className="tnum">{G2THEME.money(v, tw.currency)}</span></div>
              ))}
              <div style={{ height: 1, background: C.line, margin: '4px 0 11px' }} />
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}><span style={{ fontSize: 16, fontWeight: 800, color: C.ink }}>{t.total}</span><span className="tnum" style={{ fontSize: 21, fontWeight: 800, color: C.accent }}>{G2THEME.money(total, tw.currency)}</span></div>
            </div>
          </div>

          <div style={{ flexShrink: 0, borderTop: `1px solid ${C.line}`, padding: '14px 16px calc(14px + env(safe-area-inset-bottom))', background: C.bg2 }}>
            <G2Btn full size="lg" C={C} iconRight={Icon.arrowRight} onClick={() => onPlaced({ items: cart, total, note, eta: 18 + Math.round(Math.random() * 10) })}>{t.placeOrder} · {G2THEME.money(total, tw.currency)}</G2Btn>
          </div>
        </>
      )}
    </div>
  );
}

function G2Tracking({ C, t, lang, tw, order, onNew }) {
  const steps = [t.track_received, t.track_preparing, t.track_ontheway, t.track_served];
  const [step, setStep] = _ct2S(0);
  const [cancelled, setCancelled] = _ct2S(false);
  // Real status: poll the backend tracker (no mock auto-advance).
  const CODE_STEP = { new: 0, received: 0, preparing: 1, ready: 2, ontheway: 2, on_way: 2, delivered: 3, served: 3 };
  _ct2E(() => {
    if (!order.id || !window.guestApi) return;
    let stop = false; let id = null;
    const done = () => { stop = true; if (id) clearInterval(id); };
    const tick = async () => {
      try {
        const d = await window.guestApi.trackOrder(order.id, order.surname || '-');
        if (stop || !d) return;
        if (d.cancelled) { setCancelled(true); done(); return; }   // terminal: stop polling
        const s = CODE_STEP[d.current_code]; if (s != null) setStep(s);
        if (s >= 3) done();   // delivered/served: nothing left to track
      } catch (e) {}
    };
    tick(); id = setInterval(tick, 8000); return () => { stop = true; if (id) clearInterval(id); };
  }, [order.id, order.surname]);
  const stepIcons = [Icon.checkCircle, Icon.utensils, Icon.car, Icon.bell];

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: C.bg, fontFamily: G2THEME.BODY_FONT }}>
      <div className="g2-noscroll" style={{ flex: 1, overflowY: 'auto', padding: '70px 20px 24px' }}>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', animation: tw.animate ? 'g2pop .5s cubic-bezier(.34,1.56,.64,1)' : 'none' }}>
          <div style={{ width: 84, height: 84, borderRadius: '50%', background: `linear-gradient(135deg, ${C.accent}, ${C.accentDark})`, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: `0 14px 36px -10px ${C.accent}`, marginBottom: 18 }}>{Icon.check({ size: 42 })}</div>
          <h1 style={{ fontFamily: G2THEME.headFont(tw), fontWeight: 600, fontSize: 28, color: cancelled ? '#dc2626' : C.ink }}>{cancelled ? (lang === 'en' ? 'Order cancelled' : 'Sipariş iptal edildi') : t.orderPlaced}</h1>
          <p style={{ fontSize: 14.5, color: C.ink2, lineHeight: 1.5, marginTop: 8, maxWidth: 290 }}>{cancelled ? (lang === 'en' ? 'Please contact our team if this is unexpected.' : 'Beklenmedik ise lütfen ekibimize ulaşın.') : t.orderPlacedDesc}</p>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginTop: 16, padding: '9px 16px', borderRadius: 999, background: C.accentSoft, color: C.onAccentSoft, fontSize: 14, fontWeight: 700 }}>{Icon.clock({ size: 16 })}{t.estTime} {order.eta} {t.min}</div>
        </div>

        <div style={{ marginTop: 32, padding: '4px 8px' }}>
          {steps.map((s, i) => {
            const done = i < step, active = i === step;
            const IC = stepIcons[i];
            return (
              <div key={i} style={{ display: 'flex', gap: 15, alignItems: 'flex-start' }}>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', alignSelf: 'stretch' }}>
                  <div style={{ width: 40, height: 40, borderRadius: '50%', background: done || active ? `linear-gradient(135deg, ${C.accent}, ${C.accentDark})` : C.bg2, color: done || active ? '#fff' : C.muted, border: done || active ? 'none' : `1.5px solid ${C.line2}`, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, transition: 'all 300ms', '--g2acc': `${C.accent}80`, animation: active && tw.animate ? 'g2pulse 1.8s infinite' : 'none' }}>{done ? Icon.check({ size: 20 }) : IC({ size: 20 })}</div>
                  {i < steps.length - 1 && <div style={{ width: 2, flex: 1, minHeight: 26, background: done ? C.accent : C.line, margin: '4px 0', transition: 'background 300ms' }} />}
                </div>
                <div style={{ paddingTop: 9, paddingBottom: 18 }}>
                  <div style={{ fontSize: 15.5, fontWeight: active ? 800 : 700, color: done || active ? C.ink : C.muted }}>{s}</div>
                  {active && <div style={{ fontSize: 12.5, color: C.accent, fontWeight: 600, marginTop: 2 }}>●  {lang === 'en' ? 'In progress' : 'Devam ediyor'}</div>}
                </div>
              </div>
            );
          })}
        </div>

        <div style={{ marginTop: 8, padding: 16, borderRadius: 16, background: C.bg2, border: `1px solid ${C.line}` }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: C.muted, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 11 }}>{t.cart}</div>
          {order.items.map(it => (
            <div key={it.id} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14, marginBottom: 8 }}>
              <span style={{ color: C.ink2 }}><span className="tnum" style={{ fontWeight: 700, color: C.ink }}>{it.qty}×</span> {it.name}</span>
              <span className="tnum" style={{ fontWeight: 700, color: C.ink }}>{G2THEME.money(it.unit * it.qty, tw.currency)}</span>
            </div>
          ))}
          <div style={{ height: 1, background: C.line, margin: '8px 0' }} />
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 15, fontWeight: 800, color: C.ink }}><span>{t.total}</span><span className="tnum">{G2THEME.money(order.total, tw.currency)}</span></div>
        </div>
      </div>
      <div style={{ flexShrink: 0, borderTop: `1px solid ${C.line}`, padding: '14px 16px calc(14px + env(safe-area-inset-bottom))', background: C.bg2 }}>
        <G2Btn full size="lg" variant="soft" C={C} onClick={onNew} icon={Icon.refresh}>{t.newOrder}</G2Btn>
      </div>
    </div>
  );
}

Object.assign(window, { G2Cart, G2Tracking });
