// DISCOVERY PLATFORM — Custodians + Holds
const { useState: useDcCusState, useMemo: useDcCusMemo } = React;
const Tdc = window.ArbiterTokens;

function DiscoveryCustodians({ data }) {
  const dc = window.__dc;
  const [matterFilter, setMatterFilter] = useDcCusState('All');
  const [priorityFilter, setPriorityFilter] = useDcCusState('All');
  const matters = useDcCusMemo(() => ['All', ...new Set(data.custodians.map(c => c.matter))], [data]);
  const filtered = data.custodians.filter(c =>
    (matterFilter === 'All' || c.matter === matterFilter) &&
    (priorityFilter === 'All' || c.priority === priorityFilter)
  );

  const totalGB = data.custodians.reduce((s, c) => s + (c.volumeGB || 0), 0);
  const totalDocs = data.custodians.reduce((s, c) => s + (c.docCount || 0), 0);
  const pendingCount = data.custodians.filter(c => c.status.includes('Pending') || c.status.includes('subpoena')).length;

  const priorityColor = (p) => ({ key: { bg: dc.crimsonBg, color: dc.crimson }, high: { bg: dc.amberBg, color: dc.amber }, medium: { bg: Tdc.color.bg.secondary, color: Tdc.color.text.secondary } }[p] || { bg: Tdc.color.bg.secondary, color: Tdc.color.text.tertiary });

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={dc.stat}><span style={dc.statLabel}>Custodians (total)</span><span style={dc.statValue}>{data.kpis.custodians}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Tracked here</span><span style={dc.statValue}>{data.custodians.length}</span><span style={{ ...dc.statDelta, color: Tdc.color.text.tertiary }}>detail view</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Pending / special</span><span style={{ ...dc.statValue, color: dc.amber }}>{pendingCount}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Total collected</span><span style={dc.statValue}>{dc.bytes(totalGB)}</span><span style={{ ...dc.statDelta, color: Tdc.color.text.tertiary }}>{(totalDocs / 1_000_000).toFixed(2)}M docs</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Data sources</span><span style={dc.statValue}>{new Set(data.custodians.flatMap(c => c.sources)).size}</span><span style={{ ...dc.statDelta, color: Tdc.color.text.tertiary }}>distinct</span></div>
      </div>

      <div style={dc.card}>
        <div style={dc.cardH}>
          <span>Custodian roster — {filtered.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <select value={matterFilter} onChange={e => setMatterFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tdc.color.border.light}`, borderRadius: '5px', background: Tdc.color.bg.card, color: Tdc.color.text.secondary }}>
              {matters.map(m => <option key={m} value={m}>Matter: {m === 'All' ? 'All' : m.length > 20 ? m.slice(0, 18) + '…' : m}</option>)}
            </select>
            <select value={priorityFilter} onChange={e => setPriorityFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tdc.color.border.light}`, borderRadius: '5px', background: Tdc.color.bg.card, color: Tdc.color.text.secondary }}>
              {['All', 'key', 'high', 'medium'].map(p => <option key={p} value={p}>Priority: {p}</option>)}
            </select>
            <button style={dc.btnSecondary}>Export</button>
            <button style={dc.btnPrimary}>+ Add custodian</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={dc.th}>Custodian</th>
              <th style={dc.th}>Role / Org</th>
              <th style={dc.th}>Matter</th>
              <th style={dc.th}>Sources</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Volume</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Docs</th>
              <th style={dc.th}>Collected</th>
              <th style={dc.th}>Hold</th>
              <th style={dc.th}>Priority</th>
              <th style={dc.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(c => {
              const pc = priorityColor(c.priority);
              return (
                <tr key={c.id}>
                  <td style={{ ...dc.td, fontWeight: 600, color: Tdc.color.text.primary }}>
                    {c.name}
                    <div style={{ fontSize: '10px', fontFamily: Tdc.font.mono, color: Tdc.color.text.tertiary, marginTop: '2px' }}>{c.id}</div>
                  </td>
                  <td style={{ ...dc.td, color: Tdc.color.text.secondary, maxWidth: '200px' }}>
                    <div style={{ fontSize: '12px' }}>{c.role}</div>
                    <div style={{ fontSize: '10px', color: Tdc.color.text.tertiary }}>{c.org}</div>
                  </td>
                  <td style={{ ...dc.td, color: Tdc.color.text.secondary, maxWidth: '160px', fontSize: '11px' }}>{c.matter}</td>
                  <td style={dc.td}>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px', maxWidth: '200px' }}>
                      {c.sources.slice(0, 3).map(s => <span key={s} style={{ ...dc.tag, background: dc.cobaltBg, color: dc.cobalt }}>{s}</span>)}
                      {c.sources.length > 3 && <span style={{ fontSize: '10px', color: Tdc.color.text.tertiary }}>+{c.sources.length - 3}</span>}
                    </div>
                  </td>
                  <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdc.font.mono, color: Tdc.color.text.primary, fontWeight: 700 }}>{dc.bytes(c.volumeGB)}</td>
                  <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdc.font.mono, color: Tdc.color.text.secondary }}>{c.docCount ? c.docCount.toLocaleString() : '—'}</td>
                  <td style={{ ...dc.td, fontFamily: Tdc.font.mono, fontSize: '11px', color: Tdc.color.text.tertiary }}>{c.collectionDate || 'pending'}</td>
                  <td style={dc.td}>{c.holdAcked ? <span style={{ ...dc.tag, background: dc.emeraldBg, color: dc.emerald }}>ok ack</span> : <span style={{ ...dc.tag, background: dc.crimsonBg, color: dc.crimson }}>not ack</span>}</td>
                  <td style={dc.td}><span style={{ ...dc.tag, background: pc.bg, color: pc.color }}>{c.priority}</span></td>
                  <td style={{ ...dc.td, color: Tdc.color.text.secondary, fontSize: '11px', maxWidth: '220px' }}>{c.status}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function DiscoveryHolds({ data }) {
  const dc = window.__dc;
  const active = data.holds.filter(h => h.status === 'Active');
  const totalCovered = data.holds.reduce((s, h) => s + (h.status === 'Active' ? h.custodianCount : 0), 0);
  const totalAcked = data.holds.reduce((s, h) => s + (h.status === 'Active' ? h.acknowledged : 0), 0);
  const ackRate = totalCovered ? (totalAcked / totalCovered * 100) : 100;
  const pendingAck = active.filter(h => h.acknowledgedPct < 100);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={dc.stat}><span style={dc.statLabel}>Active holds</span><span style={dc.statValue}>{active.length}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Custodians covered</span><span style={dc.statValue}>{totalCovered}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Acknowledgement rate</span><span style={{ ...dc.statValue, color: ackRate >= 95 ? dc.emerald : dc.amber }}>{ackRate.toFixed(1)}%</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Pending acks</span><span style={{ ...dc.statValue, color: dc.amber }}>{pendingAck.length}</span><span style={{ ...dc.statDelta, color: Tdc.color.text.tertiary }}>holds awaiting full ack</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Released</span><span style={dc.statValue}>{data.holds.filter(h => h.status === 'Released').length}</span></div>
      </div>

      {/* Compliance banner */}
      <div style={{ ...dc.card, borderLeft: `3px solid ${dc.violet}`, background: dc.violetBg }}>
        <div style={{ padding: '12px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: '12px', fontWeight: 700, color: dc.violet, textTransform: 'uppercase', letterSpacing: '0.08em' }}>Preservation compliance — FRCP 37(e) / Zubulake</div>
            <div style={{ fontSize: '12px', color: Tdc.color.text.secondary, marginTop: '4px' }}>
              Monthly custodian audit · reminder cadence active · suspension logs preserved in IT chain of custody
            </div>
          </div>
          <div style={{ display: 'flex', gap: '10px' }}>
            <button style={dc.btnSecondary}>Audit report</button>
            <button style={dc.btnSecondary}>Reminder cadence</button>
            <button style={dc.btnPrimary}>+ New hold</button>
          </div>
        </div>
      </div>

      <div style={dc.card}>
        <div style={dc.cardH}>Litigation holds — {data.holds.length}</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={dc.th}>Hold</th>
              <th style={dc.th}>Matter</th>
              <th style={dc.th}>Issued</th>
              <th style={dc.th}>Scope</th>
              <th style={dc.th}>Custodians</th>
              <th style={dc.th}>Ack rate</th>
              <th style={dc.th}>Sources</th>
              <th style={dc.th}>Audit</th>
              <th style={dc.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {data.holds.map(h => {
              const ss = dc.statusColor(h.status);
              const ackColor = h.acknowledgedPct >= 95 ? dc.emerald : h.acknowledgedPct >= 80 ? dc.amber : dc.crimson;
              return (
                <tr key={h.id}>
                  <td style={{ ...dc.td, fontFamily: Tdc.font.mono, color: dc.violet, fontWeight: 700 }}>{h.id}</td>
                  <td style={{ ...dc.td, color: Tdc.color.text.primary, fontWeight: 500, maxWidth: '200px' }}>{h.matter}</td>
                  <td style={{ ...dc.td, fontFamily: Tdc.font.mono, fontSize: '11px', color: Tdc.color.text.secondary }}>
                    {h.issuedDate}
                    <div style={{ fontSize: '10px', color: Tdc.color.text.tertiary, marginTop: '2px' }}>by {h.issuedBy}</div>
                  </td>
                  <td style={{ ...dc.td, color: Tdc.color.text.secondary, fontSize: '11px', maxWidth: '280px', lineHeight: 1.5 }}>{h.scope}</td>
                  <td style={{ ...dc.td, textAlign: 'center', fontFamily: Tdc.font.mono, color: Tdc.color.text.primary, fontWeight: 700 }}>{h.custodianCount}</td>
                  <td style={dc.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <div style={{ width: '70px', height: '4px', background: Tdc.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                        <div style={{ width: `${h.acknowledgedPct}%`, height: '100%', background: ackColor }} />
                      </div>
                      <span style={{ fontFamily: Tdc.font.mono, fontSize: '11px', color: ackColor, fontWeight: 700, minWidth: '46px', textAlign: 'right' }}>{h.acknowledged}/{h.custodianCount}</span>
                    </div>
                  </td>
                  <td style={dc.td}>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px', maxWidth: '180px' }}>
                      {h.sources.slice(0, 3).map(s => <span key={s} style={{ ...dc.tag, background: dc.cobaltBg, color: dc.cobalt }}>{s}</span>)}
                      {h.sources.length > 3 && <span style={{ fontSize: '10px', color: Tdc.color.text.tertiary }}>+{h.sources.length - 3}</span>}
                    </div>
                  </td>
                  <td style={{ ...dc.td, fontFamily: Tdc.font.mono, fontSize: '11px', color: Tdc.color.text.tertiary }}>
                    {h.lastAudit}
                    {h.nextAudit && <div style={{ fontSize: '10px', color: Tdc.color.text.tertiary, marginTop: '2px' }}>next: {h.nextAudit}</div>}
                  </td>
                  <td style={dc.td}><span style={{ ...dc.tag, background: ss.bg, color: ss.color }}>{h.status}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.DiscoveryCustodians = DiscoveryCustodians;
window.DiscoveryHolds = DiscoveryHolds;
