// ESI COLLECTIONS — Views Part 1: Overview · Jobs · Custodians
const { useState: useCLV1State, useMemo: useCLV1Memo } = React;
const Tcl1 = window.ArbiterTokens;

function CollectionsOverview({ data }) {
  const esi = window.__esi;
  const k = data.collectionsExt.kpis;
  const jobs = data.collectionsExt.jobs;
  const byStatus = {};
  jobs.forEach(j => { byStatus[j.status] = (byStatus[j.status] || 0) + 1; });
  const bySource = {};
  jobs.forEach(j => { bySource[j.sourceType] = (bySource[j.sourceType] || 0) + (j.volumeGB || 0); });
  const topSources = Object.entries(bySource).sort((a, b) => b[1] - a[1]);
  const maxSourceVol = Math.max(...topSources.map(s => s[1]));

  const pipelinePct = k.totalVolumeGB > 0 ? (k.collectedVolumeGB / k.totalVolumeGB * 100).toFixed(0) : 0;

  return (
    <div>
      <div style={{ ...esi.card, borderLeft: `3px solid ${esi.cyan}`, background: esi.cyanBg }}>
        <div style={{ padding: '14px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: '13px', fontWeight: 700, color: esi.cyan, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Collection Command Center — FRCP 26(f) · Hold LH-2024-008 Active</div>
            <div style={{ fontSize: '12px', color: Tcl1.color.text.secondary, marginTop: '6px', lineHeight: 1.55 }}>
              <b style={{ color: Tcl1.color.text.primary }}>{k.totalJobs} collection jobs</b> across <b>{k.custodiansCovered} custodians</b> and <b>{k.vendorsEngaged} vendors</b>. <b style={{ fontFamily: Tcl1.font.mono, color: esi.cyan }}>{esi.bytes(k.collectedVolumeGB)}</b> collected of <b style={{ fontFamily: Tcl1.font.mono }}>{esi.bytes(k.totalVolumeGB)}</b> scoped. <b style={{ color: esi.emerald }}>{pipelinePct}% pipeline complete.</b>
            </div>
          </div>
          <div style={{ display: 'flex', gap: '6px', flexShrink: 0 }}>
            <button style={esi.btnSecondary}>Chain of custody report</button>
            <button style={{ ...esi.btnPrimary, background: esi.cyan }}>+ New collection</button>
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(8, 1fr)', gap: '10px', marginBottom: '14px' }}>
        {[
          { l: 'Total jobs',    v: k.totalJobs,    d: null,                  c: null },
          { l: 'Active',        v: k.activeJobs,   d: null,                  c: esi.cyan },
          { l: 'Completed',     v: k.completedJobs,d: null,                  c: esi.emerald },
          { l: 'Vol. collected',v: esi.bytes(k.collectedVolumeGB), d: `of ${esi.bytes(k.totalVolumeGB)}`, c: esi.cyan },
          { l: 'Docs collected',v: `${(k.collectedDocs/1_000).toFixed(0)}K`, d: `of ${(k.totalDocs/1_000).toFixed(0)}K`, c: null },
          { l: 'Custodians',    v: `${k.custodiansComplete}/${k.custodiansCovered}`, d: 'complete', c: esi.emerald },
          { l: 'Avg cycle',     v: `${k.avgCycleTimeDays}d`,     d: 'per job', c: null },
          { l: 'Error rate',    v: `${k.errorRate}%`,             d: `${k.retryQueue} retry`, c: k.errorRate < 1 ? esi.emerald : esi.amber },
        ].map(s => (
          <div key={s.l} style={esi.stat}>
            <span style={esi.statLabel}>{s.l}</span>
            <span style={{ ...esi.statValue, color: s.c || Tcl1.color.text.primary }}>{s.v}</span>
            {s.d && <span style={{ ...esi.statDelta, color: Tcl1.color.text.tertiary }}>{s.d}</span>}
          </div>
        ))}
      </div>

      {/* Pipeline progress bar */}
      <div style={{ ...esi.card, marginBottom: '14px' }}>
        <div style={esi.cardH}>Collection pipeline progress</div>
        <div style={{ padding: '14px 16px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', color: Tcl1.color.text.secondary, marginBottom: '6px' }}>
            <span>0 GB</span>
            <span style={{ fontFamily: Tcl1.font.mono, color: esi.cyan, fontWeight: 700 }}>{pipelinePct}% — {esi.bytes(k.collectedVolumeGB)} of {esi.bytes(k.totalVolumeGB)}</span>
            <span>{esi.bytes(k.totalVolumeGB)}</span>
          </div>
          <div style={{ height: '16px', background: Tcl1.color.border.light, borderRadius: '6px', overflow: 'hidden', marginBottom: '12px' }}>
            <div style={{ width: `${pipelinePct}%`, height: '100%', background: `linear-gradient(90deg, ${esi.cyan}, ${esi.teal})`, borderRadius: '6px' }} />
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '10px' }}>
            {jobs.map(j => {
              const ss = esi.statusColor(j.status);
              return (
                <div key={j.id} style={{ padding: '8px 10px', borderRadius: '6px', background: Tcl1.color.bg.secondary, border: `1px solid ${Tcl1.color.border.light}` }}>
                  <div style={{ fontFamily: Tcl1.font.mono, fontSize: '10px', fontWeight: 700, color: esi.cyan, marginBottom: '2px' }}>{j.id}</div>
                  <div style={{ fontSize: '10px', color: Tcl1.color.text.secondary, marginBottom: '4px', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{j.sourceType}</div>
                  <div style={{ height: '5px', background: Tcl1.color.border.light, borderRadius: '3px', overflow: 'hidden', marginBottom: '4px' }}>
                    <div style={{ width: `${j.progressPct}%`, height: '100%', background: j.status === 'Complete ok' ? esi.emerald : esi.cyan }} />
                  </div>
                  <span style={{ ...esi.tag, background: ss.bg, color: ss.color, fontSize: '9px', padding: '1px 5px' }}>{j.progressPct}%</span>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '14px' }}>
        <div style={esi.card}>
          <div style={esi.cardH}>Volume by source type</div>
          <div style={{ padding: '14px 16px' }}>
            {topSources.map(([type, gb]) => (
              <div key={type} style={{ marginBottom: '10px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '4px' }}>
                  <span style={{ color: Tcl1.color.text.primary, fontWeight: 500 }}>{esi.sourceStyle(type).icon} {type}</span>
                  <span style={{ fontFamily: Tcl1.font.mono, color: esi.cyan, fontWeight: 700 }}>{esi.bytes(gb)}</span>
                </div>
                <div style={{ height: '10px', background: Tcl1.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                  <div style={{ width: `${(gb / maxSourceVol) * 100}%`, height: '100%', background: `linear-gradient(90deg, ${esi.cyan}, ${esi.teal})` }} />
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={esi.card}>
          <div style={esi.cardH}>Recent collection activity</div>
          <div style={{ padding: '4px 0' }}>
            {data.collectionsExt.audit.slice(0, 6).map((a, i) => (
              <div key={a.id} style={{ padding: '8px 16px', borderBottom: i === 5 ? 'none' : `1px solid ${Tcl1.color.border.light}`, display: 'grid', gridTemplateColumns: '80px 1fr auto', gap: '10px', alignItems: 'center' }}>
                <span style={{ fontFamily: Tcl1.font.mono, fontSize: '11px', fontWeight: 700, color: esi.cyan }}>{a.id}</span>
                <div>
                  <div style={{ fontSize: '11px', color: Tcl1.color.text.primary, fontWeight: 500 }}>{a.detail}</div>
                  <div style={{ fontSize: '10px', color: Tcl1.color.text.tertiary, marginTop: '1px' }}>{a.actor} · {a.action}</div>
                </div>
                <span style={{ fontFamily: Tcl1.font.mono, fontSize: '10px', color: Tcl1.color.text.tertiary, whiteSpace: 'nowrap' }}>{a.ts.split(' ')[0]}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function CollectionsJobs({ data }) {
  const esi = window.__esi;
  const [statusFilter, setStatusFilter] = useCLV1State('All');
  const [typeFilter, setTypeFilter] = useCLV1State('All');
  const [selected, setSelected] = useCLV1State(null);
  const jobs = data.collectionsExt.jobs;
  const statuses = ['All', ...new Set(jobs.map(j => j.status))];
  const types = ['All', ...new Set(jobs.map(j => j.sourceType))];
  const rows = jobs.filter(j => (statusFilter === 'All' || j.status === statusFilter) && (typeFilter === 'All' || j.sourceType === typeFilter));

  const totalVol = rows.reduce((s, j) => s + (j.collectedGB || 0), 0);
  const totalDocs = rows.reduce((s, j) => s + (j.collectedDocs || 0), 0);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Jobs shown</span><span style={esi.statValue}>{rows.length}</span><span style={{ ...esi.statDelta, color: Tcl1.color.text.tertiary }}>of {jobs.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Volume collected</span><span style={{ ...esi.statValue, color: esi.cyan }}>{esi.bytes(totalVol)}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Docs collected</span><span style={esi.statValue}>{totalDocs.toLocaleString()}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Avg progress</span><span style={{ ...esi.statValue, color: esi.cyan }}>{rows.length ? Math.round(rows.reduce((s, j) => s + j.progressPct, 0) / rows.length) : 0}%</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}>
          <span>Collection jobs — {rows.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 ${Tcl1.color.border.light}`, borderRadius: '5px', background: Tcl1.color.bg.card, color: Tcl1.color.text.secondary }}>
              {statuses.map(s => <option key={s} value={s}>Status: {s}</option>)}
            </select>
            <select value={typeFilter} onChange={e => setTypeFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tcl1.color.border.light}`, borderRadius: '5px', background: Tcl1.color.bg.card, color: Tcl1.color.text.secondary }}>
              {types.map(t => <option key={t} value={t}>Type: {t}</option>)}
            </select>
            <button style={esi.btnSecondary}>Export CSV</button>
            <button style={{ ...esi.btnPrimary, background: esi.cyan }}>+ New collection</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={esi.th}>Job</th><th style={esi.th}>Source</th><th style={esi.th}>Custodian(s)</th>
            <th style={esi.th}>Method</th><th style={esi.th}>Vendor</th>
            <th style={{ ...esi.th, textAlign: 'right' }}>Collected</th><th style={{ ...esi.th, textAlign: 'right' }}>Docs</th>
            <th style={esi.th}>Progress</th><th style={esi.th}>ETA</th><th style={esi.th}>Chain</th><th style={esi.th}>Status</th><th style={esi.th}></th>
          </tr></thead>
          <tbody>
            {rows.map(j => {
              const ss = esi.statusColor(j.status);
              const src = esi.sourceStyle(j.sourceType);
              const isSel = selected === j.id;
              return (
                <React.Fragment key={j.id}>
                  <tr onClick={() => setSelected(isSel ? null : j.id)} style={{ cursor: 'pointer', background: isSel ? esi.cyanBg : 'transparent' }}>
                    <td style={{ ...esi.td, fontFamily: Tcl1.font.mono, fontWeight: 700, color: esi.cyan }}>{j.id}</td>
                    <td style={esi.td}><span style={{ ...esi.tag, background: src.bg, color: src.color }}>{src.icon} {j.sourceType}</span></td>
                    <td style={{ ...esi.td, fontSize: '11px', color: Tcl1.color.text.secondary, maxWidth: '180px' }}>{j.custodian}</td>
                    <td style={{ ...esi.td, fontSize: '11px', color: Tcl1.color.text.secondary, maxWidth: '200px' }}>{j.method}</td>
                    <td style={{ ...esi.td, fontSize: '11px', color: Tcl1.color.text.secondary }}>{j.vendor}</td>
                    <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tcl1.font.mono, fontWeight: 700, color: Tcl1.color.text.primary }}>{esi.bytes(j.collectedGB)}</td>
                    <td style={{ ...esi.td, textAlign: 'right', fontFamily: Tcl1.font.mono, color: Tcl1.color.text.secondary }}>{j.collectedDocs ? j.collectedDocs.toLocaleString() : '—'}</td>
                    <td style={{ ...esi.td, minWidth: '80px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                        <div style={{ flex: 1, height: '6px', background: Tcl1.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                          <div style={{ width: `${j.progressPct}%`, height: '100%', background: j.status === 'Complete ok' ? esi.emerald : esi.cyan }} />
                        </div>
                        <span style={{ fontFamily: Tcl1.font.mono, fontSize: '10px', color: Tcl1.color.text.secondary, minWidth: '28px' }}>{j.progressPct}%</span>
                      </div>
                    </td>
                    <td style={{ ...esi.td, fontFamily: Tcl1.font.mono, fontSize: '11px', color: j.status !== 'Complete ok' ? esi.amber : Tcl1.color.text.tertiary }}>{j.eta}</td>
                    <td style={{ ...esi.td, fontFamily: Tcl1.font.mono, fontSize: '11px', color: esi.violet, fontWeight: 700 }}>{j.chainId}</td>
                    <td style={esi.td}><span style={{ ...esi.tag, background: ss.bg, color: ss.color }}>{j.status}</span></td>
                    <td style={{ ...esi.td, textAlign: 'right' }}><span style={{ fontSize: '11px', color: esi.cyan, fontWeight: 600 }}>{isSel ? '− collapse' : '+ expand'}</span></td>
                  </tr>
                  {isSel && (
                    <tr>
                      <td colSpan={12} style={{ padding: 0, background: esi.cyanBg }}>
                        <div style={{ padding: '14px 20px', borderTop: `1px solid ${esi.cyan}33`, borderBottom: `1px solid ${esi.cyan}33` }}>
                          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '20px', marginBottom: '12px' }}>
                            <div>
                              <div style={{ fontSize: '10px', fontWeight: 700, color: Tcl1.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Scope</div>
                              <div style={{ fontSize: '11px', color: Tcl1.color.text.secondary, lineHeight: 1.7 }}>
                                {j.dateRangeFrom && <div>Date range: <b style={{ color: Tcl1.color.text.primary, fontFamily: Tcl1.font.mono }}>{j.dateRangeFrom} → {j.dateRangeTo}</b></div>}
                                {j.keywords.length > 0 && <div>Keywords: <b style={{ color: esi.cyan }}>{j.keywords.slice(0, 4).join(', ')}{j.keywords.length > 4 ? '…' : ''}</b></div>}
                                <div>Hold: <b style={{ color: Tcl1.color.text.primary, fontFamily: Tcl1.font.mono }}>{j.legalHoldId}</b></div>
                              </div>
                            </div>
                            <div>
                              <div style={{ fontSize: '10px', fontWeight: 700, color: Tcl1.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Approval</div>
                              <div style={{ fontSize: '11px', color: Tcl1.color.text.secondary, lineHeight: 1.7 }}>
                                <div>Approved by: <b style={{ color: Tcl1.color.text.primary }}>{j.approvedBy}</b></div>
                                <div>Approved on: <b style={{ fontFamily: Tcl1.font.mono, color: Tcl1.color.text.primary }}>{j.approvedOn}</b></div>
                                <div>Errors: <b style={{ color: j.errorCount > 0 ? esi.amber : esi.emerald }}>{j.errorCount}</b> · Retries: <b>{j.retries}</b></div>
                              </div>
                            </div>
                            <div>
                              <div style={{ fontSize: '10px', fontWeight: 700, color: Tcl1.color.text.tertiary, textTransform: 'uppercase', marginBottom: '4px' }}>Custodians</div>
                              <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px' }}>
                                {j.custodianIds.length > 0 ? j.custodianIds.map(c => <span key={c} style={{ ...esi.tag, background: esi.cyanBg, color: esi.cyan }}>{c}</span>) : <span style={{ fontSize: '11px', color: Tcl1.color.text.tertiary, fontStyle: 'italic' }}>Scope-based (no named custodians)</span>}
                              </div>
                            </div>
                          </div>
                          <div style={{ fontSize: '11px', color: Tcl1.color.text.secondary, paddingTop: '10px', borderTop: `1px solid ${esi.cyan}22` }}>
                            <b style={{ color: esi.cyan }}>Notes:</b> {j.notes}
                          </div>
                        </div>
                      </td>
                    </tr>
                  )}
                </React.Fragment>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function CollectionsCustodians({ data }) {
  const esi = window.__esi;
  const custodians = data.collectionsExt.custodianCoverage;
  const complete = custodians.filter(c => c.status === 'Complete').length;
  const totalPct = Math.round(custodians.reduce((s, c) => s + c.pct, 0) / custodians.length);

  const statusColor = (s) => ({
    'Complete':    { bg: esi.emeraldBg, color: esi.emerald },
    'In Progress': { bg: esi.cyanBg,    color: esi.cyan },
    'Partial':     { bg: esi.amberBg,   color: esi.amber },
  }[s] || { bg: Tcl1.color.bg.secondary, color: Tcl1.color.text.secondary });

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={esi.stat}><span style={esi.statLabel}>Custodians</span><span style={esi.statValue}>{custodians.length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Complete</span><span style={{ ...esi.statValue, color: esi.emerald }}>{complete}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>In Progress</span><span style={{ ...esi.statValue, color: esi.cyan }}>{custodians.filter(c => c.status === 'In Progress').length}</span></div>
        <div style={esi.stat}><span style={esi.statLabel}>Avg coverage</span><span style={{ ...esi.statValue, color: totalPct >= 80 ? esi.emerald : esi.amber }}>{totalPct}%</span></div>
      </div>

      <div style={esi.card}>
        <div style={esi.cardH}><span>Custodian coverage — {custodians.length}</span><button style={{ ...esi.btnPrimary, background: esi.cyan }}>+ Add custodian</button></div>
        <div style={{ padding: '4px 0' }}>
          {custodians.map((c, i) => {
            const sc = statusColor(c.status);
            return (
              <div key={c.name} style={{ padding: '12px 16px', borderBottom: i === custodians.length - 1 ? 'none' : `1px solid ${Tcl1.color.border.light}` }}>
                <div style={{ display: 'grid', gridTemplateColumns: '200px 1fr 140px 140px 80px', gap: '16px', alignItems: 'center' }}>
                  <div>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: Tcl1.color.text.primary }}>{c.name}</div>
                    <div style={{ fontSize: '11px', color: Tcl1.color.text.tertiary }}>{c.role}</div>
                  </div>
                  <div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', color: Tcl1.color.text.tertiary, marginBottom: '3px' }}>
                      <span>{c.sourcesCollected}/{c.sourcesTotal} sources</span>
                      <span style={{ fontFamily: Tcl1.font.mono, color: c.pct === 100 ? esi.emerald : c.pct >= 75 ? esi.cyan : esi.amber, fontWeight: 700 }}>{c.pct}%</span>
                    </div>
                    <div style={{ height: '8px', background: Tcl1.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                      <div style={{ width: `${c.pct}%`, height: '100%', background: c.pct === 100 ? esi.emerald : c.pct >= 75 ? `linear-gradient(90deg, ${esi.cyan}, ${esi.teal})` : esi.amber }} />
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontFamily: Tcl1.font.mono, fontSize: '13px', fontWeight: 700, color: Tcl1.color.text.primary }}>{esi.bytes(c.volumeGB)}</div>
                    <div style={{ fontSize: '10px', color: Tcl1.color.text.tertiary }}>total scoped</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: '11px', color: Tcl1.color.text.secondary }}>{c.sourcesInProgress > 0 ? <span style={{ color: esi.cyan }}>{c.sourcesInProgress} in progress</span> : c.sourcesScheduled > 0 ? <span style={{ color: esi.amber }}>{c.sourcesScheduled} scheduled</span> : <span style={{ color: esi.emerald }}>all done</span>}</div>
                  </div>
                  <div><span style={{ ...esi.tag, background: sc.bg, color: sc.color }}>{c.status}</span></div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.CollectionsOverview = CollectionsOverview;
window.CollectionsJobs = CollectionsJobs;
window.CollectionsCustodians = CollectionsCustodians;
