const { useState } = React;
const T = window.ArbiterTokens;

// ── AI REVIEW PIPELINE ──
function EvidenceReview({ data }) {
  const rp = data.reviewPipeline;
  const total = rp.total;
  const coded = rp.stages.find(s => s.name === 'Final Coded')?.count || 0;
  const pctComplete = Math.round(((total - rp.stages[0].count) / total) * 100);

  return (
    <div>
      {/* Pipeline overview */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={ev.stat}><span style={ev.statLabel}>Total Documents</span><span style={ev.statValue}>{total.toLocaleString()}</span></div>
        <div style={ev.stat}><span style={ev.statLabel}>Review Progress</span><span style={{ ...ev.statValue, color: ev.teal }}>{pctComplete}%</span></div>
        <div style={ev.stat}><span style={ev.statLabel}>AI Auto-Tagged</span><span style={{ ...ev.statValue, color: '#3B82F6' }}>{rp.aiAssist.autoTagged.toLocaleString()}</span></div>
        <div style={ev.stat}><span style={ev.statLabel}>Contradictions Found</span><span style={{ ...ev.statValue, color: '#C23030' }}>{rp.aiAssist.contradictionsFound}</span></div>
        <div style={ev.stat}><span style={ev.statLabel}>Duplicates Detected</span><span style={{ ...ev.statValue, color: T.color.status.warning }}>{rp.aiAssist.duplicatesDetected}</span></div>
      </div>

      {/* Pipeline stages funnel */}
      <div style={ev.card}>
        <div style={ev.cardH}><span>Review Pipeline</span><span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{total.toLocaleString()} total documents</span></div>
        <div style={{ padding: '16px' }}>
          {/* Full progress bar */}
          <div style={{ display: 'flex', height: '24px', borderRadius: '6px', overflow: 'hidden', marginBottom: '16px' }}>
            {rp.stages.map((s, i) => (
              <div key={i} style={{ width: `${(s.count / total) * 100}%`, background: s.color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '9px', fontWeight: 700, color: '#fff', minWidth: s.count > 0 ? '30px' : '0' }}>
                {(s.count / total) > 0.08 && s.count.toLocaleString()}
              </div>
            ))}
          </div>
          {/* Legend */}
          <div style={{ display: 'flex', gap: '16px', flexWrap: 'wrap' }}>
            {rp.stages.map((s, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                <div style={{ width: '10px', height: '10px', borderRadius: '2px', background: s.color }} />
                <span style={{ fontSize: '11px', color: T.color.text.secondary }}>{s.name}</span>
                <span style={{ fontSize: '11px', fontFamily: T.font.mono, fontWeight: 600, color: T.color.text.primary }}>{s.count.toLocaleString()}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
        {/* Reviewer productivity */}
        <div style={ev.card}>
          <div style={ev.cardH}><span>Reviewer Performance</span></div>
          {rp.reviewers.map((r, i) => {
            const pct = Math.round((r.completed / r.assigned) * 100);
            return (
              <div key={i} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}` }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '4px' }}>
                  <span style={{ fontWeight: 600, fontSize: '12px', color: T.color.text.primary }}>{r.name}</span>
                  <div style={{ display: 'flex', gap: '12px', fontSize: '10px' }}>
                    <span style={{ color: T.color.text.tertiary }}>{r.rate} docs/hr</span>
                    <span style={{ color: T.color.text.tertiary }}>{r.hoursLogged}h logged</span>
                    <span style={{ fontFamily: T.font.mono, fontWeight: 600, color: pct >= 90 ? T.color.status.active : T.color.text.secondary }}>{r.completed.toLocaleString()}/{r.assigned.toLocaleString()}</span>
                  </div>
                </div>
                <div style={{ ...ev.barTrack, width: '100%' }}>
                  <div style={{ ...ev.barFill, width: `${pct}%`, background: pct >= 90 ? T.color.status.active : pct >= 70 ? ev.teal : T.color.status.warning }} />
                </div>
              </div>
            );
          })}
        </div>

        {/* Coding decisions */}
        <div style={ev.card}>
          <div style={ev.cardH}><span>Coding Decisions</span></div>
          <div style={{ padding: '12px 16px' }}>
            {Object.entries(rp.codingDecisions).map(([key, val]) => {
              const labels = { responsive: 'Responsive', nonResponsive: 'Non-Responsive', privileged: 'Privileged', needsRedaction: 'Needs Redaction', hotDoc: 'Hot Document', duplicate: 'Duplicate' };
              const colors = { responsive: T.color.status.active, nonResponsive: T.color.text.tertiary, privileged: '#A855F7', needsRedaction: T.color.status.warning, hotDoc: '#C23030', duplicate: '#6E7D9E' };
              const total2 = Object.values(rp.codingDecisions).reduce((s, v) => s + v, 0);
              return (
                <div key={key} style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '8px' }}>
                  <span style={{ width: '120px', fontSize: '11px', color: T.color.text.secondary }}>{labels[key]}</span>
                  <div style={{ flex: 1, ...ev.barTrack }}>
                    <div style={{ ...ev.barFill, width: `${(val / total2) * 100}%`, background: colors[key] }} />
                  </div>
                  <span style={{ minWidth: '40px', textAlign: 'right', fontSize: '11px', fontFamily: T.font.mono, fontWeight: 600, color: T.color.text.primary }}>{val.toLocaleString()}</span>
                </div>
              );
            })}
          </div>

          {/* AI assist summary */}
          <div style={{ padding: '12px 16px', background: ev.tealBg, borderTop: `1px solid ${T.color.border.light}` }}>
            <div style={{ fontSize: '10px', fontWeight: 600, color: ev.teal, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: '6px' }}>◆ AI Assist Summary</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '4px 16px', fontSize: '11px' }}>
              <span style={{ color: T.color.text.tertiary }}>Auto-tagged:</span><span style={{ fontWeight: 600 }}>{rp.aiAssist.autoTagged.toLocaleString()} docs</span>
              <span style={{ color: T.color.text.tertiary }}>Suggested privilege:</span><span style={{ fontWeight: 600 }}>{rp.aiAssist.suggestedPrivilege} flagged</span>
              <span style={{ color: T.color.text.tertiary }}>Suggested hot docs:</span><span style={{ fontWeight: 600, color: '#C23030' }}>{rp.aiAssist.suggestedHot} flagged</span>
              <span style={{ color: T.color.text.tertiary }}>Contradictions:</span><span style={{ fontWeight: 600, color: '#C23030' }}>{rp.aiAssist.contradictionsFound} found</span>
              <span style={{ color: T.color.text.tertiary }}>Duplicates:</span><span style={{ fontWeight: 600 }}>{rp.aiAssist.duplicatesDetected} detected</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── EXHIBIT BUILDER ──
function EvidenceExhibits({ data }) {
  const [hovered, setHovered] = useState(null);
  const exhibits = data.exhibits;

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={ev.stat}><span style={ev.statLabel}>Total Exhibits</span><span style={ev.statValue}>{exhibits.length}</span></div>
        <div style={ev.stat}><span style={ev.statLabel}>Pre-Marked</span><span style={{ ...ev.statValue, color: ev.teal }}>{exhibits.filter(e => e.status === 'Pre-Marked').length}</span></div>
        <div style={ev.stat}><span style={ev.statLabel}>Objections Pending</span><span style={{ ...ev.statValue, color: '#C23030' }}>{exhibits.filter(e => e.objection).length}</span></div>
        <div style={ev.stat}><span style={ev.statLabel}>Admitted</span><span style={{ ...ev.statValue, color: T.color.status.active }}>{exhibits.filter(e => e.admitted).length}</span></div>
      </div>

      <div style={ev.card}>
        <div style={ev.cardH}>
          <span>Trial Exhibit List</span>
          <button style={{ ...ev.filterBtn, ...ev.filterBtnActive }}>+ Add Exhibit</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '70px 1fr 100px 80px 80px', padding: '6px 16px', background: T.color.bg.secondary, borderBottom: `1px solid ${T.color.border.light}`, fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', gap: '8px' }}>
          <span>Exhibit #</span><span>Description</span><span>Status</span><span>Objection</span><span>Admitted</span>
        </div>
        {exhibits.map((ex, i) => (
          <div key={i} style={{ display: 'grid', gridTemplateColumns: '70px 1fr 100px 80px 80px', padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, alignItems: 'center', gap: '8px', fontSize: '12px', background: hovered === i ? T.color.bg.hover : 'transparent', cursor: 'pointer' }}
            onMouseEnter={() => setHovered(i)} onMouseLeave={() => setHovered(null)}>
            <span style={{ fontFamily: T.font.mono, fontWeight: 700, color: ev.teal }}>{ex.num}</span>
            <div>
              <div style={{ fontWeight: 500, color: T.color.text.primary }}>{ex.name}</div>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{ex.evId}</div>
            </div>
            <span style={{ fontSize: '10px', padding: '2px 8px', borderRadius: '8px', background: ev.tealBg, color: ev.teal, fontWeight: 600 }}>{ex.status}</span>
            <span style={{ fontSize: '10px' }}>
              {ex.objection ? <span style={{ padding: '2px 8px', borderRadius: '8px', background: 'rgba(194,48,48,0.06)', color: '#C23030', fontWeight: 600 }}>Objected</span> : <span style={{ color: T.color.text.tertiary }}>None</span>}
            </span>
            <span style={{ fontSize: '10px' }}>
              {ex.admitted ? <span style={{ padding: '2px 8px', borderRadius: '8px', background: T.color.status.activeBg, color: T.color.status.active, fontWeight: 600 }}>Yes</span> : <span style={{ color: T.color.text.tertiary }}>Pending</span>}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { EvidenceReview, EvidenceExhibits });
