// DISCOVERY PLATFORM — Review batches + Privilege
const Tdrv = window.ArbiterTokens;

function DiscoveryReviewTab({ data }) {
  const dc = window.__dc;
  const totalAssigned = data.reviewBatches.reduce((s, b) => s + b.assigned, 0);
  const totalCompleted = data.reviewBatches.reduce((s, b) => s + b.completed, 0);
  const totalRemaining = data.reviewBatches.reduce((s, b) => s + b.remaining, 0);
  const overallPct = totalAssigned ? (totalCompleted / totalAssigned * 100) : 0;
  const avgQC = (data.reviewBatches.reduce((s, b) => s + b.qcPass, 0) / data.reviewBatches.length).toFixed(1);
  const totalRate = data.reviewers.reduce((s, r) => s + r.rate, 0);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={dc.stat}><span style={dc.statLabel}>Batches</span><span style={dc.statValue}>{data.reviewBatches.length}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Docs assigned</span><span style={dc.statValue}>{(totalAssigned / 1_000_000).toFixed(2)}M</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Completed</span><span style={{ ...dc.statValue, color: dc.emerald }}>{(totalCompleted / 1_000_000).toFixed(2)}M</span><span style={{ ...dc.statDelta, color: Tdrv.color.text.tertiary }}>{overallPct.toFixed(1)}%</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Remaining</span><span style={{ ...dc.statValue, color: dc.amber }}>{(totalRemaining / 1000).toFixed(0)}K</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>QC pass rate</span><span style={{ ...dc.statValue, color: avgQC >= 95 ? dc.emerald : dc.amber }}>{avgQC}%</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Review rate</span><span style={dc.statValue}>{totalRate.toLocaleString()}</span><span style={{ ...dc.statDelta, color: Tdrv.color.text.tertiary }}>docs/hr peak</span></div>
      </div>

      {/* Batches */}
      <div style={dc.card}>
        <div style={dc.cardH}>
          <span>Active review batches — {data.reviewBatches.length}</span>
          <button style={dc.btnPrimary}>+ New batch</button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={dc.th}>Batch</th>
              <th style={dc.th}>Matter</th>
              <th style={dc.th}>Team</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Assigned</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Completed</th>
              <th style={dc.th}>Progress</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Rate/hr</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>QC pass</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Hot-doc %</th>
              <th style={dc.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {data.reviewBatches.map(b => {
              const ss = dc.statusColor(b.status);
              const pctColor = b.pct >= 90 ? dc.emerald : b.pct >= 60 ? dc.cobalt : dc.amber;
              return (
                <tr key={b.id}>
                  <td style={{ ...dc.td, fontFamily: Tdrv.font.mono, color: dc.cobalt, fontWeight: 700 }}>{b.id}</td>
                  <td style={{ ...dc.td, color: Tdrv.color.text.primary, fontWeight: 500, maxWidth: '180px', fontSize: '11px' }}>{b.matter}</td>
                  <td style={{ ...dc.td, color: Tdrv.color.text.secondary, fontSize: '11px', maxWidth: '220px' }}>{b.team}</td>
                  <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdrv.font.mono, color: Tdrv.color.text.primary }}>{b.assigned.toLocaleString()}</td>
                  <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdrv.font.mono, color: dc.emerald, fontWeight: 600 }}>{b.completed.toLocaleString()}</td>
                  <td style={dc.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <div style={{ width: '80px', height: '4px', background: Tdrv.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                        <div style={{ width: `${b.pct}%`, height: '100%', background: pctColor }} />
                      </div>
                      <span style={{ fontFamily: Tdrv.font.mono, fontSize: '11px', color: pctColor, fontWeight: 700, minWidth: '46px', textAlign: 'right' }}>{b.pct.toFixed(1)}%</span>
                    </div>
                  </td>
                  <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdrv.font.mono, color: Tdrv.color.text.secondary }}>{b.rate}</td>
                  <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdrv.font.mono, color: b.qcPass >= 95 ? dc.emerald : dc.amber, fontWeight: 700 }}>{b.qcPass.toFixed(1)}%</td>
                  <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdrv.font.mono, color: b.hotDocRate != null && b.hotDocRate > 5 ? dc.crimson : Tdrv.color.text.secondary, fontWeight: b.hotDocRate > 5 ? 700 : 500 }}>{b.hotDocRate != null ? `${b.hotDocRate}%` : '—'}</td>
                  <td style={dc.td}><span style={{ ...dc.tag, background: ss.bg, color: ss.color }}>{b.status}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Reviewer leaderboard */}
      <div style={dc.card}>
        <div style={dc.cardH}>Reviewer throughput</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={dc.th}>Reviewer</th>
              <th style={dc.th}>Role</th>
              <th style={dc.th}>Matter</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Docs reviewed</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Rate/hr</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>QC pass</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Hot docs</th>
            </tr>
          </thead>
          <tbody>
            {data.reviewers.map(r => (
              <tr key={r.name}>
                <td style={{ ...dc.td, fontWeight: 600, color: Tdrv.color.text.primary }}>{r.name}</td>
                <td style={{ ...dc.td, color: Tdrv.color.text.secondary }}>{r.role}</td>
                <td style={{ ...dc.td, color: Tdrv.color.text.secondary, fontSize: '11px' }}>{r.matter}</td>
                <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdrv.font.mono, color: Tdrv.color.text.primary, fontWeight: 700 }}>{r.docsReviewed.toLocaleString()}</td>
                <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdrv.font.mono, color: dc.cobalt, fontWeight: 700 }}>{r.rate.toLocaleString()}</td>
                <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdrv.font.mono, color: r.qcPass >= 97 ? dc.emerald : dc.amber, fontWeight: 700 }}>{r.qcPass.toFixed(1)}%</td>
                <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdrv.font.mono, color: Tdrv.color.text.secondary }}>{r.hotDocs.toLocaleString()}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function DiscoveryPrivilege({ data }) {
  const dc = window.__dc;
  const p = data.privilegeLog;
  const maxCat = Math.max(...p.byCategory.map(c => c.count));

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={dc.stat}><span style={dc.statLabel}>Total entries</span><span style={dc.statValue}>{p.total.toLocaleString()}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>In review queue</span><span style={{ ...dc.statValue, color: dc.amber }}>{p.review.queued + p.review.inProgress}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Client review</span><span style={{ ...dc.statValue, color: dc.violet }}>{p.review.clientReview}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Challenged by opp.</span><span style={{ ...dc.statValue, color: dc.crimson }}>{p.byMatter.reduce((s, m) => s + m.challengedByOpposing, 0)}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Clawbacks filed</span><span style={{ ...dc.statValue, color: dc.crimson }}>{p.clawbacks.length}</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
        {/* By category */}
        <div style={dc.card}>
          <div style={dc.cardH}>By privilege category</div>
          <div style={{ padding: '12px 16px' }}>
            {p.byCategory.map(c => (
              <div key={c.category} style={{ padding: '6px 0', borderBottom: `1px solid ${Tdrv.color.border.light}` }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px', fontSize: '12px' }}>
                  <span style={{ color: Tdrv.color.text.primary, fontWeight: 500 }}>{c.category}</span>
                  <span style={{ display: 'flex', gap: '10px', fontFamily: Tdrv.font.mono }}>
                    <span style={{ color: Tdrv.color.text.secondary, fontSize: '11px' }}>{c.count.toLocaleString()}</span>
                    <span style={{ color: dc.violet, fontWeight: 700, fontSize: '11px', minWidth: '42px', textAlign: 'right' }}>{c.pct.toFixed(1)}%</span>
                  </span>
                </div>
                <div style={{ height: '5px', background: Tdrv.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                  <div style={{ width: `${(c.count / maxCat) * 100}%`, height: '100%', background: dc.violet }} />
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Review pipeline */}
        <div style={dc.card}>
          <div style={dc.cardH}>Privilege review pipeline</div>
          <div style={{ padding: '14px 16px' }}>
            {[
              { label: 'Queued', value: p.review.queued, color: dc.slate },
              { label: 'In Progress', value: p.review.inProgress, color: dc.cobalt },
              { label: 'Client Review', value: p.review.clientReview, color: dc.violet },
              { label: 'Ready to log', value: p.review.ready, color: dc.amber },
              { label: 'Produced on log', value: p.review.produced, color: dc.emerald },
            ].map(s => {
              const total = p.review.queued + p.review.inProgress + p.review.clientReview + p.review.ready + p.review.produced;
              const pct = total > 0 ? (s.value / total) * 100 : 0;
              return (
                <div key={s.label} style={{ padding: '6px 0', borderBottom: `1px solid ${Tdrv.color.border.light}` }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '12px', marginBottom: '4px' }}>
                    <span style={{ color: Tdrv.color.text.primary, fontWeight: 500 }}>{s.label}</span>
                    <span style={{ fontFamily: Tdrv.font.mono, color: s.color, fontWeight: 700 }}>{s.value}</span>
                  </div>
                  <div style={{ height: '5px', background: Tdrv.color.border.light, borderRadius: '2px', overflow: 'hidden' }}>
                    <div style={{ width: `${pct}%`, height: '100%', background: s.color }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* By matter */}
      <div style={dc.card}>
        <div style={dc.cardH}>Privilege log by matter</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={dc.th}>Matter</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Entries</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Withheld</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Produced on log</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Challenged</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Clawed back</th>
            </tr>
          </thead>
          <tbody>
            {p.byMatter.map(m => (
              <tr key={m.matter}>
                <td style={{ ...dc.td, fontWeight: 600, color: Tdrv.color.text.primary }}>{m.matter}</td>
                <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdrv.font.mono, color: Tdrv.color.text.primary, fontWeight: 700 }}>{m.entries.toLocaleString()}</td>
                <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdrv.font.mono, color: dc.violet }}>{m.withheld.toLocaleString()}</td>
                <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdrv.font.mono, color: dc.emerald }}>{m.produced}</td>
                <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdrv.font.mono, color: m.challengedByOpposing > 0 ? dc.amber : Tdrv.color.text.tertiary }}>{m.challengedByOpposing}</td>
                <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdrv.font.mono, color: m.clawed > 0 ? dc.crimson : Tdrv.color.text.tertiary, fontWeight: m.clawed > 0 ? 700 : 500 }}>{m.clawed}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Clawbacks */}
      <div style={{ ...dc.card, borderLeft: `3px solid ${dc.crimson}` }}>
        <div style={{ ...dc.cardH, color: dc.crimson }}>! Active clawback notices — FRE 502(d)</div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={dc.th}>Notice</th>
              <th style={dc.th}>Matter</th>
              <th style={dc.th}>Bates</th>
              <th style={dc.th}>Reason</th>
              <th style={dc.th}>Notified</th>
              <th style={dc.th}>Ack</th>
              <th style={dc.th}>Ack date</th>
            </tr>
          </thead>
          <tbody>
            {p.clawbacks.map(c => (
              <tr key={c.id}>
                <td style={{ ...dc.td, fontFamily: Tdrv.font.mono, color: dc.crimson, fontWeight: 700 }}>{c.id}</td>
                <td style={{ ...dc.td, color: Tdrv.color.text.primary }}>{c.matter}</td>
                <td style={{ ...dc.td, fontFamily: Tdrv.font.mono, fontSize: '11px', color: Tdrv.color.text.secondary }}>{c.bates}</td>
                <td style={{ ...dc.td, color: Tdrv.color.text.secondary, fontSize: '11px' }}>{c.reason}</td>
                <td style={{ ...dc.td, fontFamily: Tdrv.font.mono, fontSize: '11px', color: Tdrv.color.text.tertiary }}>{c.notified}</td>
                <td style={dc.td}>{c.acknowledged ? <span style={{ ...dc.tag, background: dc.emeraldBg, color: dc.emerald }}><Icons.Check size={11}/></span> : <span style={{ ...dc.tag, background: dc.crimsonBg, color: dc.crimson }}>pending</span>}</td>
                <td style={{ ...dc.td, fontFamily: Tdrv.font.mono, fontSize: '11px', color: Tdrv.color.text.tertiary }}>{c.ackDate || '—'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.DiscoveryReviewTab = DiscoveryReviewTab;
window.DiscoveryPrivilege = DiscoveryPrivilege;
