// assets/screen_hooks.jsx
function ScreenHooks({ go, t }) {
  const [tab, setTab] = React.useState('all');
  const [filterHook, setFilterHook] = React.useState('all');
  const [filterDecision, setFilterDecision] = React.useState('all');
  const [search, setSearch] = React.useState('');
  const [expanded, setExpanded] = React.useState(new Set());

  const events = HOOK_EVENTS.filter(e =>
    (filterHook === 'all' || e.hook === filterHook) &&
    (filterDecision === 'all' || e.decision === filterDecision) &&
    (!search || e.message.toLowerCase().includes(search.toLowerCase()) || e.file.toLowerCase().includes(search.toLowerCase()))
  );

  const denyCount = HOOK_EVENTS.filter(e => e.decision === 'deny').length;
  const denyRate = (denyCount / HOOK_EVENTS.length * 100).toFixed(1);
  const topHook = Object.entries(HOOK_EVENTS.reduce((m, e) => { m[e.hook] = (m[e.hook] || 0) + 1; return m; }, {})).sort((a, b) => b[1] - a[1])[0];

  // Performance: per hook stats
  const hookStats = HOOKS.map(h => {
    const fires = HOOK_EVENTS.filter(e => e.hook === h.name);
    const sessions = new Set(fires.map(f => f.session_id));
    return {
      name: h.name,
      fires: fires.length,
      avg_per_session: fires.length / (sessions.size || 1),
      sessions: sessions.size,
      pct_sessions: (sessions.size / SESSIONS.length * 100),
      deny: fires.filter(f => f.decision === 'deny').length,
      soft: fires.filter(f => f.decision === 'soft').length,
    };
  }).sort((a, b) => b.fires - a.fires);

  return (
    <div className="page">
      <div className="page-head">
        <h1>Hook events</h1>
        <span className="page-sub">24h window</span>
        <div className="page-actions">
          <div className="segmented">
            <button>1h</button><button className="active">24h</button><button>7d</button>
          </div>
          <button className="btn"><Icon name="refresh" size={12} /> Refresh</button>
        </div>
      </div>

      {/* Top stats */}
      <div className="grid cols-4" style={{ marginBottom: 16 }}>
        <KpiCard label="Total fires (24h)" value={HOOK_EVENTS.length.toLocaleString()} delta={8} icon="zap" sparkData={timeSeries(24, 25, 12)} sparkColor="var(--warning)" />
        <KpiCard label="DENY rate" value={denyRate} unit="%" delta={-2.1} icon="ban" sparkData={timeSeries(24, 8, 4)} sparkColor="var(--danger)" />
        <KpiCard label="FP suspect (>5)" value={HOOK_FP_SUSPECTS.length} delta={3} deltaLabel="new today" icon="loop" sparkData={timeSeries(24, 0.4, 1)} sparkColor="var(--warning)" />
        <KpiCard label="Top hook" value={topHook?.[0].replace(/_/g, ' ')} icon="hook" />
      </div>

      {/* Tabs */}
      <div className="tabs">
        <div className={`tab ${tab === 'all' ? 'active' : ''}`} onClick={() => setTab('all')}>
          <Icon name="zap" size={12} /> All fires <span className="count">{HOOK_EVENTS.length.toLocaleString()}</span>
        </div>
        <div className={`tab ${tab === 'fp' ? 'active' : ''}`} onClick={() => setTab('fp')}>
          <Icon name="loop" size={12} /> Suspect FP <span className="count">{HOOK_FP_SUSPECTS.length}</span>
        </div>
        <div className={`tab ${tab === 'perf' ? 'active' : ''}`} onClick={() => setTab('perf')}>
          <Icon name="trend" size={12} /> Performance
        </div>
      </div>

      {tab === 'all' && (
        <div className="card">
          <div className="card-head" style={{ gap: 8 }}>
            <select className="select" style={{ width: 'auto' }} value={filterHook} onChange={e => setFilterHook(e.target.value)}>
              <option value="all">All hooks</option>
              {HOOKS.map(h => <option key={h.name} value={h.name}>{h.name}</option>)}
            </select>
            <select className="select" style={{ width: 'auto' }} value={filterDecision} onChange={e => setFilterDecision(e.target.value)}>
              <option value="all">All decisions</option>
              <option value="deny">deny</option>
              <option value="soft">soft</option>
              <option value="info">info</option>
            </select>
            <div style={{ position: 'relative', flex: 1, maxWidth: 320 }}>
              <Icon name="search" size={12} style={{ position: 'absolute', left: 8, top: 7, color: 'var(--text-tertiary)' }} />
              <input className="input" style={{ paddingLeft: 26 }} placeholder="search file / message" value={search} onChange={e => setSearch(e.target.value)} />
            </div>
            <span className="dim fs-11" style={{ marginLeft: 'auto' }}>{events.length.toLocaleString()} events</span>
          </div>
          <div className="table-wrap" style={{ maxHeight: 'calc(100vh - 360px)' }}>
            <table className="tbl">
              <thead><tr>
                <th style={{ width: 90 }}>Time</th>
                <th>Hook</th>
                <th style={{ width: 70 }}>Decision</th>
                <th>File</th>
                <th>Session</th>
                <th>Message</th>
              </tr></thead>
              <tbody>
                {events.slice(0, 300).map(e => (
                  <React.Fragment key={e.id}>
                    <tr className="clickable" onClick={() => { const n = new Set(expanded); n.has(e.id) ? n.delete(e.id) : n.add(e.id); setExpanded(n); }}>
                      <td className="dim"><Mono>{formatRel(e.ts)}</Mono></td>
                      <td><Mono>{e.hook}</Mono></td>
                      <td><Badge kind={e.decision === 'deny' ? 'danger' : e.decision === 'soft' ? 'warning' : 'info'}>{e.decision}</Badge></td>
                      <td className="dim2"><Mono>{e.file}</Mono></td>
                      <td onClick={(ev) => { ev.stopPropagation(); go('/sessions/' + e.session_id); }}>
                        <a className="id" style={{ color: 'var(--accent)' }}>{shortId(e.session_id)}</a>
                      </td>
                      <td className="dim2" style={{ maxWidth: 480, overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.message}</td>
                    </tr>
                    {expanded.has(e.id) && (
                      <tr>
                        <td colSpan={6} style={{ background: 'var(--bg-base)', padding: '12px 16px', whiteSpace: 'normal' }}>
                          <div className="code-block">{e.message}{'\n\n'}File: {e.file}{'\n'}Session: {e.session_id}{'\n'}Project: {e.project_id}</div>
                        </td>
                      </tr>
                    )}
                  </React.Fragment>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'fp' && (
        <div className="card">
          <div className="card-head">
            <h3>Suspect false positives</h3>
            <span className="sub">grouped by (session × hook × file) with fire_count &gt; 5</span>
          </div>
          <div className="table-wrap">
            <table className="tbl">
              <thead><tr>
                <th>Session</th>
                <th>Hook</th>
                <th>File</th>
                <th className="num">Fires</th>
                <th>Sample message</th>
                <th>Last seen</th>
                <th style={{ width: 80 }}></th>
              </tr></thead>
              <tbody>
                {HOOK_FP_SUSPECTS.map((s, i) => (
                  <tr key={i} className="fp-suspect-row">
                    <td><a className="id" style={{ color: 'var(--accent)' }} onClick={() => go('/sessions/' + s.session_id)}>{shortId(s.session_id)}</a></td>
                    <td><Mono>{s.hook}</Mono></td>
                    <td className="dim2"><Mono>{s.file}</Mono></td>
                    <td className="num"><Badge kind="danger" style={{ fontWeight: 600 }}>×{s.count}</Badge></td>
                    <td className="dim2" style={{ maxWidth: 420, overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.message}</td>
                    <td className="dim"><Mono>{formatRel(s.ts)}</Mono></td>
                    <td><button className="btn xs" onClick={() => go('/sessions/' + s.session_id)}>view <Icon name="external" size={10} /></button></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === 'perf' && (
        <div className="grid" style={{ gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div className="card">
            <div className="card-head">
              <h3>Fires by hook</h3>
              <span className="sub">7d total</span>
            </div>
            <div className="card-body">
              <HBarChart data={hookStats.map(h => ({ label: h.name, value: h.fires }))} maxBars={12} color="var(--warning)" />
            </div>
          </div>
          <div className="card">
            <div className="card-head">
              <h3>Sessions hit %</h3>
              <span className="sub">% of sessions where hook fires ≥ once</span>
            </div>
            <div className="card-body">
              <HBarChart data={hookStats.map(h => ({ label: h.name, value: +h.pct_sessions.toFixed(1) }))} valueFmt={v => v + '%'} maxBars={12} color="var(--info)" />
            </div>
          </div>
          <div className="card" style={{ gridColumn: '1 / -1' }}>
            <div className="card-head"><h3>All hooks · detail</h3></div>
            <div className="table-wrap">
              <table className="tbl">
                <thead><tr>
                  <th>Hook</th>
                  <th className="num">Fires</th>
                  <th className="num">Deny</th>
                  <th className="num">Soft</th>
                  <th className="num">Sessions</th>
                  <th className="num">Avg / session</th>
                  <th className="num">% sessions hit</th>
                </tr></thead>
                <tbody>
                  {hookStats.map(h => (
                    <tr key={h.name}>
                      <td><Mono>{h.name}</Mono></td>
                      <td className="num"><Mono>{h.fires}</Mono></td>
                      <td className="num"><Mono className="text-danger">{h.deny}</Mono></td>
                      <td className="num"><Mono className="text-warning">{h.soft}</Mono></td>
                      <td className="num"><Mono>{h.sessions}</Mono></td>
                      <td className="num"><Mono>{h.avg_per_session.toFixed(2)}</Mono></td>
                      <td className="num"><Mono>{h.pct_sessions.toFixed(1)}%</Mono></td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { ScreenHooks });
