// MissionChef — POS / Kasse (Bonieren mit echtem Warenkorb)

function PosScreen({ Topbar }) {
  const store = useStore();
  const [cat, setCat] = React.useState('Antipasti');
  const [tableId, setTableId] = React.useState('t07');
  const [, force] = React.useState(0);
  const bump = () => force(n => n + 1);

  const CATS = ['Antipasti', 'Pasta', 'Secondi', 'Dolci', 'Bar', 'Wein'];
  const items = store.menu.filter(m => m.cat === cat);
  const cart = store.carts[tableId] || [];

  const addItem = (m) => {
    const c = store.carts[tableId] || [];
    const existing = c.find(x => x.mid === m.id);
    if (existing) existing.qty += 1;
    else c.push({ id: 'c' + Date.now(), mid: m.id, qty: 1, mods: [] });
    mcApi.mutate(s => { s.carts[tableId] = c; });
    bump();
  };
  const remove = (id) => {
    const c = (store.carts[tableId] || []).filter(x => x.id !== id);
    mcApi.mutate(s => { s.carts[tableId] = c; });
    bump();
  };
  const qty = (id, d) => {
    const c = store.carts[tableId] || [];
    const it = c.find(x => x.id === id);
    if (!it) return;
    it.qty = Math.max(1, it.qty + d);
    mcApi.mutate(s => { s.carts[tableId] = c; });
    bump();
  };

  const subtotal = cart.reduce((s, c) => s + store.menu.find(m => m.id === c.mid).price * c.qty, 0);
  const tax = subtotal * 0.19 / 1.19;

  const sendToKitchen = async () => {
    if (!cart.length) return;
    const table = store.tables.find(t => t.id === tableId);
    await mcApi.post('/tickets', {
      table: table.label, seats: table.seats, course: 'main', server: 'u4',
      items: cart.map(c => ({ id: c.id, mid: c.mid, qty: c.qty, state: 'new', mods: c.mods })),
    });
    mcApi.mutate(s => { s.carts[tableId] = []; });
    bump();
  };

  return (
    <>
      <Topbar
        title="Kasse"
        subtitle={`${store.tables.find(t => t.id === tableId)?.label} · Open Checks: ${Object.keys(store.carts).filter(k => (store.carts[k]||[]).length).length}`}
        actions={
          <select value={tableId} onChange={e => setTableId(e.target.value)} className="mc-input" style={{ width: 160 }}>
            {store.tables.map(t => <option key={t.id} value={t.id}>Tisch {t.label}</option>)}
          </select>
        }
      />
      <div style={{ flex: 1, display: 'grid', gridTemplateColumns: '1fr 380px', overflow: 'hidden' }}>
        {/* Menu */}
        <div style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          <div style={{ padding: '18px 28px', borderBottom: '1px solid var(--mc-rule)', display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {CATS.map(c => (
              <button key={c} onClick={() => setCat(c)} className={cat === c ? 'mc-btn' : 'mc-btn ghost'} style={{ padding: '8px 14px', fontSize: 13 }}>
                {c}
              </button>
            ))}
          </div>
          <div className="mc-scroll" style={{ flex: 1, overflow: 'auto', padding: 28 }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
              {items.map(m => (
                <button key={m.id} onClick={() => addItem(m)} className="mc-card" style={{
                  padding: 18, textAlign: 'left', cursor: 'pointer',
                  display: 'flex', flexDirection: 'column', gap: 10,
                  color: 'var(--mc-ink)', transition: 'transform .08s',
                }} onMouseDown={e => e.currentTarget.style.transform = 'scale(.98)'} onMouseUp={e => e.currentTarget.style.transform = ''}>
                  <div style={{ fontSize: 14, fontWeight: 500, lineHeight: 1.25, minHeight: 36 }}>{m.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--mc-ink-dim)', lineHeight: 1.35, minHeight: 30 }}>{m.desc}</div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 'auto' }}>
                    <div className="mc-num" style={{ fontSize: 20, fontWeight: 500 }}>{fmtEUR(m.price)}</div>
                    <Pill tone="leaf">{((m.price - m.cost)/m.price*100).toFixed(0)}%</Pill>
                  </div>
                </button>
              ))}
            </div>
          </div>
        </div>

        {/* Check */}
        <div style={{ borderLeft: '1px solid var(--mc-rule)', background: 'var(--mc-surface)', display: 'flex', flexDirection: 'column' }}>
          <div style={{ padding: 22, borderBottom: '1px solid var(--mc-rule)' }}>
            <div className="mc-eyebrow">Bon · Tisch {store.tables.find(t => t.id === tableId)?.label}</div>
            <div style={{ fontSize: 20, fontWeight: 500, marginTop: 4 }}>{cart.length} Position{cart.length === 1 ? '' : 'en'}</div>
          </div>
          <div className="mc-scroll" style={{ flex: 1, overflow: 'auto', padding: '10px 22px' }}>
            {!cart.length && <div style={{ color: 'var(--mc-ink-dim)', fontSize: 13, padding: '20px 0', textAlign: 'center' }}>Kein Artikel — tippe links, um zu bonieren.</div>}
            {cart.map(c => {
              const m = store.menu.find(x => x.id === c.mid);
              return (
                <div key={c.id} style={{ padding: '12px 0', borderBottom: '1px solid var(--mc-rule)' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'start', gap: 10 }}>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 500 }}>{m.name}</div>
                      <div style={{ fontSize: 11, color: 'var(--mc-ink-dim)' }}>{fmtEUR(m.price)} × {c.qty}</div>
                    </div>
                    <div className="mc-num" style={{ fontSize: 14, fontWeight: 500 }}>{fmtEUR(m.price * c.qty)}</div>
                  </div>
                  <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
                    <button className="mc-btn ghost sm" onClick={() => qty(c.id, -1)}>−</button>
                    <button className="mc-btn ghost sm" onClick={() => qty(c.id, 1)}>+</button>
                    <button className="mc-btn ghost sm" onClick={() => remove(c.id)} style={{ marginLeft: 'auto' }}><McIcon2 name="trash" size={12} /></button>
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{ padding: 22, borderTop: '1px solid var(--mc-rule)', background: 'var(--mc-surface-2)' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--mc-ink-dim)', marginBottom: 4 }}>
              <span>enthaltene MwSt 19%</span><span className="mc-num">{fmtEUR(tax)}</span>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginTop: 10 }}>
              <div style={{ fontSize: 14, color: 'var(--mc-ink-muted)' }}>Gesamt</div>
              <div className="mc-num" style={{ fontSize: 30, fontWeight: 500, letterSpacing: '-0.02em' }}>{fmtEUR(subtotal)}</div>
            </div>
            <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
              <button className="mc-btn leaf" style={{ flex: 1 }} onClick={sendToKitchen} disabled={!cart.length}>
                <McIcon2 name="flame" size={14} />Küche
              </button>
              <button className="mc-btn ember" style={{ flex: 1 }} disabled={!cart.length}>
                <McIcon2 name="eur" size={14} />Bezahlen
              </button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { PosScreen });
