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

// ── PRODUCTION TRACKER ──
function EvidenceProduction({ data }) {
  const [hovered, setHovered] = useState(null);
  const prods = data.productions;
  const totalSent = prods.filter(p => p.direction === 'Sent');
  const totalReceived = prods.filter(p => p.direction === 'Received');
  const sentDocs = totalSent.reduce((s, p) => s + p.docs, 0);
  const recDocs = totalReceived.reduce((s, p) => s + p.docs, 0);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={ev.stat}><span style={ev.statLabel}>Productions</span><span style={ev.statValue}>{prods.length}</span></div>
        <div style={ev.stat}><span style={ev.statLabel}>Docs Sent</span><span style={{ ...ev.statValue, color: '#3B82F6' }}>{sentDocs.toLocaleString()}</span></div>
        <div style={ev.stat}><span style={ev.statLabel}>Docs Received</span><span style={{ ...ev.statValue, color: ev.teal }}>{recDocs.toLocaleString()}</span></div>
        <div style={ev.stat}><span style={ev.statLabel}>Under Review</span><span style={{ ...ev.statValue, color: T.color.status.warning }}>{prods.filter(p => p.status === 'Under Review').length}</span></div>
        <div style={ev.stat}><span style={ev.statLabel}>Challenged</span><span style={{ ...ev.statValue, color: '#C23030' }}>{prods.filter(p => p.status === 'Under Challenge').length}</span></div>
      </div>

      <div style={ev.card}>
        <div style={ev.cardH}><span>Production Log</span></div>
        <div style={{ display: 'grid', gridTemplateColumns: '80px 1fr 100px 80px 80px 80px 90px', 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>Direction</span><span>Production</span><span>Bates Range</span><span>Docs</span><span>Pages</span><span>Size</span><span>Status</span>
        </div>
        {prods.map((p, i) => {
          const dirColor = p.direction === 'Sent' ? '#3B82F6' : ev.teal;
          const stColor = p.status === 'Complete' ? T.color.status.active : p.status === 'Under Challenge' ? '#C23030' : T.color.status.warning;
          return (
            <div key={i} style={{ display: 'grid', gridTemplateColumns: '80px 1fr 100px 80px 80px 80px 90px', padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, alignItems: 'center', gap: '8px', fontSize: '12px', background: hovered === i ? T.color.bg.hover : 'transparent' }}
              onMouseEnter={() => setHovered(i)} onMouseLeave={() => setHovered(null)}>
              <span style={{ fontSize: '10px', padding: '2px 8px', borderRadius: '8px', background: `${dirColor}10`, color: dirColor, fontWeight: 600 }}>{p.direction === 'Sent' ? '↑ Sent' : '↓ Received'}</span>
              <div>
                <div style={{ fontWeight: 500, color: T.color.text.primary }}>{p.name}</div>
                <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{p.date}{p.recipient ? ` → ${p.recipient}` : ''}</div>
              </div>
              <span style={{ fontFamily: T.font.mono, fontSize: '9px', color: T.color.text.tertiary }}>{p.batesRange.length > 20 ? p.batesRange.slice(0, 20) + '…' : p.batesRange}</span>
              <span style={{ fontFamily: T.font.mono, fontWeight: 600, color: T.color.text.primary }}>{p.docs.toLocaleString()}</span>
              <span style={{ fontFamily: T.font.mono, fontSize: '11px', color: T.color.text.secondary }}>{p.pages.toLocaleString()}</span>
              <span style={{ fontSize: '11px', color: T.color.text.secondary }}>{p.size}</span>
              <span style={{ fontSize: '10px', padding: '2px 8px', borderRadius: '8px', background: `${stColor}10`, color: stColor, fontWeight: 600 }}>{p.status}</span>
            </div>
          );
        })}
      </div>

      {/* Privilege log summary */}
      <div style={ev.card}>
        <div style={ev.cardH}><span>Privilege Dispute Summary</span></div>
        <div style={{ padding: '14px 16px' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '12px', marginBottom: '12px' }}>
            <div style={{ padding: '10px 12px', background: T.color.bg.secondary, borderRadius: '6px', border: `1px solid ${T.color.border.light}` }}>
              <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Docs Withheld</div>
              <div style={{ fontSize: '18px', fontWeight: 700, color: '#A855F7' }}>23</div>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>Attorney-client privilege</div>
            </div>
            <div style={{ padding: '10px 12px', background: T.color.bg.secondary, borderRadius: '6px', border: `1px solid ${T.color.border.light}` }}>
              <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Work Product</div>
              <div style={{ fontSize: '18px', fontWeight: 700, color: '#A855F7' }}>8</div>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>Potentially challengeable</div>
            </div>
            <div style={{ padding: '10px 12px', background: T.color.bg.secondary, borderRadius: '6px', border: `1px solid ${T.color.border.light}` }}>
              <div style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Gaps Identified</div>
              <div style={{ fontSize: '18px', fontWeight: 700, color: '#C23030' }}>3</div>
              <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>Q3 2022 records missing</div>
            </div>
          </div>
          <div style={{ padding: '10px 12px', background: ev.tealBg, borderRadius: '6px', fontSize: '12px', color: T.color.text.secondary, lineHeight: 1.5 }}>
            <span style={{ fontWeight: 600, color: ev.teal }}>◆ AI Analysis: </span>
            Defense privilege log contains 3 entries potentially subject to crime-fraud exception. Board communications from Sept–Oct 2023 may fall outside privilege if they furthered the alleged fraud. Recommend targeted motion to compel on entries #14, #31, #47.
          </div>
        </div>
      </div>
    </div>
  );
}

// ── TRANSCRIPT MANAGER ──
function EvidenceTranscripts({ data }) {
  const [expandedExcerpt, setExpandedExcerpt] = useState(null);
  const [searchQ, setSearchQ] = useState('');
  const transcripts = data.transcripts;

  return (
    <div>
      {transcripts.map(tr => {
        const filteredExcerpts = searchQ
          ? tr.keyExcerpts.filter(e => e.text.toLowerCase().includes(searchQ.toLowerCase()) || e.topic.toLowerCase().includes(searchQ.toLowerCase()))
          : tr.keyExcerpts;

        return (
          <div key={tr.id}>
            {/* Transcript header */}
            <div style={ev.card}>
              <div style={ev.cardH}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                  <span style={{ fontWeight: 700, color: T.color.text.primary }}>{tr.witness}</span>
                  <span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{tr.role}</span>
                </div>
                <div style={{ display: 'flex', gap: '12px', fontSize: '10px', color: T.color.text.tertiary }}>
                  <span>{tr.date}</span>
                  <span>{tr.duration}</span>
                  <span>{tr.pages} pages</span>
                  <span style={{ padding: '2px 8px', borderRadius: '8px', background: T.color.status.activeBg, color: T.color.status.active, fontWeight: 600 }}>{tr.status}</span>
                </div>
              </div>
              <div style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}` }}>
                <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                  {tr.topics.map((t, i) => (
                    <span key={i} style={{ fontSize: '10px', padding: '2px 8px', borderRadius: '10px', background: ev.tealBg, color: ev.teal, fontWeight: 500 }}>{t}</span>
                  ))}
                </div>
              </div>
            </div>

            {/* Search */}
            <div style={{ marginBottom: '12px' }}>
              <input style={{ height: '32px', border: `1px solid ${T.color.border.light}`, borderRadius: T.radius.md, padding: '0 12px', fontSize: '12px', fontFamily: T.font.family, background: T.color.bg.card, color: T.color.text.primary, outline: 'none', width: '300px' }} placeholder="Search transcript excerpts..." value={searchQ} onChange={e => setSearchQ(e.target.value)} />
            </div>

            {/* Key excerpts */}
            <div style={ev.card}>
              <div style={ev.cardH}><span>Key Excerpts</span><span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{filteredExcerpts.length} flagged passages</span></div>
              {filteredExcerpts.map((ex, i) => {
                const flagColor = { critical: '#C23030', high: '#B8860B', medium: '#6E7D9E' }[ex.flag];
                return (
                  <div key={i} style={{ padding: '10px 16px', borderBottom: `1px solid ${T.color.border.light}`, cursor: 'pointer', background: expandedExcerpt === i ? T.color.bg.hover : 'transparent' }} onClick={() => setExpandedExcerpt(expandedExcerpt === i ? null : i)}>
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: '10px', marginBottom: '4px' }}>
                      <span style={{ fontFamily: T.font.mono, fontSize: '10px', fontWeight: 700, color: T.color.text.tertiary, minWidth: '50px' }}>p.{ex.page}:{ex.line}</span>
                      <span style={{ fontSize: '10px', padding: '2px 8px', borderRadius: '8px', background: `${flagColor}10`, color: flagColor, fontWeight: 600 }}>{ex.flag}</span>
                      <span style={{ fontSize: '11px', fontWeight: 600, color: ev.teal }}>{ex.topic}</span>
                    </div>
                    <div style={{ fontSize: '12px', color: T.color.text.secondary, lineHeight: 1.5, paddingLeft: '60px' }}>
                      {ex.text}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })}

      {transcripts.length === 0 && (
        <div style={{ padding: '40px', textAlign: 'center', color: T.color.text.tertiary }}>No transcripts available for this matter.</div>
      )}
    </div>
  );
}

// ── RELATIONSHIP GRAPH (simplified visual) ──
function EvidenceGraph({ data }) {
  const [hoveredEntity, setHoveredEntity] = useState(null);
  const graph = data.entityGraph;

  const groupColors = { party: '#3B82F6', person: '#A855F7', entity: '#C23030', document: ev.teal, event: '#F59E0B' };
  const groupLabels = { party: 'Parties', person: 'People', entity: 'Entities', document: 'Documents', event: 'Key Events' };

  // Group entities
  const groups = {};
  graph.entities.forEach(e => {
    if (!groups[e.group]) groups[e.group] = [];
    groups[e.group].push(e);
  });

  // Get connections for hovered entity
  const hoveredConnections = hoveredEntity
    ? graph.connections.filter(c => c.from === hoveredEntity || c.to === hoveredEntity)
    : [];
  const connectedIds = new Set(hoveredConnections.flatMap(c => [c.from, c.to]));

  return (
    <div>
      {/* AI insight */}
      <div style={ev.card}>
        <div style={{ padding: '12px 16px', background: ev.tealBg, fontSize: '12px', color: T.color.text.secondary, lineHeight: 1.5 }}>
          <div style={{ fontSize: '10px', fontWeight: 600, color: ev.teal, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>◆ AI Relationship Analysis</div>
          Central node: James Harrington connects to all key entities — Meridian (CEO), Apex Ventures (sole director), the $14.2M transfers, and the Oct 2023 board meeting. This hub-and-spoke pattern is the strongest visual narrative for the jury: one person at the center of every fraudulent act.
        </div>
      </div>

      {/* Entity groups */}
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${Object.keys(groups).length}, 1fr)`, gap: '12px', marginBottom: '16px' }}>
        {Object.entries(groups).map(([group, entities]) => (
          <div key={group} style={ev.card}>
            <div style={{ padding: '8px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '6px' }}>
              <div style={{ width: '8px', height: '8px', borderRadius: '50%', background: groupColors[group] }} />
              <span style={{ fontSize: '10px', fontWeight: 600, color: T.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>{groupLabels[group]}</span>
            </div>
            {entities.map(e => {
              const isHighlighted = hoveredEntity === e.id || connectedIds.has(e.id);
              const connection = hoveredConnections.find(c => c.from === e.id || c.to === e.id);
              return (
                <div key={e.id} style={{
                  padding: '6px 16px', borderBottom: `1px solid ${T.color.border.light}`,
                  cursor: 'pointer', transition: 'all 0.15s',
                  background: hoveredEntity === e.id ? `${groupColors[group]}10` : isHighlighted ? T.color.bg.hover : 'transparent',
                  borderLeft: isHighlighted ? `3px solid ${groupColors[group]}` : '3px solid transparent',
                }} onMouseEnter={() => setHoveredEntity(e.id)} onMouseLeave={() => setHoveredEntity(null)}>
                  <div style={{ fontWeight: 600, fontSize: '12px', color: hoveredEntity === e.id ? groupColors[group] : T.color.text.primary }}>{e.name}</div>
                  <div style={{ fontSize: '10px', color: T.color.text.tertiary }}>{e.type}</div>
                  {connection && hoveredEntity !== e.id && (
                    <div style={{ fontSize: '9px', color: groupColors[group], marginTop: '2px', fontWeight: 500 }}>↔ {connection.label}</div>
                  )}
                </div>
              );
            })}
          </div>
        ))}
      </div>

      {/* Connection list */}
      <div style={ev.card}>
        <div style={ev.cardH}><span>All Relationships</span><span style={{ fontSize: '10px', color: T.color.text.tertiary }}>{graph.connections.length} connections</span></div>
        {graph.connections.map((c, i) => {
          const fromEntity = graph.entities.find(e => e.id === c.from);
          const toEntity = graph.entities.find(e => e.id === c.to);
          const isHighlighted = hoveredEntity && (c.from === hoveredEntity || c.to === hoveredEntity);
          return (
            <div key={i} style={{ padding: '6px 16px', borderBottom: `1px solid ${T.color.border.light}`, display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px', background: isHighlighted ? T.color.bg.hover : 'transparent' }}>
              <span style={{ fontWeight: 600, color: groupColors[fromEntity?.group], minWidth: '120px' }}>{fromEntity?.name}</span>
              <span style={{ color: T.color.text.tertiary, fontStyle: 'italic', flex: 1, textAlign: 'center' }}>{c.label}</span>
              <span style={{ fontWeight: 600, color: groupColors[toEntity?.group], minWidth: '120px', textAlign: 'right' }}>{toEntity?.name}</span>
              <div style={{ display: 'flex', gap: '2px' }}>
                {[1, 2, 3].map(w => (
                  <div key={w} style={{ width: '6px', height: '6px', borderRadius: '50%', background: w <= c.weight ? ev.teal : T.color.border.light }} />
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

Object.assign(window, { EvidenceProduction, EvidenceTranscripts, EvidenceGraph });
