// ESI COLLECTIONS — Views Part 2: Scope · Vendors · Errors · Audit + Platform Entry
const { useState: useCLV2State } = React;
const Tcl2 = window.ArbiterTokens;

function CollectionsScope({ data }) {
  const esi = window.__esi;
  const scopes = data.collectionsExt.scope;
  const scheduled = data.collectionsExt.scheduled;
  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' }}>◆ Collection scope — FRCP 26(f) negotiated sources · Legal hold LH-2024-008</div>
          <div style={{ fontSize: '11px', color: Tcl2.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            {scopes.length} scope definitions covering {scopes.reduce((s, sc) => s + (sc.custodians || 0), 0)} custodian slots and an estimated <b style={{ color: Tcl2.color.text.primary }}>{esi.bytes(scopes.reduce((s, sc) => s + sc.estimatedGB, 0))}</b> total volume.
          </div>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '14px', marginBottom: '14px' }}>
        {scopes.map(sc => (
          <div key={sc.id} style={{ ...esi.card, marginBottom: 0 }}>
            <div style={{ padding: '10px 14px', borderBottom: `1px solid ${Tcl2.color.border.light}`, background: esi.cyanBg }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span style={{ fontFamily: Tcl2.font.mono, fontSize: '11px', fontWeight: 700, color: esi.cyan }}>{sc.id}</span>
                <span style={{ ...esi.tag, background: esi.emeraldBg, color: esi.emerald }}>{sc.status}</span>
              </div>
              <div style={{ fontSize: '12px', fontWeight: 700, color: Tcl2.color.text.primary, marginTop: '4px' }}>{sc.name}</div>
            </div>
            <div style={{ padding: '12px 14px' }}>
              <div style={{ fontSize: '10px', color: Tcl2.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Sources</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px', marginBottom: '8px' }}>
                {sc.sources.map(s => <span key={s} style={{ ...esi.tag, background: Tcl2.color.bg.secondary, color: Tcl2.color.text.secondary, fontSize: '10px' }}>{s}</span>)}
              </div>
              {sc.dateFrom && <div style={{ fontSize: '11px', color: Tcl2.color.text.secondary, marginBottom: '4px' }}>Date: <b style={{ fontFamily: Tcl2.font.mono, color: Tcl2.color.text.primary }}>{sc.dateFrom} → {sc.dateTo}</b></div>}
              {sc.keywords.length > 0 && (
                <div style={{ fontSize: '11px', color: Tcl2.color.text.secondary, marginBottom: '4px' }}>
                  Keywords: <b style={{ color: esi.cyan }}>{sc.keywords.slice(0, 4).join(', ')}{sc.keywords.length > 4 ? `… +${sc.keywords.length - 4}` : ''}</b>
                </div>
              )}
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '8px', paddingTop: '8px', borderTop: `1px solid ${Tcl2.color.border.light}`, fontSize: '11px' }}>
                <span style={{ fontFamily: Tcl2.font.mono, fontWeight: 700, color: esi.cyan }}>{esi.bytes(sc.estimatedGB)}</span>
                <span style={{ color: Tcl2.color.text.tertiary }}>Approved: {sc.approvedBy} · {sc.approvedOn}</span>
              </div>
            </div>
          </div>
        ))}
      </div>
      {scheduled.length > 0 && (
        <div style={esi.card}>
          <div style={esi.cardH}><span>Scheduled upcoming — {scheduled.length}</span><button style={{ ...esi.btnPrimary, background: esi.cyan }}>+ Schedule collection</button></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr>
              <th style={esi.th}>ID</th><th style={esi.th}>Source</th><th style={esi.th}>Custodian</th>
              <th style={esi.th}>Vendor</th><th style={esi.th}>Method</th>
              <th style={{ ...esi.th, textAlign: 'right' }}>Est. GB</th>
              <th style={esi.th}>Scheduled</th><th style={esi.th}>Approved by</th><th style={esi.th}>Status</th>
            </tr></thead>
            <tbody>
              {scheduled.map(s => (
                <tr key={s.id}>
                  <td style={{ ...esi.td, fontFamily: Tcl2.font.mono, fontWeight: 700, color: esi.cyan }}>{s.id}</td>
                  <td style={{ ...esi.td, color: Tcl2.color.text.primary, fontSize: '11px' }}>{s.source}</td>
                  <td style={{ ...esi.td, color: Tcl2.color.text.secondary, fontSize: '11px' }}>{s.custodian}</td>
                  <td style={{ ...esi.td, color: Tcl2.color.text.secondary, fontSize: '11px' }}>{s.vendor}</td>
                  <td style={{ ...esi.td, color: Tcl2.color.text.secondary, fontSize: '11px' }}>{s.method}</td>
                  <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tcl2.font.mono, fontWeight: 700 }}>{esi.bytes(s.estimatedGB)}</td>
                  <td style={{ ...esi.td, fontFamily: Tcl2.font.mono, fontSize: '11px', color: esi.amber }}>{s.scheduledDate}</td>
                  <td style={{ ...esi.td, color: Tcl2.color.text.secondary, fontSize: '11px' }}>{s.approvedBy}</td>
                  <td style={esi.td}><span style={{ ...esi.tag, background: esi.amberBg, color: esi.amber }}>{s.status}</span></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

function CollectionsVendors({ data }) {
  const esi = window.__esi;
  const vendors = data.collectionsExt.vendorPerformance;
  const active = vendors.filter(v => v.jobsTotal > 0);
  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Vendors total</span><span style={esi.statValue}>{vendors.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Engaged this matter</span><span style={{ ...esi.statValue, color: esi.cyan }}>{active.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Total fees (est.)</span><span style={esi.statValue}>{esi.money(vendors.reduce((s, v) => s + v.cost, 0))}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Avg SLA compliance</span><span style={{ ...esi.statValue, color: esi.emerald }}>{Math.round(active.filter(v => v.slaCompliance).reduce((s, v) => s + v.slaCompliance, 0) / active.filter(v => v.slaCompliance).length)}%</span></div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '14px', marginBottom: '14px' }}>
        {active.map(v => (
          <div key={v.vendorId} style={{ ...esi.card, marginBottom: 0 }}>
            <div style={{ padding: '10px 16px', borderBottom: `1px solid ${Tcl2.color.border.light}`, background: esi.cyanBg, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <div style={{ fontSize: '13px', fontWeight: 700, color: Tcl2.color.text.primary }}>{v.name}</div>
                <div style={{ fontFamily: Tcl2.font.mono, fontSize: '10px', color: Tcl2.color.text.tertiary }}>{v.vendorId}</div>
              </div>
              <span style={{ ...esi.tag, background: esi.emeraldBg, color: esi.emerald }}>Active</span>
            </div>
            <div style={{ padding: '12px 16px', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px' }}>
              <div><span style={{ fontSize: '10px', color: Tcl2.color.text.tertiary, textTransform: 'uppercase' }}>Jobs</span><div style={{ fontFamily: Tcl2.font.mono, fontWeight: 700, color: Tcl2.color.text.primary }}>{v.jobsTotal} ({v.jobsComplete} done)</div></div>
              <div><span style={{ fontSize: '10px', color: Tcl2.color.text.tertiary, textTransform: 'uppercase' }}>Avg cycle</span><div style={{ fontFamily: Tcl2.font.mono, fontWeight: 700, color: Tcl2.color.text.primary }}>{v.avgCycleDays ? `${v.avgCycleDays}d` : '—'}</div></div>
              <div><span style={{ fontSize: '10px', color: Tcl2.color.text.tertiary, textTransform: 'uppercase' }}>SLA</span><div style={{ fontFamily: Tcl2.font.mono, fontWeight: 700, color: v.slaCompliance >= 99 ? esi.emerald : esi.amber }}>{v.slaCompliance ? `${v.slaCompliance}%` : '—'}</div></div>
              <div><span style={{ fontSize: '10px', color: Tcl2.color.text.tertiary, textTransform: 'uppercase' }}>Error rate</span><div style={{ fontFamily: Tcl2.font.mono, fontWeight: 700, color: v.errorRate === 0 ? esi.emerald : esi.amber }}>{v.errorRate != null ? `${v.errorRate}%` : '—'}</div></div>
              <div><span style={{ fontSize: '10px', color: Tcl2.color.text.tertiary, textTransform: 'uppercase' }}>Rate (MB/s)</span><div style={{ fontFamily: Tcl2.font.mono, color: Tcl2.color.text.primary }}>{v.dataRateMBs ? `${v.dataRateMBs}` : '—'}</div></div>
              <div><span style={{ fontSize: '10px', color: Tcl2.color.text.tertiary, textTransform: 'uppercase' }}>Est. cost</span><div style={{ fontFamily: Tcl2.font.mono, fontWeight: 700, color: Tcl2.color.text.primary }}>{v.cost > 0 ? esi.money(v.cost) : 'Internal'}</div></div>
            </div>
            <div style={{ padding: '8px 16px', borderTop: `1px solid ${Tcl2.color.border.light}`, fontSize: '11px', color: Tcl2.color.text.secondary }}>{v.notes}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

function CollectionsErrors({ data }) {
  const esi = window.__esi;
  const errors = data.collectionsExt.errors;
  const open = errors.filter(e => !e.resolved).length;
  return (
    <div>
      <div style={{ ...esi.card, borderLeft: `3px solid ${open > 0 ? esi.crimson : esi.emerald}`, background: open > 0 ? esi.crimsonBg : esi.emeraldBg, marginBottom: '14px' }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: open > 0 ? esi.crimson : esi.emerald, textTransform: 'uppercase', letterSpacing: '0.08em' }}>
            {open > 0 ? `! ${open} open errors require attention` : '◆ All errors resolved — collection pipeline healthy'}
          </div>
          <div style={{ fontSize: '11px', color: Tcl2.color.text.secondary, marginTop: '4px' }}>
            {errors.length} total events logged. {errors.filter(e => e.resolved).length} resolved, {open} pending.
          </div>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Total events</span><span style={esi.statValue}>{errors.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Open</span><span style={{ ...esi.statValue, color: open > 0 ? esi.crimson : esi.emerald }}>{open}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Resolved</span><span style={{ ...esi.statValue, color: esi.emerald }}>{errors.filter(e => e.resolved).length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Error rate</span><span style={{ ...esi.statValue, color: esi.emerald }}>{data.collectionsExt.kpis.errorRate}%</span></div>
      </div>
      <div style={esi.card}>
        <div style={esi.cardH}><span>Error log — {errors.length} events</span><button style={esi.btnSecondary}>Export log</button></div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={esi.th}>ID</th><th style={esi.th}>Job</th><th style={esi.th}>Timestamp</th>
            <th style={esi.th}>Type</th><th style={esi.th}>Detail</th><th style={esi.th}>Severity</th>
            <th style={esi.th}>Resolved</th><th style={esi.th}>Resolution</th>
          </tr></thead>
          <tbody>
            {errors.map(e => {
              const sev = e.severity === 'warn' ? { bg: esi.amberBg, color: esi.amber } : { bg: esi.cyanBg, color: esi.cyan };
              return (
                <tr key={e.id}>
                  <td style={{ ...esi.td, fontFamily: Tcl2.font.mono, fontWeight: 700, color: esi.cyan }}>{e.id}</td>
                  <td style={{ ...esi.td, fontFamily: Tcl2.font.mono, color: esi.violet, fontWeight: 700 }}>{e.jobId}</td>
                  <td style={{ ...esi.td, fontFamily: Tcl2.font.mono, fontSize: '11px', color: Tcl2.color.text.tertiary }}>{e.ts}</td>
                  <td style={{ ...esi.td, fontSize: '11px', color: Tcl2.color.text.primary, fontWeight: 500 }}>{e.type}</td>
                  <td style={{ ...esi.td, fontSize: '11px', color: Tcl2.color.text.secondary, maxWidth: '280px' }}>{e.detail}</td>
                  <td style={esi.td}><span style={{ ...esi.tag, background: sev.bg, color: sev.color }}>{e.severity}</span></td>
                  <td style={esi.td}>{e.resolved ? <span style={{ ...esi.tag, background: esi.emeraldBg, color: esi.emerald }}>ok {e.resolvedOn?.split(' ')[0]}</span> : <span style={{ ...esi.tag, background: esi.crimsonBg, color: esi.crimson }}>open</span>}</td>
                  <td style={{ ...esi.td, fontSize: '11px', color: Tcl2.color.text.secondary, maxWidth: '280px' }}>{e.resolution || '—'}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function CollectionsAudit({ data }) {
  const esi = window.__esi;
  const rows = data.collectionsExt.audit;
  const actionColor = (a) => {
    if (a.includes('COMPLETE') || a.includes('RESOLVE')) return esi.emerald;
    if (a.includes('START') || a.includes('UPDATE')) return esi.cyan;
    if (a.includes('APPROVE')) return esi.violet;
    if (a.includes('ERROR')) return esi.amber;
    return esi.slate;
  };
  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: Tcl2.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>Collection audit trail — {rows.length} entries</span><button style={esi.btnSecondary}>Export log</button></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 sev = 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: Tcl2.font.mono, fontWeight: 700, color: esi.cyan }}>{r.id}</td>
                  <td style={{ ...esi.td, fontFamily: Tcl2.font.mono, fontSize: '11px', color: Tcl2.color.text.tertiary }}>{r.ts}</td>
                  <td style={{ ...esi.td, color: Tcl2.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: Tcl2.font.mono, color: esi.violet, fontWeight: 700 }}>{r.target}</td>
                  <td style={{ ...esi.td, fontSize: '11px', color: Tcl2.color.text.secondary, maxWidth: '340px' }}>{r.detail}</td>
                  <td style={esi.td}><span style={{ ...esi.tag, background: sev.bg, color: sev.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 ESICollectionsPlatform({ data }) {
  const esi = window.__esi;
  const [activeView, setActiveView] = useCLV2State('overview');
  const views = [
    { id: 'overview',   label: 'Overview' },
    { id: 'jobs',       label: 'Jobs' },
    { id: 'custodians', label: 'Custodians' },
    { id: 'scope',      label: 'Scope' },
    { id: 'vendors',    label: 'Vendors' },
    { id: 'errors',     label: 'Errors & Gaps' },
    { id: 'audit',      label: 'Audit Trail' },
  ];
  const renderView = () => {
    switch (activeView) {
      case 'overview':   return <CollectionsOverview data={data} />;
      case 'jobs':       return <CollectionsJobs data={data} />;
      case 'custodians': return <CollectionsCustodians data={data} />;
      case 'scope':      return <CollectionsScope data={data} />;
      case 'vendors':    return <CollectionsVendors data={data} />;
      case 'errors':     return <CollectionsErrors data={data} />;
      case 'audit':      return <CollectionsAudit data={data} />;
      default:           return <CollectionsOverview data={data} />;
    }
  };
  return (
    <div>
      <div style={{ display: 'flex', gap: '4px', padding: '6px', background: Tcl2.color.bg.secondary, border: `1px solid ${Tcl2.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.cyan : 'transparent',
            color: activeView === v.id ? '#fff' : Tcl2.color.text.secondary,
            fontFamily: Tcl2.font.family, transition: 'all .15s',
          }}>{v.label}</button>
        ))}
      </div>
      {renderView()}
    </div>
  );
}

window.CollectionsScope = CollectionsScope;
window.CollectionsVendors = CollectionsVendors;
window.CollectionsErrors = CollectionsErrors;
window.CollectionsAudit = CollectionsAudit;
window.ESICollectionsPlatform = ESICollectionsPlatform;
