// ESI PLATFORM — Chain of Custody sub-platform
// Enterprise-grade: Overview · Ledger · Integrity · Transfers · Seals · Attestations · Exports · Compliance · Audit
const { useState: useChainState, useMemo: useChainMemo } = React;
const Tchain = window.ArbiterTokens;

// ─── Shared sub-view shell ────────────────────────────────────────────────────
function ChainSubNav({ active, onChange }) {
  const esi = window.__esi;
  const views = [
    { id: 'overview',     label: 'Overview' },
    { id: 'ledger',       label: 'Ledger' },
    { id: 'integrity',    label: 'Integrity · Hashes' },
    { id: 'transfers',    label: 'Transfers' },
    { id: 'seals',        label: 'Seals' },
    { id: 'attestations', label: 'Attestations' },
    { id: 'exports',      label: 'Court Exports' },
    { id: 'compliance',   label: 'Compliance' },
    { id: 'audit',        label: 'Audit Trail' },
  ];
  return (
    <div style={{
      display: 'flex', gap: '4px', padding: '6px',
      background: Tchain.color.bg.secondary,
      border: `1px solid ${Tchain.color.border.light}`,
      borderRadius: '8px', marginBottom: '16px', flexWrap: 'wrap',
    }}>
      {views.map(v => {
        const isActive = active === v.id;
        return (
          <button key={v.id} onClick={() => onChange(v.id)} style={{
            padding: '6px 12px', fontSize: '11px', fontWeight: isActive ? 700 : 500,
            borderRadius: '6px', border: 'none', cursor: 'pointer',
            background: isActive ? esi.violet : 'transparent',
            color: isActive ? '#fff' : Tchain.color.text.secondary,
            fontFamily: Tchain.font.family, transition: 'all .15s',
          }}>{v.label}</button>
        );
      })}
    </div>
  );
}

// ─── Helpers ──────────────────────────────────────────────────────────────────
const Mono = ({ children, color, size = '11px', weight = 500 }) => (
  <span style={{ fontFamily: Tchain.font.mono, fontSize: size, fontWeight: weight, color }}>{children}</span>
);

function Hash({ value }) {
  if (!value) return <Mono color={Tchain.color.text.tertiary}>—</Mono>;
  const short = value.length > 16 ? `${value.slice(0, 8)}…${value.slice(-6)}` : value;
  return <Mono color={Tchain.color.text.secondary} size="10px">{short}</Mono>;
}

function Badge({ color, bg, children, mono = false }) {
  return <span style={{ display: 'inline-flex', alignItems: 'center', padding: '2px 8px', borderRadius: '10px', fontSize: '10px', fontWeight: 700, background: bg, color, fontFamily: mono ? Tchain.font.mono : Tchain.font.family, letterSpacing: '0.02em' }}>{children}</span>;
}

function Divider({ label, color }) {
  const esi = window.__esi;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '10px', margin: '4px 0 10px' }}>
      <div style={{ width: '3px', height: '14px', background: color || esi.violet, borderRadius: '2px' }} />
      <div style={{ fontSize: '11px', fontWeight: 700, color: color || esi.violet, textTransform: 'uppercase', letterSpacing: '0.08em' }}>{label}</div>
    </div>
  );
}

