// ESI FORENSICS — Views Part 3: Reports · Compliance · Audit + Main Platform Entry
const { useState: useFV3State } = React;
const Tfv3 = window.ArbiterTokens;

function ForensicsReports({ data }) {
  const esi = window.__esi;
  const f = data.forensics;
  const reports = f.reports;
  const final = reports.filter(r => r.status === 'Final');

  return (
    <div>
      <div style={{ ...esi.card, borderLeft: `3px solid ${esi.violet}`, background: esi.violetBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: esi.violet, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Forensic examination reports — court-admissible under Daubert + FRE 702</div>
          <div style={{ fontSize: '11px', color: Tfv3.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            {reports.length} examination reports. {final.length} finalized with Daubert-compliant methodology documentation. All final reports include examiner credentials, methodology, error rates, and peer review attestation.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Total reports</span><span style={esi.statValue}>{reports.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Final</span><span style={{ ...esi.statValue, color: esi.emerald }}>{final.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>In progress</span><span style={{ ...esi.statValue, color: esi.cyan }}>{reports.filter(r => r.status === 'In Progress').length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Total findings</span><span style={{ ...esi.statValue, color: esi.amber }}>{final.reduce((s, r) => s + (r.findings || 0), 0)}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Court-admissible</span><span style={{ ...esi.statValue, color: esi.emerald }}>{final.filter(r => r.courtAdmissible).length}</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}><span>Examination reports — {reports.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}><button style={esi.btnSecondary}>Export manifest</button><button style={{ ...esi.btnPrimary, background: esi.teal }}>+ Generate report</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}>Title</th>
            <th style={esi.th}>Examiner</th><th style={esi.th}>Issued</th><th style={{ ...esi.th, textAlign: 'right' }}>Findings</th>
            <th style={esi.th}>Methodology</th><th style={esi.th}>Admissibility</th><th style={esi.th}>Status</th>
          </tr></thead>
          <tbody>
            {reports.map(r => {
              const ss = esi.statusColor(r.status === 'Final' ? 'Complete' : r.status);
              return (
                <tr key={r.id}>
                  <td style={{ ...esi.td, fontFamily: Tfv3.font.mono, fontWeight: 700, color: esi.violet }}>{r.id}</td>
                  <td style={{ ...esi.td, fontFamily: Tfv3.font.mono, color: Tfv3.color.text.secondary, fontSize: '11px' }}>{r.imageId}</td>
                  <td style={{ ...esi.td, color: Tfv3.color.text.primary, fontWeight: 600 }}>{r.custodian}</td>
                  <td style={{ ...esi.td, color: Tfv3.color.text.primary, fontSize: '11px', maxWidth: '280px' }}>{r.title}</td>
                  <td style={{ ...esi.td, color: Tfv3.color.text.secondary, fontSize: '11px' }}>{r.examiner}</td>
                  <td style={{ ...esi.td, fontFamily: Tfv3.font.mono, fontSize: '11px', color: r.dateIssued ? Tfv3.color.text.tertiary : esi.amber }}>{r.dateIssued || 'pending'}</td>
                  <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tfv3.font.mono, color: r.findings > 0 ? esi.amber : Tfv3.color.text.tertiary, fontWeight: 700 }}>{r.findings != null ? r.findings : '—'}</td>
                  <td style={{ ...esi.td, fontSize: '10px', color: Tfv3.color.text.secondary }}>{r.methodology}</td>
                  <td style={esi.td}>
                    {r.courtAdmissible ? (
                      <div style={{ display: 'flex', gap: '3px', flexWrap: 'wrap' }}>
                        {r.daubert && <span style={{ ...esi.tag, background: esi.emeraldBg, color: esi.emerald }}>Daubert</span>}
                        {r.fre702 && <span style={{ ...esi.tag, background: esi.emeraldBg, color: esi.emerald }}>FRE 702</span>}
                      </div>
                    ) : <span style={{ ...esi.tag, background: Tfv3.color.bg.secondary, color: Tfv3.color.text.tertiary }}>pending</span>}
                  </td>
                  <td style={esi.td}><span style={{ ...esi.tag, background: ss.bg, color: ss.color }}>{r.status}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ForensicsCompliance({ data }) {
  const esi = window.__esi;
  const f = data.forensics;
  const standards = f.compliance;
  const avgCoverage = (standards.reduce((s, st) => s + st.coverage, 0) / standards.length).toFixed(1);
  const totalFindings = standards.reduce((s, st) => s + st.findings, 0);

  return (
    <div>
      <div style={{ ...esi.card, borderLeft: `3px solid ${esi.emerald}`, background: esi.emeraldBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: esi.emerald, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Forensic compliance — {standards.length} standards · {avgCoverage}% average coverage</div>
          <div style={{ fontSize: '11px', color: Tfv3.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            All forensic methods validated against international standards. <b style={{ color: Tfv3.color.text.primary }}>{totalFindings} total finding{totalFindings !== 1 ? 's' : ''}</b> across all audits. Examiner credentials verified and current.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Standards</span><span style={esi.statValue}>{standards.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Avg coverage</span><span style={{ ...esi.statValue, color: esi.emerald }}>{avgCoverage}%</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Open findings</span><span style={{ ...esi.statValue, color: totalFindings === 0 ? esi.emerald : esi.amber }}>{totalFindings}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Last audit</span><span style={{ ...esi.statValue, fontSize: '14px' }}>{standards[0]?.lastAudit || '—'}</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}><span>Standards coverage — {standards.length}</span><button style={esi.btnSecondary}>Download audit report</button></div>
        <div style={{ padding: '16px' }}>
          {standards.map(st => (
            <div key={st.code} style={{ marginBottom: '14px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '4px' }}>
                <div><span style={{ fontWeight: 700, color: Tfv3.color.text.primary }}>{st.code}</span><span style={{ color: Tfv3.color.text.secondary, marginLeft: '8px' }}>{st.title}</span></div>
                <div style={{ display: 'flex', gap: '12px', alignItems: 'center' }}>
                  <span style={{ fontFamily: Tfv3.font.mono, fontSize: '11px', color: Tfv3.color.text.tertiary }}>Audit: {st.lastAudit} ({st.auditor})</span>
                  <span style={{ ...esi.tag, background: st.findings === 0 ? esi.emeraldBg : esi.amberBg, color: st.findings === 0 ? esi.emerald : esi.amber }}>{st.findings} finding{st.findings !== 1 ? 's' : ''}</span>
                  <span style={{ fontFamily: Tfv3.font.mono, fontWeight: 700, color: st.coverage === 100 ? esi.emerald : esi.amber, minWidth: '42px', textAlign: 'right' }}>{st.coverage}%</span>
                </div>
              </div>
              <div style={{ height: '10px', background: Tfv3.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                <div style={{ width: `${st.coverage}%`, height: '100%', background: st.coverage === 100 ? `linear-gradient(90deg, ${esi.emerald}, ${esi.teal})` : esi.amber }} />
              </div>
            </div>
          ))}
        </div>
      </div>

      <div style={{ ...esi.card, marginTop: '14px' }}>
        <div style={esi.cardH}>Examiner credentials matrix</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={esi.th}>Examiner</th><th style={esi.th}>Organization</th><th style={esi.th}>Certifications</th>
            <th style={esi.th}>Specialty</th><th style={{ ...esi.th, textAlign: 'right' }}>Cases YTD</th><th style={esi.th}>Status</th>
          </tr></thead>
          <tbody>
            {f.labOps.examiners.map(ex => (
              <tr key={ex.id}>
                <td style={{ ...esi.td, fontWeight: 600, color: Tfv3.color.text.primary }}>{ex.name}</td>
                <td style={{ ...esi.td, color: Tfv3.color.text.secondary, fontSize: '11px' }}>{ex.org}</td>
                <td style={esi.td}><div style={{ display: 'flex', gap: '3px', flexWrap: 'wrap' }}>{ex.certs.map(c => <span key={c} style={{ ...esi.tag, background: esi.violetBg, color: esi.violet }}>{c}</span>)}</div></td>
                <td style={{ ...esi.td, color: Tfv3.color.text.secondary, fontSize: '11px' }}>{ex.specialty}</td>
                <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tfv3.font.mono, fontWeight: 700 }}>{ex.completedYTD}</td>
                <td style={esi.td}><span style={{ ...esi.tag, background: esi.emeraldBg, color: esi.emerald }}>ok current</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function ForensicsAudit({ data }) {
  const esi = window.__esi;
  const f = data.forensics;
  const rows = f.audit;
  const actionColor = (a) => {
    if (a.includes('COMPLETE') || a.includes('ISSUED') || a.includes('VERIFY')) return esi.emerald;
    if (a.includes('START') || a.includes('EXPORT')) return esi.cyan;
    return esi.teal;
  };

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Audit entries</span><span style={esi.statValue}>{rows.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Warnings</span><span style={{ ...esi.statValue, color: rows.filter(r => r.severity === 'warn').length > 0 ? esi.amber : esi.emerald }}>{rows.filter(r => r.severity === 'warn').length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Signatures</span><span style={{ ...esi.statValue, color: esi.emerald }}>{rows.filter(r => r.sig.includes('ok')).length}</span><span style={{ ...esi.statDelta, color: Tfv3.color.text.tertiary }}>all verified</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Actors</span><span style={esi.statValue}>{new Set(rows.map(r => r.actor)).size}</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}><span>Forensic audit trail — {rows.length} entries</span>
          <div style={{ display: 'flex', gap: '6px' }}><button style={esi.btnSecondary}>Export log</button></div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={esi.th}>ID</th><th style={esi.th}>Timestamp</th><th style={esi.th}>Actor</th><th style={esi.th}>Action</th>
            <th style={esi.th}>Target</th><th style={esi.th}>Detail</th><th style={esi.th}>Severity</th><th style={esi.th}>Signature</th>
          </tr></thead>
          <tbody>
            {rows.map(r => {
              const ac = actionColor(r.action);
              const sevStyle = r.severity === 'warn' ? { bg: esi.amberBg, color: esi.amber } : { bg: esi.cyanBg, color: esi.cyan };
              return (
                <tr key={r.id}>
                  <td style={{ ...esi.td, fontFamily: Tfv3.font.mono, fontWeight: 700, color: esi.teal }}>{r.id}</td>
                  <td style={{ ...esi.td, fontFamily: Tfv3.font.mono, fontSize: '11px', color: Tfv3.color.text.tertiary }}>{r.ts}</td>
                  <td style={{ ...esi.td, color: Tfv3.color.text.primary, fontWeight: 500 }}>{r.actor}</td>
                  <td style={esi.td}><span style={{ ...esi.tag, background: `${ac}14`, color: ac }}>{r.action}</span></td>
                  <td style={{ ...esi.td, fontFamily: Tfv3.font.mono, color: esi.violet, fontWeight: 700 }}>{r.target}</td>
                  <td style={{ ...esi.td, color: Tfv3.color.text.secondary, fontSize: '11px', maxWidth: '360px' }}>{r.detail}</td>
                  <td style={esi.td}><span style={{ ...esi.tag, background: sevStyle.bg, color: sevStyle.color }}>{r.severity}</span></td>
                  <td style={esi.td}><span style={{ ...esi.tag, background: esi.emeraldBg, color: esi.emerald }}>{r.sig}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── MAIN PLATFORM ENTRY ──────────────────────────────────────────────────────
function ESIForensicsPlatform({ data }) {
  const esi = window.__esi;
  const [activeView, setActiveView] = useFV3State('overview');

  const views = [
    { id: 'overview', label: 'Overview' },
    { id: 'images', label: 'Images' },
    { id: 'artifacts', label: 'Artifacts' },
    { id: 'analysis', label: 'Analysis' },
    { id: 'timeline', label: 'Timeline' },
    { id: 'labops', label: 'Lab Ops' },
    { id: 'reports', label: 'Reports' },
    { id: 'compliance', label: 'Compliance' },
    { id: 'audit', label: 'Audit Trail' },
  ];

  const renderView = () => {
    switch (activeView) {
      case 'overview': return <ForensicsOverview data={data} />;
      case 'images': return <ForensicsImages data={data} />;
      case 'artifacts': return <ForensicsArtifacts data={data} />;
      case 'analysis': return <ForensicsAnalysis data={data} />;
      case 'timeline': return <ForensicsTimeline data={data} />;
      case 'labops': return <ForensicsLabOps data={data} />;
      case 'reports': return <ForensicsReports data={data} />;
      case 'compliance': return <ForensicsCompliance data={data} />;
      case 'audit': return <ForensicsAudit data={data} />;
      default: return <ForensicsOverview data={data} />;
    }
  };

  return (
    <div>
      <div style={{
        display: 'flex', gap: '4px', padding: '6px',
        background: Tfv3.color.bg.secondary,
        border: `1px solid ${Tfv3.color.border.light}`,
        borderRadius: '8px', marginBottom: '16px', flexWrap: 'wrap',
      }}>
        {views.map(v => (
          <button key={v.id} onClick={() => setActiveView(v.id)} style={{
            padding: '6px 12px', fontSize: '11px', fontWeight: activeView === v.id ? 700 : 500,
            borderRadius: '6px', border: 'none', cursor: 'pointer',
            background: activeView === v.id ? esi.teal : 'transparent',
            color: activeView === v.id ? '#fff' : Tfv3.color.text.secondary,
            fontFamily: Tfv3.font.family, transition: 'all .15s',
          }}>{v.label}</button>
        ))}
      </div>
      {renderView()}
    </div>
  );
}

window.ForensicsReports = ForensicsReports;
window.ForensicsCompliance = ForensicsCompliance;
window.ForensicsAudit = ForensicsAudit;
window.ESIForensicsPlatform = ESIForensicsPlatform;
