// ===== Optimierung → Kommentare (Tabelle aller KiKi-Kommentare) =====
const { useState: useKvS, useEffect: useKvE, useMemo: useKvM } = React;

function KommentareView() {
  const [, force] = useKvS(0);
  useKvE(() => window.KkStore.sub(() => force(n => n + 1)), []);
  const list = window.KkStore.list;
  const cats = window.KkStore.cats;
  const [catF, setCatF] = useKvS('alle');
  const [q, setQ] = useKvS('');
  const [sort, setSort] = useKvS({ key: 'ts', dir: -1 });
  const [detail, setDetail] = useKvS(null);

  const rows = useKvM(() => {
    let r = list.slice();
    if (catF !== 'alle') r = r.filter(c => c.cat === catF);
    if (q.trim()) { const s = q.trim().toLowerCase(); r = r.filter(c => (c.refId + ' ' + c.refLabel + ' ' + c.text + ' ' + c.cat).toLowerCase().includes(s)); }
    r.sort((a, b) => {
      let va = a[sort.key], vb = b[sort.key];
      if (va == null) va = ''; if (vb == null) vb = '';
      return (va < vb ? -1 : va > vb ? 1 : 0) * sort.dir;
    });
    return r;
  }, [list, catF, q, sort]);

  const th = (key, label, w) => {
    const active = sort.key === key;
    return <th onClick={() => setSort(s => s.key === key ? { key, dir: -s.dir } : { key, dir: 1 })}
      style={{ padding: '8px 12px', textAlign: 'left', fontFamily: 'var(--mono)', fontSize: 10.5, letterSpacing: '.08em', textTransform: 'uppercase', color: active ? 'var(--accent-ink)' : 'var(--muted)', cursor: 'pointer', whiteSpace: 'nowrap', borderBottom: '1px solid var(--line-2)', width: w }}>
      {label} {active ? (sort.dir === 1 ? '▲' : '▼') : ''}</th>;
  };
  const fmtTs = (ts) => { const d = new Date(ts); return d.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: '2-digit' }) + ' ' + d.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' }); };
  const catColor = (c) => { const i = cats.indexOf(c); const hues = ['var(--good)', 'var(--accent)', 'var(--warn)', 'var(--bad)', '#D8C8E8', 'var(--line-2)']; return hues[i % hues.length]; };

  return (
    <React.Fragment>
      <header style={{ flex: '0 0 auto', display: 'flex', alignItems: 'center', gap: 14, padding: '0 18px', height: 56, background: 'var(--panel)', borderBottom: '1px solid var(--line-2)' }}>
        <span style={{ fontSize: 14.5, fontWeight: 600 }}>Kommentare</span>
        <span className="label">{rows.length} von {list.length} · KiKi</span>
      </header>
      <main style={{ flex: 1, minHeight: 0, overflow: 'auto', padding: 14 }}>
        {/* Filterleiste */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Kommentare durchsuchen…" style={{ flex: 1, maxWidth: 360, height: 36, boxSizing: 'border-box', padding: '0 12px', border: '1px solid var(--line-2)', borderRadius: 8, fontSize: 13, background: 'var(--panel)', color: 'var(--ink)' }} />
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            <button onClick={() => setCatF('alle')} style={kvChip(catF === 'alle')}>Alle</button>
            {cats.map(c => <button key={c} onClick={() => setCatF(c)} style={kvChip(catF === c)}>{c}</button>)}
          </div>
        </div>

        <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 8, boxShadow: 'var(--shadow)', overflow: 'hidden' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead><tr>
              {th('refId', 'Auftrags-ID', 140)}
              {th('ts', 'Zeitstempel', 150)}
              {th('cat', 'Kategorie', 130)}
              {th('text', 'Kommentar')}
              <th style={{ width: 40, borderBottom: '1px solid var(--line-2)' }}></th>
            </tr></thead>
            <tbody>
              {rows.map(c => (
                <tr key={c.id} onClick={() => setDetail(c)} style={{ borderBottom: '1px solid var(--line)', cursor: 'pointer' }}>
                  <td style={{ padding: '9px 12px', fontFamily: 'var(--mono)', fontWeight: 600, whiteSpace: 'nowrap' }}>{c.refId || '—'}</td>
                  <td style={{ padding: '9px 12px', fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--ink-2)', whiteSpace: 'nowrap' }}>{fmtTs(c.ts)}</td>
                  <td style={{ padding: '9px 12px' }}><span style={{ display: 'inline-block', padding: '2px 9px', borderRadius: 99, fontSize: 11.5, fontWeight: 600, background: `color-mix(in oklch, ${catColor(c.cat)} 50%, var(--surface))`, color: 'var(--ink-2)' }}>{c.cat}</span></td>
                  <td style={{ padding: '9px 12px', color: 'var(--ink)', maxWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.text}</td>
                  <td style={{ padding: '9px 8px', textAlign: 'right' }}><Icon name="chevron" size={14} style={{ color: 'var(--muted)' }} /></td>
                </tr>
              ))}
              {rows.length === 0 && <tr><td colSpan={5} style={{ padding: 36, textAlign: 'center', color: 'var(--muted)' }}>
                Noch keine Kommentare. Rechtsklick auf eine Auftragszeile oder ein Widget → „kiki".
              </td></tr>}
            </tbody>
          </table>
        </div>
      </main>

      {/* Detail Slide-Over */}
      {detail && (
        <React.Fragment>
          <div onClick={() => setDetail(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(63,62,61,.3)', zIndex: 81, animation: 'rowIn .15s' }} />
          <div style={{ position: 'fixed', top: 0, right: 0, bottom: 0, width: 420, background: 'var(--surface)', zIndex: 82, boxShadow: '-12px 0 40px rgba(63,62,61,.18)', borderLeft: '1px solid var(--line-2)', display: 'flex', flexDirection: 'column', animation: 'kkSlide .26s cubic-bezier(.2,.8,.2,1)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '15px 18px', borderBottom: '1px solid var(--line)' }}>
              <span style={{ display: 'grid', placeItems: 'center', width: 28, height: 28, borderRadius: 7, background: 'var(--accent-ink)', color: '#fff', fontWeight: 700, fontSize: 13, fontFamily: 'var(--mono)' }}>ki</span>
              <div><div style={{ fontWeight: 600, fontSize: 14.5 }}>Kommentar-Detail</div><div className="num" style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--muted)' }}>{fmtTs(detail.ts)}</div></div>
              <button onClick={() => setDetail(null)} style={{ marginLeft: 'auto', width: 30, height: 30, border: '1px solid var(--line-2)', borderRadius: 6, background: 'var(--surface)', display: 'grid', placeItems: 'center', color: 'var(--ink-2)', cursor: 'pointer' }}><Icon name="close" size={15} /></button>
            </div>
            <div style={{ flex: 1, overflow: 'auto', padding: 18 }}>
              <KvField label="Auftrag" value={detail.refLabel || detail.refId || '—'} mono />
              <KvField label="Bezug" value={detail.kind || 'Auftrag'} />
              <KvField label="Kategorie" value={detail.cat} />
              <KvField label="Zeitstempel" value={fmtTs(detail.ts)} mono />
              <div className="label" style={{ marginTop: 16, marginBottom: 6 }}>Kommentar</div>
              <div style={{ padding: 14, borderRadius: 8, background: 'var(--surface-2)', border: '1px solid var(--line)', fontSize: 14, lineHeight: 1.55, color: 'var(--ink)', whiteSpace: 'pre-wrap' }}>{detail.text}</div>
            </div>
            <div style={{ padding: '14px 18px', borderTop: '1px solid var(--line)' }}>
              <button onClick={() => { window.KkStore.remove(detail.id); setDetail(null); }} style={{ display: 'inline-flex', alignItems: 'center', gap: 7, height: 36, padding: '0 14px', borderRadius: 8, border: '1px solid var(--line-2)', background: 'var(--surface)', color: 'var(--bad-ink)', fontWeight: 500, fontSize: 13, cursor: 'pointer' }}><Icon name="trash" size={15} /> Kommentar löschen</button>
            </div>
          </div>
        </React.Fragment>
      )}
    </React.Fragment>
  );
}

function KvField({ label, value, mono }) {
  return <div style={{ marginBottom: 12 }}>
    <div className="label" style={{ marginBottom: 3 }}>{label}</div>
    <div style={{ fontSize: 13.5, fontFamily: mono ? 'var(--mono)' : 'var(--sans)', color: 'var(--ink)' }}>{value}</div>
  </div>;
}
const kvChip = (on) => ({ height: 32, padding: '0 13px', borderRadius: 99, fontSize: 12.5, fontWeight: 500, cursor: 'pointer', border: '1px solid ' + (on ? 'var(--accent-ink)' : 'var(--line-2)'), background: on ? 'var(--accent)' : 'var(--panel)', color: on ? 'var(--accent-ink)' : 'var(--ink-2)' });

Object.assign(window, { KommentareView });