// ─── 1. OVERVIEW ──────────────────────────────────────────────────────────────
function ChainOverview({ data }) {
  const esi = window.__esi;
  const k = data.chainKpis;
  const tenRecent = data.chainOfCustody.slice(0, 6);

  // transfer method distribution
  const methodCounts = {};
  data.chainOfCustody.forEach(c => { methodCounts[c.transferMethod] = (methodCounts[c.transferMethod] || 0) + 1; });
  const methodBars = Object.entries(methodCounts).sort((a, b) => b[1] - a[1]).slice(0, 5);
  const maxMethod = Math.max(...methodBars.map(m => m[1]));

  // volume-by-actor-role
  const roleVol = {};
  data.chainOfCustody.forEach(c => { roleVol[c.actorRole] = (roleVol[c.actorRole] || 0) + (c.volumeGB || 0); });
  const roleBars = Object.entries(roleVol).sort((a, b) => b[1] - a[1]);
  const maxRole = Math.max(...roleBars.map(r => r[1]));

  return (
    <div>
      {/* Hero compliance banner */}
      <div style={{ ...esi.card, borderLeft: `3px solid ${esi.violet}`, background: esi.violetBg }}>
        <div style={{ padding: '14px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: '16px' }}>
          <div>
            <div style={{ fontSize: '13px', fontWeight: 700, color: esi.violet, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Court-admissible chain of custody — ISO 27050-2 · FRE 901/902 compliant</div>
            <div style={{ fontSize: '12px', color: Tchain.color.text.secondary, marginTop: '6px', lineHeight: 1.55 }}>
              Every transfer end-to-end <b style={{ color: Tchain.color.text.primary }}>SHA-256 hashed</b> and witnessed. Tamper-evident seals applied at every node. <b>Zero integrity failures</b> year-to-date across <b style={{ fontFamily: Tchain.font.mono, color: esi.violet }}>{k.totalEvents}</b> events and <b style={{ fontFamily: Tchain.font.mono, color: esi.violet }}>{esi.bytes(k.volumeTrackedGB)}</b> tracked volume.
            </div>
          </div>
          <div style={{ display: 'flex', gap: '6px', flexShrink: 0 }}>
            <button style={{ ...esi.btnSecondary }}>Download court bundle</button>
            <button style={{ ...esi.btnPrimary, background: esi.violet }}>+ Record event</button>
          </div>
        </div>
      </div>

      {/* KPI strip — 8 metrics */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(8, 1fr)', gap: '10px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Events (total)</span><span style={esi.statValue}>{k.totalEvents}</span><span style={{ ...esi.statDelta, color: esi.violet, fontFamily: Tchain.font.mono }}>+{k.eventsMTD} MTD</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Hash verified</span><span style={{ ...esi.statValue, color: esi.emerald }}>{k.hashVerifiedPct.toFixed(1)}%</span><span style={{ ...esi.statDelta, color: Tchain.color.text.tertiary }}>{k.hashAlgorithm}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Integrity failures</span><span style={{ ...esi.statValue, color: k.integrityFailures === 0 ? esi.emerald : esi.crimson }}>{k.integrityFailures}</span><span style={{ ...esi.statDelta, color: Tchain.color.text.tertiary }}>YTD</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Volume tracked</span><span style={esi.statValue}>{esi.bytes(k.volumeTrackedGB)}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Seals active</span><span style={{ ...esi.statValue, color: esi.cobalt }}>{k.sealsActive}</span><span style={{ ...esi.statDelta, color: Tchain.color.text.tertiary }}>{k.sealsBroken} broken</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Transfers in flight</span><span style={{ ...esi.statValue, color: esi.cyan }}>{k.transfersInFlight}</span><span style={{ ...esi.statDelta, color: Tchain.color.text.tertiary }}>{k.transfersCompleted} complete</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Attestations</span><span style={{ ...esi.statValue, color: esi.teal }}>{k.attestationsSigned}</span><span style={{ ...esi.statDelta, color: esi.amber }}>{k.attestationsPending} pending</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Court exports</span><span style={esi.statValue}>{k.exportsPrepared}</span><span style={{ ...esi.statDelta, color: esi.emerald }}>{k.exportsCourtReady} court-ready</span></div>
      </div>

      {/* Compliance posture strip */}
      <div style={{ ...esi.card, marginBottom: '14px' }}>
        <div style={esi.cardH}>Compliance posture</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '10px', padding: '14px 16px' }}>
          {[
            { label: 'Daubert',      value: k.daubert,       color: esi.emerald },
            { label: 'FRE 901',       value: k.fre901,        color: esi.emerald },
            { label: 'FRE 902(14)',   value: k.fre902,        color: esi.emerald },
            { label: 'ISO 27050-2',   value: 'Compliant',     color: esi.emerald },
            { label: 'Audit findings',value: `${k.auditFindings} open`, color: k.auditFindings === 0 ? esi.emerald : esi.amber },
          ].map(p => (
            <div key={p.label} style={{ padding: '10px 12px', borderRadius: '6px', background: `${p.color}0f`, border: `1px solid ${p.color}22` }}>
              <div style={{ fontSize: '10px', fontWeight: 700, color: Tchain.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '2px' }}>{p.label}</div>
              <div style={{ fontSize: '13px', fontWeight: 700, color: p.color, fontFamily: Tchain.font.family }}>{p.value}</div>
            </div>
          ))}
        </div>
        <div style={{ padding: '10px 16px 12px', borderTop: `1px solid ${Tchain.color.border.light}`, fontSize: '11px', color: Tchain.color.text.secondary }}>
          Last audit <b style={{ color: Tchain.color.text.primary, fontFamily: Tchain.font.mono }}>{k.lastAuditDate}</b> · next audit <b style={{ color: esi.violet, fontFamily: Tchain.font.mono }}>{k.nextAuditDate}</b> · auditor <b>BSI</b>
        </div>
      </div>

      {/* Two-column: method distribution + actor role volume */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px', marginBottom: '14px' }}>
        <div style={esi.card}>
          <div style={esi.cardH}>Transfer method distribution</div>
          <div style={{ padding: '14px 16px' }}>
            {methodBars.map(([method, count]) => (
              <div key={method} style={{ marginBottom: '10px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', marginBottom: '4px' }}>
                  <span style={{ color: Tchain.color.text.primary, fontWeight: 500 }}>{method}</span>
                  <Mono color={esi.violet} weight={700}>{count}</Mono>
                </div>
                <div style={{ height: '10px', background: Tchain.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                  <div style={{ width: `${(count / maxMethod) * 100}%`, height: '100%', background: `linear-gradient(90deg, ${esi.violet}, ${esi.cobalt})` }} />
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={esi.card}>
          <div style={esi.cardH}>Volume handled by actor role</div>
          <div style={{ padding: '14px 16px' }}>
            {roleBars.map(([role, vol]) => (
              <div key={role} style={{ marginBottom: '10px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', marginBottom: '4px' }}>
                  <span style={{ color: Tchain.color.text.primary, fontWeight: 500 }}>{role}</span>
                  <Mono color={esi.cyan} weight={700}>{esi.bytes(vol)}</Mono>
                </div>
                <div style={{ height: '10px', background: Tchain.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                  <div style={{ width: `${(vol / maxRole) * 100}%`, height: '100%', background: `linear-gradient(90deg, ${esi.cyan}, ${esi.teal})` }} />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Recent events + compliance sidecar */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: '14px' }}>
        <div style={esi.card}>
          <div style={esi.cardH}>
            <span>Recent chain events</span>
            <span style={{ fontSize: '10px', color: Tchain.color.text.tertiary }}>{tenRecent.length} of {data.chainOfCustody.length}</span>
          </div>
          <div style={{ padding: '4px 0' }}>
            {tenRecent.map((c, i) => (
              <div key={c.id} style={{ padding: '10px 16px', borderBottom: i === tenRecent.length - 1 ? 'none' : `1px solid ${Tchain.color.border.light}`, display: 'grid', gridTemplateColumns: '84px 1fr auto auto', gap: '12px', alignItems: 'center' }}>
                <Mono color={esi.violet} weight={700} size="11px">{c.id}</Mono>
                <div>
                  <div style={{ fontSize: '12px', color: Tchain.color.text.primary, fontWeight: 500 }}>{c.from} → {c.to}</div>
                  <div style={{ fontSize: '10px', color: Tchain.color.text.tertiary, marginTop: '2px' }}>{c.custodian} · {c.actor}</div>
                </div>
                <Mono color={Tchain.color.text.primary} weight={700}>{esi.bytes(c.volumeGB)}</Mono>
                {c.hashVerified
                  ? <Badge color={esi.emerald} bg={esi.emeraldBg}>ok verified</Badge>
                  : <Badge color={esi.crimson} bg={esi.crimsonBg}>! pending</Badge>}
              </div>
            ))}
          </div>
        </div>

        <div style={{ ...esi.card, borderLeft: `3px solid ${esi.violet}` }}>
          <div style={esi.cardH}>What you can prove in court</div>
          <div style={{ padding: '12px 16px', fontSize: '11px', color: Tchain.color.text.secondary, lineHeight: 1.65 }}>
            <div style={{ marginBottom: '10px' }}>Every data transfer in this matter is:</div>
            {[
              'End-to-end SHA-256 hashed',
              'Witnessed by ≥ 1 attested actor',
              'Sealed (physical or cryptographic)',
              'Logged with immutable audit entry',
              'Declared under FRE 902(14)',
            ].map(item => (
              <div key={item} style={{ display: 'flex', alignItems: 'start', gap: '8px', marginBottom: '6px' }}>
                <span style={{ color: esi.emerald, fontWeight: 700 }}><Icons.Check size={11}/></span>
                <span>{item}</span>
              </div>
            ))}
            <div style={{ marginTop: '10px', paddingTop: '10px', borderTop: `1px solid ${Tchain.color.border.light}`, fontSize: '11px', color: Tchain.color.text.tertiary }}>
              <b style={{ color: esi.violet }}>Daubert-ready</b>: methods peer-reviewed, published, and with known error rates.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── 2. LEDGER ────────────────────────────────────────────────────────────────
function ChainLedger({ data }) {
  const esi = window.__esi;
  const [q, setQ] = useChainState('');
  const [fromFilter, setFromFilter] = useChainState('All');
  const [verifiedOnly, setVerifiedOnly] = useChainState(false);
  const [selected, setSelected] = useChainState(null);

  const fromTypes = useChainMemo(() => ['All', ...new Set(data.chainOfCustody.map(c => c.fromType))], [data]);

  const rows = useChainMemo(() => data.chainOfCustody.filter(c => {
    const blob = `${c.id} ${c.from} ${c.to} ${c.custodian} ${c.actor} ${c.note}`.toLowerCase();
    if (q && !blob.includes(q.toLowerCase())) return false;
    if (fromFilter !== 'All' && c.fromType !== fromFilter) return false;
    if (verifiedOnly && !c.hashVerified) return false;
    return true;
  }), [data, q, fromFilter, verifiedOnly]);

  const totalVol = rows.reduce((s, r) => s + (r.volumeGB || 0), 0);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Events shown</span><span style={esi.statValue}>{rows.length}</span><span style={{ ...esi.statDelta, color: Tchain.color.text.tertiary }}>of {data.chainOfCustody.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Volume (filtered)</span><span style={esi.statValue}>{esi.bytes(totalVol)}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Hash verified</span><span style={{ ...esi.statValue, color: esi.emerald }}>{rows.filter(r => r.hashVerified).length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Distinct 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, gap: '8px' }}>
          <span>Custody ledger</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <input
              placeholder="Search id, custodian, source, actor…"
              value={q} onChange={e => setQ(e.target.value)}
              style={{ padding: '4px 10px', fontSize: '11px', border: `1px solid ${Tchain.color.border.light}`, borderRadius: '5px', background: Tchain.color.bg.card, color: Tchain.color.text.primary, width: '260px' }}
            />
            <select value={fromFilter} onChange={e => setFromFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tchain.color.border.light}`, borderRadius: '5px', background: Tchain.color.bg.card, color: Tchain.color.text.secondary }}>
              {fromTypes.map(t => <option key={t} value={t}>Source: {t}</option>)}
            </select>
            <label style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '11px', color: Tchain.color.text.secondary, padding: '0 8px' }}>
              <input type="checkbox" checked={verifiedOnly} onChange={e => setVerifiedOnly(e.target.checked)} />
              verified only
            </label>
            <button style={esi.btnSecondary}>Export CSV</button>
            <button style={{ ...esi.btnPrimary, background: esi.violet }}>Export for court</button>
          </div>
        </div>

        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={esi.th}>Chain ID</th>
              <th style={esi.th}>Date / time</th>
              <th style={esi.th}>From</th>
              <th style={esi.th}>To</th>
              <th style={esi.th}>Custodian / Scope</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>Volume</th>
              <th style={esi.th}>Actor / Role</th>
              <th style={esi.th}>Method</th>
              <th style={esi.th}>Seal</th>
              <th style={esi.th}>Hash</th>
              <th style={esi.th}></th>
            </tr>
          </thead>
          <tbody>
            {rows.map(c => {
              const isSel = selected === c.id;
              return (
                <React.Fragment key={c.id}>
                  <tr onClick={() => setSelected(isSel ? null : c.id)} style={{ cursor: 'pointer', background: isSel ? esi.violetBg : 'transparent' }}>
                    <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontWeight: 700, color: esi.violet }}>{c.id}</td>
                    <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontSize: '11px', color: Tchain.color.text.tertiary }}>{c.date}</td>
                    <td style={{ ...esi.td, fontSize: '11px', maxWidth: '160px' }}>
                      <div style={{ color: Tchain.color.text.primary, fontWeight: 500 }}>{c.from}</div>
                      <div style={{ color: Tchain.color.text.tertiary, fontSize: '10px' }}>{c.fromType}</div>
                    </td>
                    <td style={{ ...esi.td, fontSize: '11px', maxWidth: '160px' }}>
                      <div style={{ color: Tchain.color.text.primary, fontWeight: 500 }}>{c.to}</div>
                      <div style={{ color: Tchain.color.text.tertiary, fontSize: '10px' }}>{c.toType}</div>
                    </td>
                    <td style={{ ...esi.td, color: Tchain.color.text.secondary, fontSize: '11px' }}>{c.custodian}</td>
                    <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tchain.font.mono, color: Tchain.color.text.primary, fontWeight: 700 }}>{esi.bytes(c.volumeGB)}</td>
                    <td style={{ ...esi.td, fontSize: '11px' }}>
                      <div style={{ color: Tchain.color.text.primary, fontWeight: 500 }}>{c.actor}</div>
                      <div style={{ color: Tchain.color.text.tertiary, fontSize: '10px' }}>{c.actorRole}</div>
                    </td>
                    <td style={{ ...esi.td, color: Tchain.color.text.secondary, fontSize: '11px' }}>{c.transferMethod}</td>
                    <td style={esi.td}><Mono color={esi.cobalt} weight={700}>{c.sealId}</Mono></td>
                    <td style={esi.td}>
                      {c.hashVerified
                        ? <Badge color={esi.emerald} bg={esi.emeraldBg}>ok {c.hashAlgo}</Badge>
                        : <Badge color={esi.crimson} bg={esi.crimsonBg}>pending</Badge>}
                    </td>
                    <td style={{ ...esi.td, textAlign: 'right' }}>
                      <span style={{ fontSize: '11px', color: esi.violet, fontWeight: 600 }}>{isSel ? '− collapse' : '+ expand'}</span>
                    </td>
                  </tr>
                  {isSel && (
                    <tr>
                      <td colSpan={11} style={{ padding: 0, background: esi.violetBg }}>
                        <div style={{ padding: '14px 20px', borderTop: `1px solid ${esi.violet}33`, borderBottom: `1px solid ${esi.violet}33` }}>
                          <Divider label="Event detail" color={esi.violet} />
                          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '20px', marginBottom: '14px' }}>
                            <div>
                              <div style={{ fontSize: '10px', fontWeight: 700, color: Tchain.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Hash integrity</div>
                              <div style={{ fontSize: '11px', color: Tchain.color.text.secondary, lineHeight: 1.7 }}>
                                <div>Algorithm: <b style={{ color: Tchain.color.text.primary, fontFamily: Tchain.font.mono }}>{c.hashAlgo}</b></div>
                                <div>Pre: <Hash value={c.preHash} /></div>
                                <div>Post: <Hash value={c.postHash} /></div>
                                <div>Match: {c.hashVerified ? <Badge color={esi.emerald} bg={esi.emeraldBg}>VERIFIED</Badge> : <Badge color={esi.crimson} bg={esi.crimsonBg}>PENDING</Badge>}</div>
                              </div>
                            </div>
                            <div>
                              <div style={{ fontSize: '10px', fontWeight: 700, color: Tchain.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Witnesses & signatures</div>
                              <div style={{ fontSize: '11px', color: Tchain.color.text.secondary, lineHeight: 1.7 }}>
                                <div>Actor: <b style={{ color: Tchain.color.text.primary }}>{c.actor}</b> ({c.actorRole})</div>
                                <div>Witness: <b style={{ color: Tchain.color.text.primary }}>{c.witness}</b></div>
                                <div>Signature: <Badge color={esi.cobalt} bg={esi.cobaltBg}>{c.sig}</Badge></div>
                                <div>Seal: <Mono color={esi.cobalt} weight={700}>{c.sealId}</Mono></div>
                              </div>
                            </div>
                            <div>
                              <div style={{ fontSize: '10px', fontWeight: 700, color: Tchain.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Links</div>
                              <div style={{ fontSize: '11px', color: Tchain.color.text.secondary, lineHeight: 1.7 }}>
                                <div>Source: <Mono color={esi.cyan} weight={700}>{c.sourceId}</Mono></div>
                                <div>Collection: <Mono color={esi.cyan} weight={700}>{c.linkedCollection}</Mono></div>
                                <div>Doc count: <Mono color={Tchain.color.text.primary} weight={700}>{c.docCount ? c.docCount.toLocaleString() : '—'}</Mono></div>
                                <div>Volume: <Mono color={Tchain.color.text.primary} weight={700}>{esi.bytes(c.volumeGB)}</Mono></div>
                              </div>
                            </div>
                          </div>
                          <div style={{ fontSize: '11px', color: Tchain.color.text.secondary, lineHeight: 1.5, paddingTop: '10px', borderTop: `1px solid ${esi.violet}22` }}>
                            <b style={{ color: esi.violet }}>Note:</b> {c.note}
                          </div>
                        </div>
                      </td>
                    </tr>
                  )}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── 3. INTEGRITY ─────────────────────────────────────────────────────────────
function ChainIntegrity({ data }) {
  const esi = window.__esi;
  const rows = data.chainIntegrity;
  const matched = rows.filter(r => r.match).length;
  const totalBytes = rows.reduce((s, r) => s + r.bytesHashed, 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' }}>◆ Hash integrity — {matched} of {rows.length} verified</div>
          <div style={{ fontSize: '11px', color: Tchain.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            SHA-256 computed at source and re-verified at destination for every transfer. <b>{(totalBytes / 1_073_741_824).toFixed(1)} GB</b> hashed across this matter with zero mismatches.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Records</span><span style={esi.statValue}>{rows.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Matched</span><span style={{ ...esi.statValue, color: esi.emerald }}>{matched}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Mismatches</span><span style={{ ...esi.statValue, color: rows.length - matched === 0 ? esi.emerald : esi.crimson }}>{rows.length - matched}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Bytes hashed</span><span style={esi.statValue}>{(totalBytes / 1_073_741_824).toFixed(1)} GB</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}>
          <span>Hash registry — {rows.length} records</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <button style={esi.btnSecondary}>Re-verify all</button>
            <button style={esi.btnSecondary}>Export hash manifest</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={esi.th}>Record</th>
              <th style={esi.th}>Chain</th>
              <th style={esi.th}>Date</th>
              <th style={esi.th}>Algo</th>
              <th style={esi.th}>Pre-transfer hash</th>
              <th style={esi.th}>Post-transfer hash</th>
              <th style={esi.th}>Match</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>Bytes</th>
              <th style={esi.th}>Duration</th>
              <th style={esi.th}>Verifier</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(r => (
              <tr key={r.id}>
                <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontWeight: 700, color: esi.emerald }}>{r.id}</td>
                <td style={{ ...esi.td, fontFamily: Tchain.font.mono, color: esi.violet, fontWeight: 700 }}>{r.chainId}</td>
                <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontSize: '11px', color: Tchain.color.text.tertiary }}>{r.date}</td>
                <td style={esi.td}><Badge color={esi.cobalt} bg={esi.cobaltBg} mono>{r.algorithm}</Badge></td>
                <td style={esi.td}><Hash value={r.preHash} /></td>
                <td style={esi.td}><Hash value={r.postHash} /></td>
                <td style={esi.td}>{r.match
                  ? <Badge color={esi.emerald} bg={esi.emeraldBg}>ok MATCH</Badge>
                  : <Badge color={esi.crimson} bg={esi.crimsonBg}>x MISMATCH</Badge>}</td>
                <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tchain.font.mono, color: Tchain.color.text.primary, fontWeight: 500 }}>{(r.bytesHashed / 1_073_741_824).toFixed(2)} GB</td>
                <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontSize: '11px', color: Tchain.color.text.tertiary }}>{r.duration}</td>
                <td style={{ ...esi.td, fontSize: '11px', color: Tchain.color.text.secondary }}>{r.verifier}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── 4. TRANSFERS ─────────────────────────────────────────────────────────────
function ChainTransfers({ data }) {
  const esi = window.__esi;
  const inFlight = data.chainTransfers;

  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' }}>◆ Active transfers — {inFlight.length} in flight</div>
          <div style={{ fontSize: '11px', color: Tchain.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Every transfer — physical or logical — is tracked with tamper-evident controls and streaming SHA-256 hash. Couriers are bonded; APIs are TLS 1.3.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>In flight</span><span style={{ ...esi.statValue, color: esi.cyan }}>{inFlight.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Completed YTD</span><span style={esi.statValue}>{data.chainKpis.transfersCompleted}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Bonded couriers</span><span style={esi.statValue}>{data.chainCouriers.filter(c => c.type === 'Bonded courier' || c.type.includes('forensicist') || c.type === 'Forensic Collector').length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Failed transfers</span><span style={{ ...esi.statValue, color: esi.emerald }}>0</span><span style={{ ...esi.statDelta, color: Tchain.color.text.tertiary }}>YTD</span></div>
      </div>

      {/* Active transfers — detailed cards */}
      <Divider label="In-flight transfers" color={esi.cyan} />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '14px', marginBottom: '14px' }}>
        {inFlight.map(t => (
          <div key={t.id} style={{ ...esi.card, borderLeft: `3px solid ${esi.cyan}`, marginBottom: 0 }}>
            <div style={{ ...esi.cardH, background: esi.cyanBg, color: esi.cyan }}>
              <span>{t.id} <span style={{ color: Tchain.color.text.tertiary, fontWeight: 400 }}>→ chain {t.chainId}</span></span>
              <Badge color={esi.cyan} bg="rgba(255,255,255,0.7)">{t.status}</Badge>
            </div>
            <div style={{ padding: '14px 16px' }}>
              <div style={{ fontSize: '12px', color: Tchain.color.text.primary, marginBottom: '10px' }}>
                <b>{t.from}</b> → <b>{t.to}</b>
                <div style={{ fontSize: '11px', color: Tchain.color.text.tertiary, marginTop: '2px' }}>Method: {t.method} · Courier: {t.courier}</div>
              </div>
              <div style={{ marginBottom: '10px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', color: Tchain.color.text.tertiary, marginBottom: '4px', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                  <span>Progress</span>
                  <Mono color={esi.cyan} weight={700}>{t.progressPct}%</Mono>
                </div>
                <div style={{ height: '8px', background: Tchain.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                  <div style={{ width: `${t.progressPct}%`, height: '100%', background: `linear-gradient(90deg, ${esi.cyan}, ${esi.teal})` }} />
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', fontSize: '11px' }}>
                <div><span style={{ color: Tchain.color.text.tertiary }}>Custodian</span><div style={{ color: Tchain.color.text.primary, fontWeight: 500 }}>{t.custodian}</div></div>
                <div><span style={{ color: Tchain.color.text.tertiary }}>Volume (est.)</span><div><Mono color={Tchain.color.text.primary} weight={700}>{esi.bytes(t.etaVolumeGB)}</Mono></div></div>
                <div><span style={{ color: Tchain.color.text.tertiary }}>Started</span><div><Mono color={Tchain.color.text.secondary}>{t.started}</Mono></div></div>
                <div><span style={{ color: Tchain.color.text.tertiary }}>ETA</span><div><Mono color={esi.amber} weight={700}>{t.eta}</Mono></div></div>
              </div>
              <div style={{ marginTop: '10px', paddingTop: '10px', borderTop: `1px solid ${Tchain.color.border.light}`, fontSize: '11px', color: Tchain.color.text.secondary }}>
                <b style={{ color: esi.cobalt }}>Integrity:</b> {t.integrity} — <i>{t.note}</i>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Couriers directory */}
      <Divider label="Bonded couriers & collectors" color={esi.cobalt} />
      <div style={esi.card}>
        <div style={esi.cardH}>
          <span>Courier directory — {data.chainCouriers.length}</span>
          <button style={esi.btnSecondary}>+ Add courier</button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={esi.th}>ID</th>
              <th style={esi.th}>Name</th>
              <th style={esi.th}>Organization</th>
              <th style={esi.th}>Type</th>
              <th style={esi.th}>License</th>
              <th style={esi.th}>Insured</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>Active</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>YTD</th>
              <th style={esi.th}>Note</th>
            </tr>
          </thead>
          <tbody>
            {data.chainCouriers.map(c => (
              <tr key={c.id}>
                <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontWeight: 700, color: esi.cobalt }}>{c.id}</td>
                <td style={{ ...esi.td, color: Tchain.color.text.primary, fontWeight: 600 }}>{c.name}</td>
                <td style={{ ...esi.td, color: Tchain.color.text.secondary, fontSize: '11px' }}>{c.org}</td>
                <td style={esi.td}><Badge color={esi.cobalt} bg={esi.cobaltBg}>{c.type}</Badge></td>
                <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontSize: '11px', color: Tchain.color.text.secondary }}>{c.license}</td>
                <td style={{ ...esi.td, fontFamily: Tchain.font.mono, color: esi.emerald, fontSize: '11px' }}>{c.insured}</td>
                <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tchain.font.mono, color: c.activeTransfers > 0 ? esi.cyan : Tchain.color.text.tertiary, fontWeight: 700 }}>{c.activeTransfers}</td>
                <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tchain.font.mono, color: Tchain.color.text.primary }}>{c.completedYTD}</td>
                <td style={{ ...esi.td, fontSize: '11px', color: Tchain.color.text.tertiary, maxWidth: '260px' }}>{c.note}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── 5. SEALS ─────────────────────────────────────────────────────────────────
function ChainSeals({ data }) {
  const esi = window.__esi;
  const seals = data.chainSeals;
  const intact = seals.filter(s => s.status === 'Intact').length;
  const broken = seals.filter(s => s.status.includes('Opened') || s.status === 'Broken').length;

  const statusStyle = (s) => {
    if (s === 'Intact') return { bg: esi.emeraldBg, color: esi.emerald };
    if (s === 'Broken') return { bg: esi.crimsonBg, color: esi.crimson };
    return { bg: esi.amberBg, color: esi.amber };
  };

  return (
    <div>
      <div style={{ ...esi.card, borderLeft: `3px solid ${esi.cobalt}`, background: esi.cobaltBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: esi.cobalt, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Evidence seals & containers — tamper-evident controls</div>
          <div style={{ fontSize: '11px', color: Tchain.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Physical seals (tamper-evident, ultrasonic) and cryptographic seals (PGP, TLS, signed ZIP) applied to every container. Broken seals trigger re-hash + witness 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 seals</span><span style={esi.statValue}>{seals.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Intact</span><span style={{ ...esi.statValue, color: esi.emerald }}>{intact}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Broken / re-sealed</span><span style={{ ...esi.statValue, color: esi.amber }}>{broken}</span><span style={{ ...esi.statDelta, color: Tchain.color.text.tertiary }}>all witnessed</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Physical</span><span style={esi.statValue}>{seals.filter(s => s.type === 'Physical').length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Logical</span><span style={esi.statValue}>{seals.filter(s => s.type === 'Logical').length}</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}>
          <span>Seal registry — {seals.length}</span>
          <button style={esi.btnSecondary}>+ Apply seal</button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={esi.th}>Seal</th>
              <th style={esi.th}>Type</th>
              <th style={esi.th}>Material / Mechanism</th>
              <th style={esi.th}>Container</th>
              <th style={esi.th}>Chain</th>
              <th style={esi.th}>Sealed on</th>
              <th style={esi.th}>Sealed by</th>
              <th style={esi.th}>Location</th>
              <th style={esi.th}>Status</th>
              <th style={esi.th}>Notes</th>
            </tr>
          </thead>
          <tbody>
            {seals.map(s => {
              const ss = statusStyle(s.status);
              return (
                <tr key={s.id}>
                  <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontWeight: 700, color: esi.cobalt }}>{s.id}</td>
                  <td style={esi.td}><Badge color={s.type === 'Physical' ? esi.amber : esi.cobalt} bg={s.type === 'Physical' ? esi.amberBg : esi.cobaltBg}>{s.type}</Badge></td>
                  <td style={{ ...esi.td, color: Tchain.color.text.secondary, fontSize: '11px' }}>{s.material}</td>
                  <td style={{ ...esi.td, color: Tchain.color.text.primary, fontSize: '11px', maxWidth: '200px' }}>{s.container}</td>
                  <td style={{ ...esi.td, fontFamily: Tchain.font.mono, color: esi.violet, fontWeight: 700 }}>{s.chainId}</td>
                  <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontSize: '11px', color: Tchain.color.text.tertiary }}>{s.sealedOn}</td>
                  <td style={{ ...esi.td, color: Tchain.color.text.secondary, fontSize: '11px' }}>{s.sealedBy}</td>
                  <td style={{ ...esi.td, color: Tchain.color.text.tertiary, fontSize: '11px' }}>{s.location}</td>
                  <td style={esi.td}><Badge color={ss.color} bg={ss.bg}>{s.status}</Badge></td>
                  <td style={{ ...esi.td, color: Tchain.color.text.secondary, fontSize: '11px', maxWidth: '280px' }}>{s.note}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── 6. ATTESTATIONS ──────────────────────────────────────────────────────────
function ChainAttestations({ data }) {
  const esi = window.__esi;
  const [statusFilter, setStatusFilter] = useChainState('All');
  const att = data.chainAttestations;
  const statuses = ['All', ...new Set(att.map(a => a.status))];
  const rows = att.filter(a => statusFilter === 'All' || a.status === statusFilter);

  const signed = att.filter(a => a.status === 'Signed').length;
  const pending = att.filter(a => a.status === 'Pending').length;

  return (
    <div>
      <div style={{ ...esi.card, borderLeft: `3px solid ${esi.teal}`, background: esi.tealBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: esi.teal, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Custodian attestations — sworn declarations</div>
          <div style={{ fontSize: '11px', color: Tchain.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Notarized affidavits from custodians, collectors, and records custodians. FRE 902(14) self-authenticating declarations attached to every production bundle.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Total attestations</span><span style={esi.statValue}>{att.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Signed</span><span style={{ ...esi.statValue, color: esi.emerald }}>{signed}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Pending</span><span style={{ ...esi.statValue, color: esi.amber }}>{pending}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Types in use</span><span style={esi.statValue}>{new Set(att.map(a => a.type)).size}</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}>
          <span>Attestation registry — {rows.length} of {att.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 ${Tchain.color.border.light}`, borderRadius: '5px', background: Tchain.color.bg.card, color: Tchain.color.text.secondary }}>
              {statuses.map(s => <option key={s}>Status: {s}</option>)}
            </select>
            <button style={esi.btnSecondary}>Generate declaration</button>
            <button style={{ ...esi.btnPrimary, background: esi.teal }}>+ Send notice</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={esi.th}>ID</th>
              <th style={esi.th}>Custodian / Affiant</th>
              <th style={esi.th}>Role</th>
              <th style={esi.th}>Type</th>
              <th style={esi.th}>Status</th>
              <th style={esi.th}>Signed on</th>
              <th style={esi.th}>Notary</th>
              <th style={esi.th}>Exhibit</th>
              <th style={esi.th}>Linked chains</th>
              <th style={esi.th}>Note</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(a => (
              <tr key={a.id}>
                <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontWeight: 700, color: esi.teal }}>{a.id}</td>
                <td style={{ ...esi.td, color: Tchain.color.text.primary, fontWeight: 600 }}>{a.custodian}</td>
                <td style={{ ...esi.td, color: Tchain.color.text.secondary, fontSize: '11px' }}>{a.role}</td>
                <td style={{ ...esi.td, color: Tchain.color.text.primary, fontSize: '11px', maxWidth: '260px' }}>{a.type}</td>
                <td style={esi.td}>{a.status === 'Signed'
                  ? <Badge color={esi.emerald} bg={esi.emeraldBg}>ok signed</Badge>
                  : <Badge color={esi.amber} bg={esi.amberBg}>pending</Badge>}</td>
                <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontSize: '11px', color: Tchain.color.text.tertiary }}>{a.signedOn || '—'}</td>
                <td style={{ ...esi.td, color: Tchain.color.text.secondary, fontSize: '11px' }}>{a.notary || '—'}</td>
                <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontSize: '11px', color: esi.cobalt, fontWeight: 700 }}>{a.exhibit}</td>
                <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontSize: '10px', color: esi.violet }}>{a.relatedChains.join(', ') || '—'}</td>
                <td style={{ ...esi.td, color: Tchain.color.text.secondary, fontSize: '11px', maxWidth: '280px' }}>{a.note}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── 7. EXPORTS ───────────────────────────────────────────────────────────────
function ChainExports({ data }) {
  const esi = window.__esi;
  const exp = data.chainExports;
  const delivered = exp.filter(e => e.status === 'Delivered' || e.status === 'Filed').length;
  const totalEvents = exp.reduce((s, e) => s + e.events, 0);

  const statusStyle = (s) => {
    const m = {
      'Delivered': { bg: esi.emeraldBg, color: esi.emerald },
      'Filed':     { bg: esi.emeraldBg, color: esi.emerald },
      'In QC':     { bg: esi.cyanBg, color: esi.cyan },
      'Drafting':  { bg: esi.amberBg, color: esi.amber },
    };
    return m[s] || { bg: Tchain.color.bg.secondary, color: Tchain.color.text.secondary };
  };

  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' }}>◆ Court-admissible export bundles — FRE 901/902 + ISO 27050-2</div>
          <div style={{ fontSize: '11px', color: Tchain.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Each export bundle includes the chain manifest, SHA-256 hash table, custodian declarations (FRE 902(14)), seal registry, and PGP-signed cover page. Bundles are court-admissible out of the box.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Exports prepared</span><span style={esi.statValue}>{exp.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Delivered / filed</span><span style={{ ...esi.statValue, color: esi.emerald }}>{delivered}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Events packaged</span><span style={esi.statValue}>{totalEvents}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Admissibility flags</span><span style={{ ...esi.statValue, color: esi.emerald }}>100%</span><span style={{ ...esi.statDelta, color: Tchain.color.text.tertiary }}>FRE 901/902 · ISO</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}>
          <span>Export bundles — {exp.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <button style={esi.btnSecondary}>Export manifest</button>
            <button style={{ ...esi.btnPrimary, background: esi.violet }}>+ Prepare bundle</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={esi.th}>ID</th>
              <th style={esi.th}>Title</th>
              <th style={esi.th}>Prepared on</th>
              <th style={esi.th}>Prepared by</th>
              <th style={esi.th}>Recipient</th>
              <th style={esi.th}>Format</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>Events</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>Attest.</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>Seals</th>
              <th style={esi.th}>Admissibility</th>
              <th style={esi.th}>Status</th>
              <th style={esi.th}>Tracking</th>
            </tr>
          </thead>
          <tbody>
            {exp.map(e => {
              const ss = statusStyle(e.status);
              return (
                <tr key={e.id}>
                  <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontWeight: 700, color: esi.violet }}>{e.id}</td>
                  <td style={{ ...esi.td, color: Tchain.color.text.primary, fontWeight: 600, maxWidth: '280px' }}>{e.title}</td>
                  <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontSize: '11px', color: Tchain.color.text.tertiary }}>{e.preparedOn}</td>
                  <td style={{ ...esi.td, color: Tchain.color.text.secondary, fontSize: '11px' }}>{e.preparedBy}</td>
                  <td style={{ ...esi.td, color: Tchain.color.text.secondary, fontSize: '11px', maxWidth: '220px' }}>{e.recipient}</td>
                  <td style={{ ...esi.td, color: Tchain.color.text.tertiary, fontSize: '11px' }}>{e.format}</td>
                  <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tchain.font.mono, color: Tchain.color.text.primary, fontWeight: 700 }}>{e.events}</td>
                  <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tchain.font.mono, color: esi.teal, fontWeight: 600 }}>{e.attestations}</td>
                  <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tchain.font.mono, color: esi.cobalt, fontWeight: 600 }}>{e.seals}</td>
                  <td style={esi.td}>
                    <div style={{ display: 'flex', gap: '3px', flexWrap: 'wrap' }}>
                      {e.fre901 && <Badge color={esi.emerald} bg={esi.emeraldBg}>FRE 901</Badge>}
                      {e.fre902 && <Badge color={esi.emerald} bg={esi.emeraldBg}>FRE 902</Badge>}
                      {e.iso27050 && <Badge color={esi.violet} bg={esi.violetBg}>ISO 27050</Badge>}
                    </div>
                  </td>
                  <td style={esi.td}><Badge color={ss.color} bg={ss.bg}>{e.status}</Badge></td>
                  <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontSize: '10px', color: Tchain.color.text.tertiary }}>{e.trackingNum || '—'}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── 8. COMPLIANCE ────────────────────────────────────────────────────────────
function ChainCompliance({ data }) {
  const esi = window.__esi;
  const std = data.chainStandards;
  const avgCoverage = Math.round(std.reduce((s, r) => s + r.coverage, 0) / std.length);
  const totalFindings = std.reduce((s, r) => s + r.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' }}>◆ Compliance posture — {avgCoverage}% average coverage</div>
          <div style={{ fontSize: '11px', color: Tchain.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            {std.length} standards tracked across federal rules, ISO, NIST, and professional-conduct authorities. <b>{totalFindings} open finding(s)</b>; last external audit {data.chainKpis.lastAuditDate} by BSI.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Standards tracked</span><span style={esi.statValue}>{std.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 / next audit</span><span style={{ ...esi.statValue, fontSize: '14px' }}>{data.chainKpis.lastAuditDate}</span><span style={{ ...esi.statDelta, color: Tchain.color.text.tertiary }}>next {data.chainKpis.nextAuditDate}</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}>
          <span>Standards & rule coverage</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <button style={esi.btnSecondary}>Download audit package</button>
            <button style={esi.btnSecondary}>Schedule internal audit</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={esi.th}>Code</th>
              <th style={esi.th}>Title</th>
              <th style={esi.th}>Applied to</th>
              <th style={esi.th}>Coverage</th>
              <th style={esi.th}>Last audit</th>
              <th style={esi.th}>Auditor</th>
              <th style={esi.th}>Findings</th>
              <th style={esi.th}>Note</th>
            </tr>
          </thead>
          <tbody>
            {std.map(s => (
              <tr key={s.code}>
                <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontWeight: 700, color: esi.violet, whiteSpace: 'nowrap' }}>{s.code}</td>
                <td style={{ ...esi.td, color: Tchain.color.text.primary, fontSize: '12px', fontWeight: 500, maxWidth: '340px' }}>{s.title}</td>
                <td style={esi.td}>
                  <div style={{ display: 'flex', gap: '3px', flexWrap: 'wrap' }}>
                    {s.applied.map(a => <Badge key={a} color={esi.slate} bg={esi.slateBg}>{a}</Badge>)}
                  </div>
                </td>
                <td style={esi.td}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <div style={{ width: '80px', height: '6px', background: Tchain.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                      <div style={{ width: `${s.coverage}%`, height: '100%', background: s.coverage >= 100 ? esi.emerald : s.coverage >= 90 ? esi.cyan : esi.amber }} />
                    </div>
                    <Mono color={s.coverage >= 100 ? esi.emerald : esi.cyan} weight={700}>{s.coverage}%</Mono>
                  </div>
                </td>
                <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontSize: '11px', color: Tchain.color.text.tertiary }}>{s.lastAudit}</td>
                <td style={{ ...esi.td, color: Tchain.color.text.secondary, fontSize: '11px' }}>{s.auditor}</td>
                <td style={esi.td}>{s.findings === 0
                  ? <Badge color={esi.emerald} bg={esi.emeraldBg}>0 open</Badge>
                  : <Badge color={esi.amber} bg={esi.amberBg}>{s.findings} open</Badge>}</td>
                <td style={{ ...esi.td, color: Tchain.color.text.secondary, fontSize: '11px', maxWidth: '320px' }}>{s.note}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── 9. AUDIT TRAIL ───────────────────────────────────────────────────────────
function ChainAudit({ data }) {
  const esi = window.__esi;
  const [actionFilter, setActionFilter] = useChainState('All');
  const audit = data.chainAudit;
  const actions = ['All', ...new Set(audit.map(a => a.action))];
  const rows = audit.filter(a => actionFilter === 'All' || a.action === actionFilter);

  const sevStyle = (s) => s === 'error' ? { bg: esi.crimsonBg, color: esi.crimson }
    : s === 'warn' ? { bg: esi.amberBg, color: esi.amber }
    : { bg: esi.emeraldBg, color: esi.emerald };

  const actionColor = (a) => {
    if (a.includes('BREAK') || a.includes('FAIL')) return esi.crimson;
    if (a.includes('SEAL') || a.includes('VERIFY')) return esi.cobalt;
    if (a.includes('TRANSFER') || a.includes('INGEST') || a.includes('EXPORT')) return esi.cyan;
    if (a.includes('AUDIT')) return esi.violet;
    return esi.slate;
  };

  return (
    <div>
      <div style={{ ...esi.card, borderLeft: `3px solid ${esi.slate}`, background: esi.slateBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: esi.slate, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Tamper-evident audit trail — HMAC-SHA256 signed</div>
          <div style={{ fontSize: '11px', color: Tchain.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Every chain event generates an immutable audit record. Records are HMAC-signed, append-only, and externally witnessed by a compliance daemon. Log truncation or rewrite is detectable and alarmed.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Audit records</span><span style={esi.statValue}>{audit.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Signature verified</span><span style={{ ...esi.statValue, color: esi.emerald }}>100%</span><span style={{ ...esi.statDelta, color: Tchain.color.text.tertiary }}>HMAC-SHA256</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Warnings</span><span style={{ ...esi.statValue, color: esi.amber }}>{audit.filter(a => a.severity === 'warn').length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Errors</span><span style={{ ...esi.statValue, color: esi.crimson }}>{audit.filter(a => a.severity === 'error').length}</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}>
          <span>Audit log — {rows.length} of {audit.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <select value={actionFilter} onChange={e => setActionFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tchain.color.border.light}`, borderRadius: '5px', background: Tchain.color.bg.card, color: Tchain.color.text.secondary }}>
              {actions.map(a => <option key={a}>Action: {a}</option>)}
            </select>
            <button style={esi.btnSecondary}>Verify chain signatures</button>
            <button style={esi.btnSecondary}>Export audit log</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={esi.th}>Record</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}>Before</th>
              <th style={esi.th}>After</th>
              <th style={esi.th}>IP / Location</th>
              <th style={esi.th}>Signature</th>
              <th style={esi.th}>Severity</th>
            </tr>
          </thead>
          <tbody>
            {rows.map(r => {
              const ss = sevStyle(r.severity);
              const ac = actionColor(r.action);
              return (
                <tr key={r.id}>
                  <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontWeight: 700, color: esi.slate }}>{r.id}</td>
                  <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontSize: '11px', color: Tchain.color.text.tertiary }}>{r.ts}</td>
                  <td style={{ ...esi.td, color: Tchain.color.text.primary, fontSize: '11px', fontWeight: 500 }}>
                    <span style={{ display: 'inline-block', width: '6px', height: '6px', borderRadius: '50%', background: ss.color, marginRight: '8px' }} />
                    {r.actor}
                  </td>
                  <td style={esi.td}><Badge color={ac} bg={`${ac}14`} mono>{r.action}</Badge></td>
                  <td style={{ ...esi.td, fontFamily: Tchain.font.mono, color: esi.violet, fontSize: '11px', fontWeight: 700 }}>{r.target}</td>
                  <td style={{ ...esi.td, color: Tchain.color.text.tertiary, fontSize: '11px' }}>{r.before}</td>
                  <td style={{ ...esi.td, color: Tchain.color.text.primary, fontSize: '11px', fontWeight: 500 }}>{r.after}</td>
                  <td style={{ ...esi.td, fontFamily: Tchain.font.mono, fontSize: '10px', color: Tchain.color.text.tertiary }}>{r.ip}</td>
                  <td style={{ ...esi.td, fontSize: '11px', color: esi.emerald, fontWeight: 600 }}>{r.sig}</td>
                  <td style={esi.td}><Badge color={ss.color} bg={ss.bg}>{r.severity}</Badge></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── ROOT — ESIChainOfCustody ─────────────────────────────────────────────────
function ESIChainOfCustody({ data }) {
  const esi = window.__esi;
  const [view, setView] = useChainState('overview');

  const renderView = () => {
    switch (view) {
      case 'overview':     return <ChainOverview     data={data} />;
      case 'ledger':       return <ChainLedger       data={data} />;
      case 'integrity':    return <ChainIntegrity    data={data} />;
      case 'transfers':    return <ChainTransfers    data={data} />;
      case 'seals':        return <ChainSeals        data={data} />;
      case 'attestations': return <ChainAttestations data={data} />;
      case 'exports':      return <ChainExports      data={data} />;
      case 'compliance':   return <ChainCompliance   data={data} />;
      case 'audit':        return <ChainAudit        data={data} />;
      default:             return <ChainOverview     data={data} />;
    }
  };

  return (
    <div>
      <ChainSubNav active={view} onChange={setView} />
      {renderView()}
    </div>
  );
}

window.ESIChainOfCustody = ESIChainOfCustody;
