// DISCOVERY PLATFORM — Dashboard + Requests
const { useState: useDcDashState, useMemo: useDcDashMemo } = React;
const Tdd = window.ArbiterTokens;

function DiscoveryDashboard({ data }) {
  const dc = window.__dc;
  const k = data.kpis;

  // EDRM stage summary — which matters are in which stages
  const stages = [
    { name: 'Identify', count: 0 },
    { name: 'Preserve', count: data.holds.filter(h => h.status === 'Active').length },
    { name: 'Collect', count: data.collections.filter(c => c.status !== 'Complete').length },
    { name: 'Process', count: data.processing.activeJobs.length },
    { name: 'Review', count: data.reviewBatches.filter(b => b.status === 'In Progress').length },
    { name: 'Analyze', count: data.tarModels.filter(t => t.status === 'Production' || t.status === 'Validation').length },
    { name: 'Produce', count: data.productions.filter(p => p.status === 'In Prep' || p.status === 'In QC').length },
    { name: 'Present', count: data.depositions.filter(d => d.status === 'Scheduled').length },
  ];

  // Processing pipeline funnel
  const proc = data.processing.stages;

  return (
    <div>
      {/* KPI strip — 6 cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={dc.stat}><span style={dc.statLabel}>Active matters</span><span style={dc.statValue}>{k.activeMatters}</span><span style={{ ...dc.statDelta, color: Tdd.color.text.tertiary }}>in discovery</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Corpus</span><span style={dc.statValue}>{(k.corpusDocs / 1_000_000).toFixed(1)}M</span><span style={{ ...dc.statDelta, color: Tdd.color.text.tertiary }}>{dc.bytes(k.corpusGB)} ingested</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Reviewed</span><span style={{ ...dc.statValue, color: dc.emerald }}>{(k.docsReviewed / 1_000_000).toFixed(2)}M</span><span style={{ ...dc.statDelta, color: Tdd.color.text.tertiary }}>{(k.docsRemaining / 1000).toFixed(0)}K remaining</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Review rate</span><span style={dc.statValue}>{k.reviewRate.toLocaleString()}</span><span style={{ ...dc.statDelta, color: Tdd.color.text.tertiary }}>docs/hr · QC {k.reviewQCPass}%</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Productions shipped</span><span style={{ ...dc.statValue, color: dc.emerald }}>{k.productionsShipped}</span><span style={{ ...dc.statDelta, color: Tdd.color.text.tertiary }}>{(k.batesProduced / 1_000_000).toFixed(2)}M Bates</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Budget burn</span><span style={{ ...dc.statValue, color: k.budgetBurnPct > 75 ? dc.amber : dc.emerald }}>{k.budgetBurnPct}%</span><span style={{ ...dc.statDelta, color: Tdd.color.text.tertiary }}>${(k.budgetSpent / 1_000_000).toFixed(1)}M of ${(k.budgetAllocated / 1_000_000).toFixed(1)}M</span></div>
      </div>

      {/* EDRM stage bar */}
      <div style={dc.card}>
        <div style={dc.cardH}>EDRM workflow — active items by stage</div>
        <div style={{ padding: '14px 16px', display: 'flex', gap: '8px' }}>
          {stages.map((s, i) => {
            const sc = dc.edrmColor(s.name);
            return (
              <div key={s.name} style={{ flex: 1, position: 'relative' }}>
                <div style={{ padding: '10px 8px', background: sc.bg, border: `1px solid ${sc.color}22`, borderRadius: '6px', textAlign: 'center' }}>
                  <div style={{ fontSize: '9px', fontWeight: 700, color: sc.color, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '3px' }}>{s.name}</div>
                  <div style={{ fontSize: '20px', fontWeight: 700, color: sc.color, fontFamily: Tdd.font.mono }}>{s.count}</div>
                </div>
                {i < stages.length - 1 && (
                  <div style={{ position: 'absolute', right: '-6px', top: '50%', transform: 'translateY(-50%)', fontSize: '10px', color: Tdd.color.text.tertiary, pointerEvents: 'none' }}>›</div>
                )}
              </div>
            );
          })}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: '16px' }}>
        {/* Processing funnel */}
        <div style={dc.card}>
          <div style={dc.cardH}>
            <span>Corpus reduction funnel — {(proc[0].docs / 1_000_000).toFixed(1)}M → {(proc[proc.length - 1].docs / 1_000_000).toFixed(2)}M review-ready</span>
            <span style={{ fontSize: '10px', color: dc.emerald, fontWeight: 700, fontFamily: Tdd.font.mono }}>{proc[proc.length - 1].reductionPct}% reduction</span>
          </div>
          <div style={{ padding: '14px 16px' }}>
            {proc.map((s, i) => {
              const pct = (s.docs / proc[0].docs) * 100;
              const color = s.color === 'slate' ? dc.slate
                : s.color === 'teal' ? dc.teal
                : s.color === 'cobalt' ? dc.cobalt
                : s.color === 'violet' ? dc.violet
                : s.color === 'amber' ? dc.amber
                : dc.emerald;
              return (
                <div key={s.stage} style={{ marginBottom: '10px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', marginBottom: '4px' }}>
                    <span style={{ color: Tdd.color.text.primary, fontWeight: 600 }}>{i + 1}. {s.stage}</span>
                    <span style={{ display: 'flex', gap: '10px', fontFamily: Tdd.font.mono }}>
                      <span style={{ color: Tdd.color.text.secondary, fontSize: '11px' }}>{(s.docs / 1_000_000).toFixed(2)}M docs · {dc.bytes(s.volumeGB)}</span>
                      <span style={{ color, fontWeight: 700, fontSize: '11px', minWidth: '48px', textAlign: 'right' }}>{s.reductionPct > 0 ? `−${s.reductionPct}%` : '100%'}</span>
                    </span>
                  </div>
                  <div style={{ height: '18px', background: Tdd.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                    <div style={{ width: `${pct}%`, height: '100%', background: `linear-gradient(90deg, ${color} 0%, ${color}CC 100%)`, display: 'flex', alignItems: 'center', justifyContent: 'flex-end', paddingRight: '6px', color: '#fff', fontSize: '10px', fontWeight: 700 }}>
                      {pct >= 15 ? `${pct.toFixed(1)}%` : ''}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Alerts + compliance */}
        <div>
          <div style={{ ...dc.card, borderLeft: `3px solid ${dc.crimson}` }}>
            <div style={{ ...dc.cardH, color: dc.crimson }}>! Discovery alerts</div>
            <div style={{ padding: '10px 16px' }}>
              {[
                { label: 'Overdue responses', value: k.overdueResponses, color: dc.crimson },
                { label: 'Open disputes', value: k.openDisputes, color: dc.crimson },
                { label: 'Motions to compel', value: k.motionsToCompel, color: dc.amber },
                { label: 'Pending hold acks', value: k.pendingAcks, color: dc.amber },
                { label: 'Clawback notices', value: data.privilegeLog.clawbacks.filter(c => !c.acknowledged).length, color: dc.amber },
                { label: 'Processing errors', value: data.processing.errorQueue, color: dc.crimson },
              ].map(a => (
                <div key={a.label} style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', padding: '4px 0' }}>
                  <span style={{ color: Tdd.color.text.secondary }}>{a.label}</span>
                  <span style={{ color: a.color, fontWeight: 700, fontFamily: Tdd.font.mono }}>{a.value}</span>
                </div>
              ))}
            </div>
          </div>

          <div style={{ ...dc.card, borderLeft: `3px solid ${dc.cobalt}` }}>
            <div style={{ ...dc.cardH, color: dc.cobalt }}>Preservation compliance</div>
            <div style={{ padding: '10px 16px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', padding: '4px 0' }}>
                <span style={{ color: Tdd.color.text.secondary }}>Holds active</span>
                <span style={{ fontWeight: 700, color: Tdd.color.text.primary, fontFamily: Tdd.font.mono }}>{data.holds.filter(h => h.status === 'Active').length}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', padding: '4px 0' }}>
                <span style={{ color: Tdd.color.text.secondary }}>Custodians covered</span>
                <span style={{ fontWeight: 700, color: Tdd.color.text.primary, fontFamily: Tdd.font.mono }}>{k.custodiansOnHold} / {k.custodians}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', padding: '4px 0' }}>
                <span style={{ color: Tdd.color.text.secondary }}>Acknowledgement rate</span>
                <span style={{ fontWeight: 700, color: dc.emerald, fontFamily: Tdd.font.mono }}>{((data.holds.reduce((s, h) => s + h.acknowledged, 0) / data.holds.reduce((s, h) => s + h.custodianCount, 0)) * 100).toFixed(1)}%</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', padding: '4px 0' }}>
                <span style={{ color: Tdd.color.text.secondary }}>TAR models in production</span>
                <span style={{ fontWeight: 700, color: dc.cobalt, fontFamily: Tdd.font.mono }}>{data.tarModels.filter(t => t.status === 'Production').length}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Active processing jobs */}
      <div style={dc.card}>
        <div style={dc.cardH}>Active processing jobs — {data.processing.activeJobs.length}</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={dc.th}>Job</th>
              <th style={dc.th}>Matter</th>
              <th style={dc.th}>Stage</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>In flight</th>
              <th style={dc.th}>Started</th>
              <th style={dc.th}>ETA</th>
            </tr>
          </thead>
          <tbody>
            {data.processing.activeJobs.map(j => (
              <tr key={j.id}>
                <td style={{ ...dc.td, fontFamily: Tdd.font.mono, fontWeight: 600, color: dc.cobalt }}>{j.id}</td>
                <td style={{ ...dc.td, color: Tdd.color.text.primary, fontWeight: 500 }}>{j.matter}</td>
                <td style={dc.td}><span style={{ ...dc.tag, background: dc.cobaltBg, color: dc.cobalt }}>{j.stage}</span></td>
                <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdd.font.mono, color: Tdd.color.text.primary, fontWeight: 700 }}>{j.inflight.toLocaleString()}</td>
                <td style={{ ...dc.td, fontFamily: Tdd.font.mono, fontSize: '11px', color: Tdd.color.text.secondary }}>{j.started}</td>
                <td style={{ ...dc.td, fontFamily: Tdd.font.mono, fontSize: '11px', color: dc.amber }}>{j.eta}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function DiscoveryRequests({ data }) {
  const dc = window.__dc;
  const [dirFilter, setDirFilter] = useDcDashState('All');
  const [matterFilter, setMatterFilter] = useDcDashState('All');

  const matters = useDcDashMemo(() => ['All', ...new Set(data.requests.map(r => r.matter))], [data]);
  const filtered = data.requests.filter(r =>
    (dirFilter === 'All' || r.direction === dirFilter) &&
    (matterFilter === 'All' || r.matter === matterFilter)
  );

  const inbound = data.requests.filter(r => r.direction === 'Inbound');
  const outbound = data.requests.filter(r => r.direction === 'Outbound');
  const overdue = data.requests.filter(r => r.status === 'Overdue');

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={dc.stat}><span style={dc.statLabel}>Total requests</span><span style={dc.statValue}>{data.requests.length}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Inbound</span><span style={{ ...dc.statValue, color: dc.cobalt }}>{inbound.length}</span><span style={{ ...dc.statDelta, color: Tdd.color.text.tertiary }}>{inbound.reduce((s, r) => s + r.count, 0)} items</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Outbound</span><span style={{ ...dc.statValue, color: dc.emerald }}>{outbound.length}</span><span style={{ ...dc.statDelta, color: Tdd.color.text.tertiary }}>{outbound.reduce((s, r) => s + r.count, 0)} items</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Overdue</span><span style={{ ...dc.statValue, color: dc.crimson }}>{overdue.length}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Total items</span><span style={dc.statValue}>{data.requests.reduce((s, r) => s + r.count, 0)}</span><span style={{ ...dc.statDelta, color: Tdd.color.text.tertiary }}>RFPs / ROGs / RFAs</span></div>
      </div>

      <div style={dc.card}>
        <div style={dc.cardH}>
          <span>Discovery requests — {filtered.length} of {data.requests.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <select value={dirFilter} onChange={e => setDirFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tdd.color.border.light}`, borderRadius: '5px', background: Tdd.color.bg.card, color: Tdd.color.text.secondary }}>
              {['All', 'Inbound', 'Outbound'].map(d => <option key={d} value={d}>{d}</option>)}
            </select>
            <select value={matterFilter} onChange={e => setMatterFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tdd.color.border.light}`, borderRadius: '5px', background: Tdd.color.bg.card, color: Tdd.color.text.secondary }}>
              {matters.map(m => <option key={m} value={m}>Matter: {m === 'All' ? 'All' : m.length > 22 ? m.slice(0, 20) + '…' : m}</option>)}
            </select>
            <button style={dc.btnPrimary}>+ New request</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={dc.th}>Request</th>
              <th style={dc.th}>Type</th>
              <th style={dc.th}>Matter</th>
              <th style={dc.th}>Direction</th>
              <th style={dc.th}>Served</th>
              <th style={dc.th}>Due</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Items</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Objections</th>
              <th style={dc.th}>Meet-and-confer</th>
              <th style={dc.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(r => {
              const ss = dc.statusColor(r.status);
              const dirColor = r.direction === 'Inbound' ? { bg: dc.cobaltBg, color: dc.cobalt } : { bg: dc.emeraldBg, color: dc.emerald };
              return (
                <tr key={r.id}>
                  <td style={{ ...dc.td, fontFamily: Tdd.font.mono, color: Tdd.color.text.primary, fontWeight: 600 }}>{r.id}</td>
                  <td style={{ ...dc.td, color: Tdd.color.text.primary, fontWeight: 500 }}>{r.type}</td>
                  <td style={{ ...dc.td, color: Tdd.color.text.secondary, maxWidth: '200px' }}>{r.matter}</td>
                  <td style={dc.td}><span style={{ ...dc.tag, background: dirColor.bg, color: dirColor.color }}>{r.direction}</span></td>
                  <td style={{ ...dc.td, fontFamily: Tdd.font.mono, fontSize: '11px', color: Tdd.color.text.tertiary }}>{r.served}</td>
                  <td style={{ ...dc.td, fontFamily: Tdd.font.mono, fontSize: '11px', color: r.status === 'Overdue' ? dc.crimson : Tdd.color.text.secondary, fontWeight: r.status === 'Overdue' ? 700 : 500 }}>{r.due}</td>
                  <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdd.font.mono, color: Tdd.color.text.primary, fontWeight: 700 }}>{r.count}</td>
                  <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdd.font.mono, color: r.objections > 0 ? dc.amber : Tdd.color.text.tertiary }}>{r.objections ?? '—'}</td>
                  <td style={{ ...dc.td, color: Tdd.color.text.secondary, fontSize: '11px' }}>{r.meetConfer}</td>
                  <td style={dc.td}><span style={{ ...dc.tag, background: ss.bg, color: ss.color }}>{r.status}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.DiscoveryDashboard = DiscoveryDashboard;
window.DiscoveryRequests = DiscoveryRequests;
