// DISCOVERY PLATFORM — TAR + Productions
const Tdt = window.ArbiterTokens;

function DiscoveryTAR({ data }) {
  const dc = window.__dc;
  const prod = data.tarModels.filter(m => m.status === 'Production');
  const avgRecall = prod.length ? (prod.reduce((s, m) => s + (m.recall || 0), 0) / prod.length).toFixed(1) : '—';
  const avgPrecision = prod.length ? (prod.reduce((s, m) => s + (m.precision || 0), 0) / prod.length).toFixed(1) : '—';
  const totalClassified = data.tarModels.reduce((s, m) => s + m.docsClassified, 0);

  const statusColor = (s) => ({
    'Production': { bg: dc.emeraldBg, color: dc.emerald },
    'Validation': { bg: dc.amberBg, color: dc.amber },
    'Training': { bg: dc.cobaltBg, color: dc.cobalt },
  }[s] || { bg: Tdt.color.bg.secondary, color: Tdt.color.text.secondary });

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={dc.stat}><span style={dc.statLabel}>TAR models</span><span style={dc.statValue}>{data.tarModels.length}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>In production</span><span style={{ ...dc.statValue, color: dc.emerald }}>{prod.length}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Avg recall</span><span style={{ ...dc.statValue, color: dc.emerald }}>{avgRecall}%</span><span style={{ ...dc.statDelta, color: Tdt.color.text.tertiary }}>production models</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Avg precision</span><span style={{ ...dc.statValue, color: dc.cobalt }}>{avgPrecision}%</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Docs classified</span><span style={dc.statValue}>{(totalClassified / 1_000_000).toFixed(2)}M</span></div>
      </div>

      {/* Model cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(380px, 1fr))', gap: '14px' }}>
        {data.tarModels.map(m => {
          const sc = statusColor(m.status);
          return (
            <div key={m.id} style={{ ...dc.card, marginBottom: 0 }}>
              <div style={{ padding: '14px 16px', borderBottom: `1px solid ${Tdt.color.border.light}`, background: `linear-gradient(135deg, ${sc.bg} 0%, transparent 100%)` }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '6px' }}>
                  <span style={{ ...dc.tag, background: sc.bg, color: sc.color, fontSize: '11px', padding: '3px 10px' }}>{m.status}</span>
                  <span style={{ fontSize: '10px', fontFamily: Tdt.font.mono, color: Tdt.color.text.tertiary }}>{m.id}</span>
                </div>
                <div style={{ fontSize: '13px', fontWeight: 700, color: Tdt.color.text.primary }}>{m.matter}</div>
                <div style={{ fontSize: '11px', color: Tdt.color.text.tertiary, marginTop: '2px' }}>{m.type}</div>
              </div>
              <div style={{ padding: '14px 16px' }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '10px', marginBottom: '12px' }}>
                  <div>
                    <div style={{ fontSize: '9px', color: Tdt.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Recall</div>
                    <div style={{ fontSize: '16px', fontWeight: 700, color: m.recall >= 85 ? dc.emerald : dc.amber, fontFamily: Tdt.font.mono }}>{m.recall != null ? `${m.recall}%` : '—'}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '9px', color: Tdt.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Precision</div>
                    <div style={{ fontSize: '16px', fontWeight: 700, color: dc.cobalt, fontFamily: Tdt.font.mono }}>{m.precision != null ? `${m.precision}%` : '—'}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '9px', color: Tdt.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>F1</div>
                    <div style={{ fontSize: '16px', fontWeight: 700, color: dc.violet, fontFamily: Tdt.font.mono }}>{m.f1 != null ? m.f1.toFixed(1) : '—'}</div>
                  </div>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginBottom: '12px', paddingTop: '10px', borderTop: `1px solid ${Tdt.color.border.light}` }}>
                  <div>
                    <div style={{ fontSize: '9px', color: Tdt.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Training rounds</div>
                    <div style={{ fontSize: '13px', fontWeight: 600, color: Tdt.color.text.primary, fontFamily: Tdt.font.mono }}>{m.trainingRounds}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '9px', color: Tdt.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Stability</div>
                    <div style={{ fontSize: '13px', fontWeight: 600, color: m.stability === 'Stable' ? dc.emerald : m.stability === 'Stabilizing' ? dc.amber : dc.cobalt }}>{m.stability}</div>
                  </div>
                </div>
                <div style={{ marginBottom: '10px' }}>
                  <div style={{ fontSize: '10px', color: Tdt.color.text.tertiary, marginBottom: '2px' }}>Docs classified</div>
                  <div style={{ fontSize: '14px', fontWeight: 700, color: Tdt.color.text.primary, fontFamily: Tdt.font.mono }}>{(m.docsClassified / 1_000_000).toFixed(2)}M</div>
                  <div style={{ fontSize: '11px', color: dc.emerald, fontWeight: 600 }}>{m.relevantPredicted != null ? `${m.relevantPredicted.toLocaleString()} predicted relevant` : 'Classification pending'}</div>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: '10px', borderTop: `1px solid ${Tdt.color.border.light}`, fontSize: '10px', color: Tdt.color.text.tertiary }}>
                  <span>Validated by {m.validatedBy}</span>
                  <span>Last run: {m.lastRun}</span>
                </div>
                <div style={{ fontSize: '10px', color: Tdt.color.text.tertiary, marginTop: '4px' }}>Statistical report: {m.statReport}</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function DiscoveryProductions({ data }) {
  const dc = window.__dc;
  const totalDocs = data.productions.reduce((s, p) => s + p.docCount, 0);
  const totalGB = data.productions.reduce((s, p) => s + p.volumeGB, 0);
  const totalRedactions = data.productions.reduce((s, p) => s + p.redactions, 0);
  const sent = data.productions.filter(p => p.status === 'Sent' || p.status === 'Received').length;
  const inQC = data.productions.filter(p => p.status === 'In QC' || p.status === 'In Prep').length;

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={dc.stat}><span style={dc.statLabel}>Productions (total)</span><span style={dc.statValue}>{data.productions.length}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Shipped / received</span><span style={{ ...dc.statValue, color: dc.emerald }}>{sent}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>In QC / prep</span><span style={{ ...dc.statValue, color: dc.amber }}>{inQC}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Bates produced</span><span style={dc.statValue}>{totalDocs.toLocaleString()}</span><span style={{ ...dc.statDelta, color: Tdt.color.text.tertiary }}>{dc.bytes(totalGB)}</span></div>
        <div style={dc.stat}><span style={dc.statLabel}>Redactions applied</span><span style={{ ...dc.statValue, color: dc.violet }}>{totalRedactions.toLocaleString()}</span></div>
      </div>

      <div style={dc.card}>
        <div style={dc.cardH}>
          <span>Productions — {data.productions.length}</span>
          <button style={dc.btnPrimary}>+ Stage production</button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={dc.th}>Production</th>
              <th style={dc.th}>Matter</th>
              <th style={dc.th}>Bates range</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Docs</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Volume</th>
              <th style={dc.th}>Format</th>
              <th style={{ ...dc.th, textAlign: 'right' }}>Redactions</th>
              <th style={dc.th}>Priv log</th>
              <th style={dc.th}>Client approval</th>
              <th style={dc.th}>Sent</th>
              <th style={dc.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {data.productions.map(p => {
              const ss = dc.statusColor(p.status);
              const caColor = p.clientApproval === 'Approved' ? { bg: dc.emeraldBg, color: dc.emerald }
                : p.clientApproval === 'Pending' ? { bg: dc.amberBg, color: dc.amber }
                : { bg: Tdt.color.bg.secondary, color: Tdt.color.text.secondary };
              return (
                <tr key={p.id}>
                  <td style={{ ...dc.td, fontFamily: Tdt.font.mono, color: dc.cobalt, fontWeight: 700 }}>{p.id}</td>
                  <td style={{ ...dc.td, color: Tdt.color.text.primary, fontWeight: 500, maxWidth: '160px', fontSize: '11px' }}>{p.matter}</td>
                  <td style={{ ...dc.td, fontFamily: Tdt.font.mono, fontSize: '11px', color: Tdt.color.text.secondary }}>{p.batesRange}</td>
                  <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdt.font.mono, color: Tdt.color.text.primary, fontWeight: 700 }}>{p.docCount.toLocaleString()}</td>
                  <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdt.font.mono, color: Tdt.color.text.secondary }}>{dc.bytes(p.volumeGB)}</td>
                  <td style={{ ...dc.td, color: Tdt.color.text.secondary, fontSize: '11px' }}>{p.loadFormat}</td>
                  <td style={{ ...dc.td, textAlign: 'right', fontFamily: Tdt.font.mono, color: dc.violet, fontWeight: 600 }}>{p.redactions.toLocaleString()}</td>
                  <td style={dc.td}>{p.privLog ? <span style={{ ...dc.tag, background: dc.violetBg, color: dc.violet }}><Icons.Check size={11}/></span> : <span style={{ fontSize: '10px', color: Tdt.color.text.tertiary }}>—</span>}</td>
                  <td style={dc.td}><span style={{ ...dc.tag, background: caColor.bg, color: caColor.color }}>{p.clientApproval}</span></td>
                  <td style={{ ...dc.td, fontFamily: Tdt.font.mono, fontSize: '11px', color: Tdt.color.text.tertiary }}>{p.sentDate || '—'}</td>
                  <td style={dc.td}><span style={{ ...dc.tag, background: ss.bg, color: ss.color }}>{p.status}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.DiscoveryTAR = DiscoveryTAR;
window.DiscoveryProductions = DiscoveryProductions;
