// ESI FORENSICS — Views Part 1: Overview · Images · Artifacts
const { useState: useFV1State, useMemo: useFV1Memo } = React;
const Tfv1 = window.ArbiterTokens;

function ForensicsOverview({ data }) {
  const esi = window.__esi;
  const f = data.forensics;
  const k = f.kpis;
  const imaged = data.forensicImages.filter(i => i.status === 'Imaged');
  const deviceTypes = {};
  data.forensicImages.forEach(i => {
    const t = i.device.includes('iPhone') || i.device.includes('Android') ? 'Mobile' : 'Computer';
    deviceTypes[t] = (deviceTypes[t] || 0) + 1;
  });
  const maxUtil = Math.max(...f.labOps.examiners.map(e => e.utilization));

  return (
    <div>
      <div style={{ ...esi.card, borderLeft: `3px solid ${esi.teal}`, background: esi.tealBg }}>
        <div style={{ padding: '14px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: '13px', fontWeight: 700, color: esi.teal, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Digital Forensics Laboratory — ISO 27037 · NIST SP 800-86/101 · Daubert Compliant</div>
            <div style={{ fontSize: '12px', color: Tfv1.color.text.secondary, marginTop: '6px', lineHeight: 1.55 }}>
              <b style={{ color: Tfv1.color.text.primary }}>{k.totalImages} forensic images</b> across {data.forensicImages.length} devices. <b style={{ fontFamily: Tfv1.font.mono, color: esi.teal }}>{esi.bytes(k.storageGB)}</b> total storage. <b>{k.artifactsExtracted.toLocaleString()}</b> artifacts extracted with <b style={{ color: esi.emerald }}>zero anti-forensics detections</b>.
            </div>
          </div>
          <div style={{ display: 'flex', gap: '6px', flexShrink: 0 }}>
            <button style={esi.btnSecondary}>Export report</button>
            <button style={{ ...esi.btnPrimary, background: esi.teal }}>+ New image</button>
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(8, 1fr)', gap: '10px', marginBottom: '14px' }}>
        {[
          { l: 'Images', v: k.totalImages, d: `${k.imaged} imaged`, c: null },
          { l: 'Storage', v: esi.bytes(k.storageGB), d: 'E01 + FFS', c: null },
          { l: 'Artifacts', v: k.artifactsExtracted.toLocaleString(), d: 'extracted', c: esi.teal },
          { l: 'Analyses', v: k.analysisJobs, d: `${k.activeAnalyses} active`, c: esi.cyan },
          { l: 'Findings', v: f.analysisJobs.filter(j=>j.findings).reduce((s,j)=>s+(j.findings||0),0), d: 'total', c: esi.amber },
          { l: 'Examiners', v: k.examiners, d: `${k.labUtilization}% util`, c: null },
          { l: 'Reports', v: k.reportsGenerated, d: `${k.reportsPending} pending`, c: esi.violet },
          { l: 'Compliance', v: `${k.complianceScore}%`, d: `${k.standardsCovered} standards`, c: esi.emerald },
        ].map(s => (
          <div key={s.l} style={esi.stat}>
            <span style={esi.statLabel}>{s.l}</span>
            <span style={{ ...esi.statValue, color: s.c || Tfv1.color.text.primary }}>{s.v}</span>
            <span style={{ ...esi.statDelta, color: Tfv1.color.text.tertiary }}>{s.d}</span>
          </div>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px', marginBottom: '14px' }}>
        <div style={esi.card}>
          <div style={esi.cardH}>Device type distribution</div>
          <div style={{ padding: '14px 16px' }}>
            {Object.entries(deviceTypes).map(([type, count]) => (
              <div key={type} style={{ marginBottom: '10px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '4px' }}>
                  <span style={{ color: Tfv1.color.text.primary, fontWeight: 500 }}>{type === 'Mobile' ? ' Mobile devices' : ' Computers'}</span>
                  <span style={{ fontFamily: Tfv1.font.mono, color: esi.teal, fontWeight: 700 }}>{count}</span>
                </div>
                <div style={{ height: '12px', background: Tfv1.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                  <div style={{ width: `${(count / data.forensicImages.length) * 100}%`, height: '100%', background: `linear-gradient(90deg, ${esi.teal}, ${esi.cyan})` }} />
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={esi.card}>
          <div style={esi.cardH}>Examiner workload</div>
          <div style={{ padding: '14px 16px' }}>
            {f.labOps.examiners.map(ex => (
              <div key={ex.id} style={{ marginBottom: '10px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '4px' }}>
                  <span style={{ color: Tfv1.color.text.primary, fontWeight: 500 }}>{ex.name} <span style={{ color: Tfv1.color.text.tertiary, fontSize: '10px' }}>({ex.org})</span></span>
                  <span style={{ fontFamily: Tfv1.font.mono, color: ex.utilization > 80 ? esi.amber : esi.emerald, fontWeight: 700 }}>{ex.utilization}%</span>
                </div>
                <div style={{ height: '8px', background: Tfv1.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                  <div style={{ width: `${ex.utilization}%`, height: '100%', background: ex.utilization > 80 ? esi.amber : esi.emerald }} />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}><span>Recent forensic activity</span><span style={{ fontSize: '10px', color: Tfv1.color.text.tertiary }}>{f.audit.length} events</span></div>
        <div style={{ padding: '4px 0' }}>
          {f.audit.slice(0, 6).map((a, i) => (
            <div key={a.id} style={{ padding: '8px 16px', borderBottom: i === 5 ? 'none' : `1px solid ${Tfv1.color.border.light}`, display: 'grid', gridTemplateColumns: '90px 1fr auto', gap: '12px', alignItems: 'center' }}>
              <span style={{ fontFamily: Tfv1.font.mono, fontSize: '11px', fontWeight: 700, color: esi.teal }}>{a.id}</span>
              <div>
                <div style={{ fontSize: '12px', color: Tfv1.color.text.primary, fontWeight: 500 }}>{a.detail}</div>
                <div style={{ fontSize: '10px', color: Tfv1.color.text.tertiary, marginTop: '1px' }}>{a.actor} · {a.action}</div>
              </div>
              <span style={{ fontFamily: Tfv1.font.mono, fontSize: '10px', color: Tfv1.color.text.tertiary }}>{a.ts}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function ForensicsImages({ data }) {
  const esi = window.__esi;
  const [statusFilter, setStatusFilter] = useFV1State('All');
  const [deviceFilter, setDeviceFilter] = useFV1State('All');
  const images = data.forensicImages;
  const statuses = ['All', ...new Set(images.map(f => f.status))];
  const deviceTypes = ['All', 'Mobile', 'Computer'];
  const imaged = images.filter(f => f.status === 'Imaged');
  const totalGB = imaged.reduce((s, f) => s + (f.storageGB || 0), 0);

  const deviceStyle = (device) => {
    const d = device.toLowerCase();
    if (d.includes('iphone') || d.includes('ipad') || d.includes('android')) return esi.sourceStyle('Mobile');
    if (d.includes('macbook') || d.includes('dell') || d.includes('lenovo')) return esi.sourceStyle('Laptop');
    return esi.sourceStyle('Other');
  };
  const isMobile = (d) => d.toLowerCase().includes('iphone') || d.toLowerCase().includes('android');

  const filtered = images.filter(f => {
    if (statusFilter !== 'All' && f.status !== statusFilter) return false;
    if (deviceFilter === 'Mobile' && !isMobile(f.device)) return false;
    if (deviceFilter === 'Computer' && isMobile(f.device)) return false;
    return true;
  });

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Forensic images</span><span style={esi.statValue}>{images.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Imaged</span><span style={{ ...esi.statValue, color: esi.teal }}>{imaged.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Queued</span><span style={{ ...esi.statValue, color: esi.amber }}>{images.filter(f => f.status === 'Queued').length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Storage</span><span style={esi.statValue}>{esi.bytes(totalGB)}</span><span style={{ ...esi.statDelta, color: Tfv1.color.text.tertiary }}>E01 + FFS</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Hash verified</span><span style={{ ...esi.statValue, color: esi.emerald }}>{imaged.length}</span><span style={{ ...esi.statDelta, color: Tfv1.color.text.tertiary }}>SHA-256</span></div>
      </div>

      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
        <span style={{ fontSize: '12px', fontWeight: 600, color: Tfv1.color.text.primary }}>Showing {filtered.length} of {images.length} images</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 ${Tfv1.color.border.light}`, borderRadius: '5px', background: Tfv1.color.bg.card, color: Tfv1.color.text.secondary }}>
            {statuses.map(s => <option key={s}>Status: {s}</option>)}
          </select>
          <select value={deviceFilter} onChange={e => setDeviceFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tfv1.color.border.light}`, borderRadius: '5px', background: Tfv1.color.bg.card, color: Tfv1.color.text.secondary }}>
            {deviceTypes.map(t => <option key={t} value={t}>Device: {t}</option>)}
          </select>
          <button style={esi.btnSecondary}>Export CSV</button>
          <button style={{ ...esi.btnPrimary, background: esi.teal }}>+ New image</button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(440px, 1fr))', gap: '14px' }}>
        {filtered.map(f => {
          const ds = deviceStyle(f.device);
          const ss = esi.statusColor(f.status);
          return (
            <div key={f.id} style={{ ...esi.card, marginBottom: 0 }}>
              <div style={{ padding: '12px 14px', borderBottom: `1px solid ${Tfv1.color.border.light}`, background: `linear-gradient(135deg, ${ds.bg} 0%, transparent 100%)` }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
                  <span style={{ ...esi.tag, background: ds.bg, color: ds.color, fontSize: '11px', padding: '3px 10px' }}>{ds.icon} {f.device}</span>
                  <span style={{ ...esi.tag, background: ss.bg, color: ss.color }}>{f.status}</span>
                </div>
                <div style={{ fontSize: '13px', fontWeight: 700, color: Tfv1.color.text.primary, marginTop: '2px' }}>{f.custodian}</div>
                <div style={{ fontSize: '10px', fontFamily: Tfv1.font.mono, color: Tfv1.color.text.tertiary, marginTop: '2px' }}>{f.id} · serial {f.serialNum}</div>
              </div>
              <div style={{ padding: '12px 14px' }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '10px' }}>
                  <div><div style={{ fontSize: '9px', color: Tfv1.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Method</div><div style={{ fontSize: '11px', fontWeight: 500, color: Tfv1.color.text.primary, marginTop: '2px' }}>{f.method}</div></div>
                  <div><div style={{ fontSize: '9px', color: Tfv1.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Storage</div><div style={{ fontSize: '13px', fontWeight: 700, color: esi.teal, fontFamily: Tfv1.font.mono }}>{esi.bytes(f.storageGB)}</div></div>
                </div>
                <div style={{ fontSize: '9px', color: Tfv1.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>Artifacts extracted</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px', marginBottom: '10px' }}>
                  {f.artifactTypes.length > 0 ? f.artifactTypes.map(a => <span key={a} style={{ ...esi.tag, background: Tfv1.color.bg.secondary, color: Tfv1.color.text.secondary }}>{a}</span>) : <span style={{ fontSize: '10px', color: Tfv1.color.text.tertiary, fontStyle: 'italic' }}>pending imaging</span>}
                </div>
                <div style={{ paddingTop: '10px', borderTop: `1px solid ${Tfv1.color.border.light}` }}>
                  <div style={{ fontSize: '9px', color: Tfv1.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '3px' }}>SHA-256</div>
                  <div style={{ fontFamily: Tfv1.font.mono, fontSize: '11px', color: esi.emerald, fontWeight: 600, wordBreak: 'break-all' }}>{f.hashSHA256}</div>
                </div>
                <div style={{ marginTop: '8px', fontSize: '10px', color: Tfv1.color.text.tertiary, display: 'flex', justifyContent: 'space-between' }}>
                  <span>{f.imagedBy}</span><span style={{ fontFamily: Tfv1.font.mono }}>{f.imagedOn}</span>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function ForensicsArtifacts({ data }) {
  const esi = window.__esi;
  const f = data.forensics;
  const [typeFilter, setTypeFilter] = useFV1State('All');
  const [custFilter, setCustFilter] = useFV1State('All');
  const types = ['All', ...new Set(f.artifacts.map(a => a.type))];
  const custs = ['All', ...new Set(f.artifacts.map(a => a.custodian))];
  const rows = f.artifacts.filter(a => (typeFilter === 'All' || a.type === typeFilter) && (custFilter === 'All' || a.custodian === custFilter));
  const totalCount = rows.reduce((s, a) => s + a.count, 0);
  const flaggedCount = rows.reduce((s, a) => s + a.flagged, 0);

  const typeColor = (t) => {
    const m = { 'iMessage': esi.cobalt, 'WhatsApp': esi.emerald, 'Call Logs': esi.slate, 'Location History': esi.amber, 'Browser History': esi.cyan, 'Deleted Files': esi.crimson, 'Keychain': esi.violet, 'Email Cache': esi.orange, 'Email': esi.cobalt, 'File System': esi.slate, 'Registry': esi.amber, 'Event Logs': esi.teal, 'Slack': esi.violet };
    return m[t] || esi.slate;
  };

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Artifact records</span><span style={esi.statValue}>{rows.length}</span><span style={{ ...esi.statDelta, color: Tfv1.color.text.tertiary }}>of {f.artifacts.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Total items</span><span style={{ ...esi.statValue, color: esi.teal }}>{totalCount.toLocaleString()}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Flagged</span><span style={{ ...esi.statValue, color: esi.crimson }}>{flaggedCount}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Evidentiary</span><span style={{ ...esi.statValue, color: esi.emerald }}>{rows.filter(a => a.evidentiary).length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Types</span><span style={esi.statValue}>{new Set(rows.map(a => a.type)).size}</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}>
          <span>Extracted artifact registry — {rows.length} records</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <select value={typeFilter} onChange={e => setTypeFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tfv1.color.border.light}`, borderRadius: '5px', background: Tfv1.color.bg.card, color: Tfv1.color.text.secondary }}>
              {types.map(t => <option key={t} value={t}>Type: {t}</option>)}
            </select>
            <select value={custFilter} onChange={e => setCustFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tfv1.color.border.light}`, borderRadius: '5px', background: Tfv1.color.bg.card, color: Tfv1.color.text.secondary }}>
              {custs.map(c => <option key={c} value={c}>Custodian: {c}</option>)}
            </select>
            <button style={esi.btnSecondary}>Export CSV</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={esi.th}>ID</th><th style={esi.th}>Image</th><th style={esi.th}>Custodian</th><th style={esi.th}>Device</th>
            <th style={esi.th}>Type</th><th style={{ ...esi.th, textAlign: 'right' }}>Count</th><th style={esi.th}>Date range</th>
            <th style={esi.th}>Evid.</th><th style={{ ...esi.th, textAlign: 'right' }}>Flagged</th><th style={esi.th}>Note</th>
          </tr></thead>
          <tbody>
            {rows.map(a => {
              const tc = typeColor(a.type);
              return (
                <tr key={a.id}>
                  <td style={{ ...esi.td, fontFamily: Tfv1.font.mono, fontWeight: 700, color: esi.teal }}>{a.id}</td>
                  <td style={{ ...esi.td, fontFamily: Tfv1.font.mono, color: Tfv1.color.text.secondary, fontSize: '11px' }}>{a.imageId}</td>
                  <td style={{ ...esi.td, color: Tfv1.color.text.primary, fontWeight: 600 }}>{a.custodian}</td>
                  <td style={{ ...esi.td, color: Tfv1.color.text.secondary, fontSize: '11px' }}>{a.device}</td>
                  <td style={esi.td}><span style={{ ...esi.tag, background: `${tc}14`, color: tc }}>{a.type}</span></td>
                  <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tfv1.font.mono, color: Tfv1.color.text.primary, fontWeight: 700 }}>{a.count.toLocaleString()}</td>
                  <td style={{ ...esi.td, fontFamily: Tfv1.font.mono, fontSize: '10px', color: Tfv1.color.text.tertiary }}>{a.dateRange}</td>
                  <td style={esi.td}>{a.evidentiary ? <span style={{ ...esi.tag, background: esi.emeraldBg, color: esi.emerald }}>ok yes</span> : <span style={{ ...esi.tag, background: Tfv1.color.bg.secondary, color: Tfv1.color.text.tertiary }}>no</span>}</td>
                  <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tfv1.font.mono, color: a.flagged > 0 ? esi.crimson : Tfv1.color.text.tertiary, fontWeight: a.flagged > 0 ? 700 : 400 }}>{a.flagged}</td>
                  <td style={{ ...esi.td, color: Tfv1.color.text.secondary, fontSize: '11px', maxWidth: '280px' }}>{a.note}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.ForensicsOverview = ForensicsOverview;
window.ForensicsImages = ForensicsImages;
window.ForensicsArtifacts = ForensicsArtifacts;
