// ESI FORENSICS — Views Part 2: Analysis · Timeline · Lab Ops
const { useState: useFV2State } = React;
const Tfv2 = window.ArbiterTokens;

function ForensicsAnalysis({ data }) {
  const esi = window.__esi;
  const f = data.forensics;
  const [statusFilter, setStatusFilter] = useFV2State('All');
  const jobs = f.analysisJobs;
  const statuses = ['All', ...new Set(jobs.map(j => j.status))];
  const rows = jobs.filter(j => statusFilter === 'All' || j.status === statusFilter);
  const completed = jobs.filter(j => j.status === 'Complete');
  const totalFindings = completed.reduce((s, j) => s + (j.findings || 0), 0);

  const priorityColor = (p) => ({ Critical: esi.crimson, High: esi.amber, Medium: esi.cyan, Low: esi.slate }[p] || esi.slate);
  const typeIcon = (t) => ({ 'Keyword Search': '', 'Deleted File Recovery': '', 'Timeline Reconstruction': '', 'Location Analysis': '', 'Anti-Forensics Detection': '', 'Email Cache Analysis': '' }[t] || '◆');

  return (
    <div>
      <div style={{ ...esi.card, borderLeft: `3px solid ${esi.cyan}`, background: esi.cyanBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: esi.cyan, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Forensic analysis — keyword searches · timeline reconstruction · deleted file recovery</div>
          <div style={{ fontSize: '11px', color: Tfv2.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            {jobs.length} analysis jobs tracked. {completed.length} completed with <b style={{ color: Tfv2.color.text.primary }}>{totalFindings} total findings</b>. {jobs.filter(j => j.status === 'In Progress').length} currently in progress.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Total jobs</span><span style={esi.statValue}>{jobs.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Completed</span><span style={{ ...esi.statValue, color: esi.emerald }}>{completed.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>In progress</span><span style={{ ...esi.statValue, color: esi.cyan }}>{jobs.filter(j => j.status === 'In Progress').length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Total findings</span><span style={{ ...esi.statValue, color: esi.amber }}>{totalFindings}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Anti-forensics</span><span style={{ ...esi.statValue, color: esi.emerald }}>0</span><span style={{ ...esi.statDelta, color: Tfv2.color.text.tertiary }}>none detected</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}>
          <span>Analysis jobs — {rows.length} of {jobs.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tfv2.color.border.light}`, borderRadius: '5px', background: Tfv2.color.bg.card, color: Tfv2.color.text.secondary }}>
              {statuses.map(s => <option key={s} value={s}>Status: {s}</option>)}
            </select>
            <button style={{ ...esi.btnPrimary, background: esi.teal }}>+ New analysis</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={esi.th}>Job</th><th style={esi.th}>Image</th><th style={esi.th}>Custodian</th><th style={esi.th}>Type</th>
            <th style={esi.th}>Priority</th><th style={esi.th}>Examiner</th><th style={esi.th}>Started</th><th style={esi.th}>Completed</th>
            <th style={{ ...esi.th, textAlign: 'right' }}>Hits</th><th style={{ ...esi.th, textAlign: 'right' }}>Findings</th><th style={esi.th}>Status</th>
          </tr></thead>
          <tbody>
            {rows.map(j => {
              const pc = priorityColor(j.priority);
              const ss = esi.statusColor(j.status);
              return (
                <tr key={j.id}>
                  <td style={{ ...esi.td, fontFamily: Tfv2.font.mono, fontWeight: 700, color: esi.teal }}>{j.id}</td>
                  <td style={{ ...esi.td, fontFamily: Tfv2.font.mono, color: Tfv2.color.text.secondary, fontSize: '11px' }}>{j.imageId}</td>
                  <td style={{ ...esi.td, color: Tfv2.color.text.primary, fontWeight: 600 }}>{j.custodian}</td>
                  <td style={esi.td}><span style={{ fontSize: '11px', color: Tfv2.color.text.primary }}>{typeIcon(j.type)} {j.type}</span></td>
                  <td style={esi.td}><span style={{ ...esi.tag, background: `${pc}14`, color: pc }}>{j.priority}</span></td>
                  <td style={{ ...esi.td, color: Tfv2.color.text.secondary, fontSize: '11px' }}>{j.examiner}</td>
                  <td style={{ ...esi.td, fontFamily: Tfv2.font.mono, fontSize: '11px', color: Tfv2.color.text.tertiary }}>{j.started}</td>
                  <td style={{ ...esi.td, fontFamily: Tfv2.font.mono, fontSize: '11px', color: j.completed ? esi.emerald : Tfv2.color.text.tertiary }}>{j.completed || '—'}</td>
                  <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tfv2.font.mono, color: Tfv2.color.text.primary, fontWeight: 700 }}>{j.hits != null ? j.hits.toLocaleString() : '—'}</td>
                  <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tfv2.font.mono, color: j.findings > 0 ? esi.amber : Tfv2.color.text.tertiary, fontWeight: 700 }}>{j.findings != null ? j.findings : '—'}</td>
                  <td style={esi.td}><span style={{ ...esi.tag, background: ss.bg, color: ss.color }}>{j.status}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
        <div style={{ padding: '8px 16px' }}>
          {rows.filter(j => j.note).map(j => (
            <div key={j.id} style={{ fontSize: '11px', color: Tfv2.color.text.secondary, padding: '3px 0' }}>
              <span style={{ fontFamily: Tfv2.font.mono, color: esi.teal, fontWeight: 700 }}>{j.id}</span> — {j.note}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function ForensicsTimeline({ data }) {
  const esi = window.__esi;
  const f = data.forensics;
  const events = f.timeline;
  const sevColor = (s) => ({ critical: esi.crimson, warn: esi.amber, info: esi.cyan }[s] || esi.slate);
  const typeIcon = (t) => ({ 'Logon': '', 'USB Insert': '', 'USB Remove': '', 'File Copy': '', 'File Delete': '', 'Trash Empty': '', 'iMessage': '', 'WhatsApp': '', 'Location': '', 'Draft Created': '' }[t] || '◆');

  return (
    <div>
      <div style={{ ...esi.card, borderLeft: `3px solid ${esi.amber}`, background: esi.amberBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: esi.amber, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Forensic timeline — reconstructed device events across all images</div>
          <div style={{ fontSize: '11px', color: Tfv2.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            {events.length} events reconstructed from {new Set(events.map(e => e.imageId)).size} forensic images spanning {new Set(events.map(e => e.custodian)).size} custodians. Events sorted chronologically with severity color coding.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Events</span><span style={esi.statValue}>{events.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Critical</span><span style={{ ...esi.statValue, color: esi.crimson }}>{events.filter(e => e.severity === 'critical').length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Warnings</span><span style={{ ...esi.statValue, color: esi.amber }}>{events.filter(e => e.severity === 'warn').length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Custodians</span><span style={esi.statValue}>{new Set(events.map(e => e.custodian)).size}</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}><span>Reconstructed timeline — {events.length} events</span><button style={esi.btnSecondary}>Export timeline</button></div>
        <div style={{ padding: '4px 0' }}>
          {events.map((e, i) => {
            const sc = sevColor(e.severity);
            return (
              <div key={e.id} style={{ padding: '10px 16px', borderBottom: i === events.length - 1 ? 'none' : `1px solid ${Tfv2.color.border.light}`, display: 'flex', gap: '12px', alignItems: 'start' }}>
                <div style={{ width: '4px', minHeight: '36px', borderRadius: '2px', background: sc, flexShrink: 0, marginTop: '2px' }} />
                <div style={{ minWidth: '130px' }}>
                  <div style={{ fontFamily: Tfv2.font.mono, fontSize: '11px', fontWeight: 700, color: sc }}>{e.ts}</div>
                  <div style={{ fontSize: '10px', color: Tfv2.color.text.tertiary, marginTop: '2px' }}>{e.custodian}</div>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', gap: '6px', alignItems: 'center', marginBottom: '2px' }}>
                    <span style={{ ...esi.tag, background: `${sc}14`, color: sc }}>{typeIcon(e.eventType)} {e.eventType}</span>
                    <span style={{ fontFamily: Tfv2.font.mono, fontSize: '10px', color: Tfv2.color.text.tertiary }}>{e.imageId}</span>
                  </div>
                  <div style={{ fontSize: '12px', color: Tfv2.color.text.primary, fontWeight: 500 }}>{e.detail}</div>
                  <div style={{ fontSize: '10px', color: Tfv2.color.text.tertiary, marginTop: '2px' }}>{e.device}</div>
                </div>
                <span style={{ ...esi.tag, background: `${sc}14`, color: sc, flexShrink: 0 }}>{e.severity}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function ForensicsLabOps({ data }) {
  const esi = window.__esi;
  const f = data.forensics;
  const lab = f.labOps;
  const totalCost = lab.tools.reduce((s, t) => s + t.annualCost, 0);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Examiners</span><span style={esi.statValue}>{lab.examiners.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Active jobs</span><span style={{ ...esi.statValue, color: esi.cyan }}>{lab.examiners.reduce((s, e) => s + e.activeJobs, 0)}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Tools licensed</span><span style={esi.statValue}>{lab.tools.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Annual tool cost</span><span style={esi.statValue}>{esi.money(totalCost)}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Queue depth</span><span style={{ ...esi.statValue, color: esi.amber }}>{lab.queue.length}</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '14px', marginBottom: '14px' }}>
        {lab.examiners.map(ex => (
          <div key={ex.id} style={{ ...esi.card, marginBottom: 0 }}>
            <div style={{ padding: '12px 16px', borderBottom: `1px solid ${Tfv2.color.border.light}`, background: esi.tealBg }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <div style={{ fontSize: '14px', fontWeight: 700, color: Tfv2.color.text.primary }}>{ex.name}</div>
                  <div style={{ fontSize: '11px', color: Tfv2.color.text.tertiary }}>{ex.org} · {ex.specialty}</div>
                </div>
                <span style={{ ...esi.tag, background: ex.activeJobs > 0 ? esi.cyanBg : esi.emeraldBg, color: ex.activeJobs > 0 ? esi.cyan : esi.emerald }}>{ex.activeJobs > 0 ? `${ex.activeJobs} active` : 'available'}</span>
              </div>
            </div>
            <div style={{ padding: '12px 16px' }}>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px', marginBottom: '10px' }}>
                {ex.certs.map(c => <span key={c} style={{ ...esi.tag, background: esi.violetBg, color: esi.violet }}>{c}</span>)}
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '10px' }}>
                <div><span style={{ fontSize: '10px', color: Tfv2.color.text.tertiary, textTransform: 'uppercase' }}>Completed YTD</span><div style={{ fontFamily: Tfv2.font.mono, fontWeight: 700, color: Tfv2.color.text.primary }}>{ex.completedYTD}</div></div>
                <div><span style={{ fontSize: '10px', color: Tfv2.color.text.tertiary, textTransform: 'uppercase' }}>Utilization</span><div style={{ fontFamily: Tfv2.font.mono, fontWeight: 700, color: ex.utilization > 80 ? esi.amber : esi.emerald }}>{ex.utilization}%</div></div>
              </div>
              <div style={{ height: '6px', background: Tfv2.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                <div style={{ width: `${ex.utilization}%`, height: '100%', background: ex.utilization > 80 ? esi.amber : esi.emerald }} />
              </div>
            </div>
          </div>
        ))}
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}><span>Tool licenses — {lab.tools.length}</span><button style={esi.btnSecondary}>+ Add license</button></div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={esi.th}>ID</th><th style={esi.th}>Tool</th><th style={esi.th}>Version</th><th style={esi.th}>Type</th>
            <th style={{ ...esi.th, textAlign: 'right' }}>Seats</th><th style={{ ...esi.th, textAlign: 'right' }}>In use</th>
            <th style={esi.th}>License expiry</th><th style={{ ...esi.th, textAlign: 'right' }}>Annual cost</th><th style={esi.th}>Status</th>
          </tr></thead>
          <tbody>
            {lab.tools.map(t => (
              <tr key={t.id}>
                <td style={{ ...esi.td, fontFamily: Tfv2.font.mono, fontWeight: 700, color: esi.teal }}>{t.id}</td>
                <td style={{ ...esi.td, fontWeight: 600, color: Tfv2.color.text.primary }}>{t.name}</td>
                <td style={{ ...esi.td, fontFamily: Tfv2.font.mono, fontSize: '11px', color: Tfv2.color.text.tertiary }}>{t.version}</td>
                <td style={esi.td}><span style={{ ...esi.tag, background: esi.cyanBg, color: esi.cyan }}>{t.type}</span></td>
                <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tfv2.font.mono, color: Tfv2.color.text.primary }}>{t.seats || '∞'}</td>
                <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tfv2.font.mono, color: esi.cyan, fontWeight: 700 }}>{t.inUse}</td>
                <td style={{ ...esi.td, fontFamily: Tfv2.font.mono, fontSize: '11px', color: Tfv2.color.text.tertiary }}>{t.licenseExpiry}</td>
                <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tfv2.font.mono, color: Tfv2.color.text.primary, fontWeight: 700 }}>{t.annualCost > 0 ? esi.money(t.annualCost) : 'Free'}</td>
                <td style={esi.td}><span style={{ ...esi.tag, background: esi.emeraldBg, color: esi.emerald }}>{t.status}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {lab.queue.length > 0 && (
        <div style={{ ...esi.card, marginTop: '14px' }}>
          <div style={esi.cardH}><span>Imaging queue — {lab.queue.length} pending</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr>
              <th style={esi.th}>ID</th><th style={esi.th}>Custodian</th><th style={esi.th}>Device</th><th style={esi.th}>Type</th>
              <th style={esi.th}>Priority</th><th style={esi.th}>Assigned</th><th style={esi.th}>Scheduled</th><th style={esi.th}>Note</th>
            </tr></thead>
            <tbody>
              {lab.queue.map(q => (
                <tr key={q.id}>
                  <td style={{ ...esi.td, fontFamily: Tfv2.font.mono, fontWeight: 700, color: esi.teal }}>{q.id}</td>
                  <td style={{ ...esi.td, fontWeight: 600, color: Tfv2.color.text.primary }}>{q.custodian}</td>
                  <td style={{ ...esi.td, color: Tfv2.color.text.secondary, fontSize: '11px' }}>{q.device}</td>
                  <td style={{ ...esi.td, color: Tfv2.color.text.secondary, fontSize: '11px' }}>{q.type}</td>
                  <td style={esi.td}><span style={{ ...esi.tag, background: esi.amberBg, color: esi.amber }}>{q.priority}</span></td>
                  <td style={{ ...esi.td, color: Tfv2.color.text.secondary, fontSize: '11px' }}>{q.assignedTo}</td>
                  <td style={{ ...esi.td, fontFamily: Tfv2.font.mono, fontSize: '11px', color: esi.amber }}>{q.scheduledDate}</td>
                  <td style={{ ...esi.td, color: Tfv2.color.text.tertiary, fontSize: '11px' }}>{q.note}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

window.ForensicsAnalysis = ForensicsAnalysis;
window.ForensicsTimeline = ForensicsTimeline;
window.ForensicsLabOps = ForensicsLabOps;
