// MissionChef — KDS (Küchen-Display) mit Live-Timern

function KdsScreen({ Topbar }) {
  const store = useStore();
  const [, force] = React.useState(0);
  React.useEffect(() => {
    const iv = setInterval(() => force(n => n + 1), 1000);
    return () => clearInterval(iv);
  }, []);

  const setItemState = (tid, iid, state) => {
    mcApi.patch(`/tickets/${tid}/items/${iid}`, { state });
  };
  const bumpTicket = (tid) => {
    mcApi.delete(`/tickets/${tid}`);
  };

  return (
    <>
      <Topbar
        title="Küche · KDS"
        subtitle={`${store.tickets.length} offene Tickets · Pass Live`}
        actions={
          <div style={{ display: 'flex', gap: 8 }}>
            <Pill tone="leaf"><StatusDot tone="ok" /> Küche online</Pill>
            <Pill>Pass</Pill>
          </div>
        }
      />
      <div className="mc-scroll" style={{ flex: 1, overflow: 'auto', padding: 24, background: 'var(--mc-surface-2)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 18 }}>
          {store.tickets.map(tk => {
            const mins = Math.floor((Date.now() - tk.opened) / 60000);
            const secs = Math.floor((Date.now() - tk.opened) / 1000) % 60;
            const tone = mins > 18 ? 'bad' : mins > 10 ? 'warn' : 'ok';
            const border = tone === 'bad' ? 'var(--mc-bad)' : tone === 'warn' ? 'var(--mc-ember)' : 'var(--mc-leaf-700)';
            return (
              <div key={tk.id} style={{
                background: 'var(--mc-surface)', border: `1px solid var(--mc-rule)`,
                borderTop: `3px solid ${border}`,
                display: 'flex', flexDirection: 'column',
              }}>
                <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--mc-rule)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <div style={{ fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em' }}>Tisch {tk.table}</div>
                    <div style={{ fontSize: 11, color: 'var(--mc-ink-dim)', textTransform: 'uppercase', letterSpacing: '.12em', marginTop: 2 }}>
                      {tk.course} · {tk.seats} Pl · #{tk.id.replace('k','')}
                    </div>
                  </div>
                  <div className="mc-mono mc-num" style={{
                    fontSize: 22, fontWeight: 500,
                    color: tone === 'bad' ? 'var(--mc-bad)' : tone === 'warn' ? 'var(--mc-ember-700)' : 'var(--mc-ink)',
                  }}>
                    {String(Math.floor(mins/60)).padStart(2,'0')}:{String(mins%60).padStart(2,'0')}:{String(secs).padStart(2,'0')}
                  </div>
                </div>

                <div style={{ padding: '6px 0', flex: 1 }}>
                  {tk.items.map(it => {
                    const m = store.menu.find(x => x.id === it.mid);
                    const done = it.state === 'done';
                    const cooking = it.state === 'cooking';
                    return (
                      <div key={it.id} onClick={() => setItemState(tk.id, it.id, done ? 'cooking' : (cooking ? 'done' : 'cooking'))} style={{
                        padding: '10px 18px', display: 'flex', alignItems: 'center', gap: 12,
                        cursor: 'pointer',
                        opacity: done ? 0.45 : 1,
                        textDecoration: done ? 'line-through' : 'none',
                      }}>
                        <div style={{
                          width: 20, height: 20, border: `2px solid ${done ? 'var(--mc-leaf-700)' : cooking ? 'var(--mc-ember)' : 'var(--mc-rule-strong)'}`,
                          background: done ? 'var(--mc-leaf-700)' : 'transparent',
                          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                        }}>
                          {done && <McIcon2 name="check" size={12} color="#FFFFFF" stroke={2.5} />}
                          {cooking && <div style={{ width: 6, height: 6, background: 'var(--mc-ember)', borderRadius: '50%' }} />}
                        </div>
                        <div style={{ flex: 1 }}>
                          <div style={{ fontSize: 14, fontWeight: 500 }}>
                            <span className="mc-mono" style={{ color: 'var(--mc-leaf-700)', marginRight: 6 }}>{it.qty}×</span>
                            {m?.name}
                          </div>
                          {it.mods && it.mods.length > 0 && (
                            <div style={{ fontSize: 11, color: 'var(--mc-ember-700)', marginTop: 2, fontStyle: 'italic' }}>
                              {it.mods.join(' · ')}
                            </div>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>

                <button onClick={() => bumpTicket(tk.id)} className="mc-btn leaf" style={{ margin: 12, justifyContent: 'center' }}>
                  <McIcon2 name="check" size={14} />Bump · Pass fertig
                </button>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
}

Object.assign(window, { KdsScreen });
