// NEXUS PLATFORM — Patterns + Issues + Witnesses
const Tnp = window.ArbiterTokens;

function NexusPatterns({ data }) {
  const nx = window.__nx;
  const strengthColor = (s) => ({
    'Very strong': { bg: 'rgba(185,28,28,0.08)', color: nx.crimson },
    'Strong': { bg: nx.fuchsiaBg, color: nx.fuchsia },
    'Moderate': { bg: nx.eventBg, color: nx.event },
    'Emerging': { bg: nx.orgBg, color: nx.org },
    'Gap': { bg: Tnp.color.bg.secondary, color: Tnp.color.text.tertiary },
  }[s] || { bg: Tnp.color.bg.secondary, color: Tnp.color.text.secondary });

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={nx.stat}><span style={nx.statLabel}>Patterns detected</span><span style={nx.statValue}>{data.patterns.length}</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Very strong</span><span style={{ ...nx.statValue, color: nx.crimson }}>{data.patterns.filter(p => p.strength === 'Very strong').length}</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Strong</span><span style={{ ...nx.statValue, color: nx.fuchsia }}>{data.patterns.filter(p => p.strength === 'Strong').length}</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Avg confidence</span><span style={{ ...nx.statValue, color: nx.fuchsia }}>{(data.patterns.reduce((s, p) => s + p.confidence, 0) / data.patterns.length * 100).toFixed(0)}%</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Gaps to resolve</span><span style={{ ...nx.statValue, color: nx.event }}>{data.patterns.filter(p => p.strength === 'Gap').length}</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(380px, 1fr))', gap: '14px' }}>
        {data.patterns.map(p => {
          const sc = strengthColor(p.strength);
          return (
            <div key={p.id} style={{ ...nx.card, marginBottom: 0 }}>
              <div style={{ padding: '12px 14px', borderBottom: `1px solid ${Tnp.color.border.light}`, background: `linear-gradient(135deg, ${sc.bg} 0%, transparent 100%)` }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
                  <span style={{ ...nx.tag, background: sc.bg, color: sc.color, fontSize: '11px', padding: '3px 10px' }}>{p.strength}</span>
                  <span style={{ fontSize: '10px', fontFamily: Tnp.font.mono, color: Tnp.color.text.tertiary }}>{p.id}</span>
                </div>
                <div style={{ fontSize: '13px', fontWeight: 700, color: Tnp.color.text.primary }}>{p.name}</div>
                <div style={{ fontSize: '11px', color: Tnp.color.text.secondary, marginTop: '4px', lineHeight: 1.5 }}>{p.description}</div>
              </div>
              <div style={{ padding: '12px 14px' }}>
                <div style={{ fontSize: '11px', color: Tnp.color.text.secondary, lineHeight: 1.55, marginBottom: '10px' }}>{p.narrative}</div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px' }}>
                  <div>
                    <div style={{ fontSize: '9px', color: Tnp.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Entities</div>
                    <div style={{ fontSize: '14px', fontWeight: 700, color: Tnp.color.text.primary, fontFamily: Tnp.font.mono }}>{p.entitiesInvolved}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '9px', color: Tnp.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Confidence</div>
                    <div style={{ fontSize: '14px', fontWeight: 700, color: p.confidence >= 0.85 ? nx.emerald || '#059669' : p.confidence >= 0.70 ? nx.fuchsia : nx.event, fontFamily: Tnp.font.mono }}>{(p.confidence * 100).toFixed(0)}%</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '9px', color: Tnp.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Matter</div>
                    <div style={{ fontSize: '11px', fontWeight: 500, color: Tnp.color.text.primary, marginTop: '2px' }}>{p.matter.length > 14 ? p.matter.slice(0, 12) + '…' : p.matter}</div>
                  </div>
                </div>
                <div style={{ marginTop: '10px', paddingTop: '10px', borderTop: `1px solid ${Tnp.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <span style={{ fontSize: '10px', color: Tnp.color.text.tertiary }}>AI confidence</span>
                  <button style={nx.btnGhost}>Explore →</button>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function NexusIssues({ data }) {
  const nx = window.__nx;
  const issues = data.entities.filter(e => e.type === 'issue');
  const entityById = {}; data.entities.forEach(e => entityById[e.id] = e);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={nx.stat}><span style={nx.statLabel}>Legal issues</span><span style={{ ...nx.statValue, color: nx.issue }}>{issues.length}</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Counts / claims</span><span style={nx.statValue}>{issues.filter(i => i.name.startsWith('Count')).length}</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Avg supporting evidence</span><span style={nx.statValue}>{Math.round(issues.reduce((s, i) => s + i.linkCount, 0) / issues.length)}</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Key-priority issues</span><span style={{ ...nx.statValue, color: nx.issue }}>{issues.filter(i => i.priority === 'key').length}</span></div>
      </div>

      <div style={nx.card}>
        <div style={nx.cardH}>Legal issues ↔ supporting evidence</div>
        {issues.map(issue => {
          const supporting = data.links.filter(l => l.to === issue.id && (l.type === 'supports' || l.type === 'corroborates'));
          const rebutting = data.links.filter(l => l.to === issue.id && (l.type === 'rebuts' || l.type === 'contradicts'));
          return (
            <div key={issue.id} style={{ padding: '14px 16px', borderBottom: `1px solid ${Tnp.color.border.light}` }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: '8px' }}>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '3px' }}>
                    <span style={{ color: nx.issue, fontSize: '14px' }}><Icons.Star size={11}/></span>
                    <span style={{ fontSize: '13px', fontWeight: 700, color: Tnp.color.text.primary }}>{issue.name}</span>
                    <span style={{ ...nx.tag, background: nx.issueBg, color: nx.issue }}>{issue.priority}</span>
                  </div>
                  <div style={{ fontSize: '11px', color: Tnp.color.text.secondary, marginBottom: '4px' }}>{issue.summary}</div>
                  <div style={{ fontSize: '10px', color: Tnp.color.text.tertiary, fontFamily: Tnp.font.mono }}>{issue.id} · {issue.matter}</div>
                </div>
                <div style={{ display: 'flex', gap: '8px' }}>
                  <span style={{ ...nx.tag, background: nx.artifactBg, color: nx.artifact }}>↑ {supporting.length} supports</span>
                  {rebutting.length > 0 && <span style={{ ...nx.tag, background: nx.crimsonBg, color: nx.crimson }}>↓ {rebutting.length} rebuts</span>}
                </div>
              </div>
              {supporting.length > 0 && (
                <div style={{ marginTop: '8px', paddingLeft: '24px' }}>
                  <div style={{ fontSize: '9px', fontWeight: 700, color: Tnp.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>Supporting evidence</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
                    {supporting.map(l => {
                      const e = entityById[l.from];
                      if (!e) return null;
                      const ts = nx.typeStyle(e.type);
                      return <span key={l.id} style={{ ...nx.tag, background: ts.bg, color: ts.color }}>{ts.icon} {e.name}</span>;
                    })}
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function NexusWitnesses({ data }) {
  const nx = window.__nx;
  const entityById = {}; data.entities.forEach(e => entityById[e.id] = e);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={nx.stat}><span style={nx.statLabel}>Mapped witnesses</span><span style={{ ...nx.statValue, color: nx.person }}>{data.witnesses.length}</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Scheduled depos</span><span style={nx.statValue}>{data.witnesses.filter(w => w.depoId).length}</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Total exhibits</span><span style={nx.statValue}>{data.witnesses.reduce((s, w) => s + w.exhibits, 0)}</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Avg linked entities</span><span style={nx.statValue}>{Math.round(data.witnesses.reduce((s, w) => s + w.linkedEntities.length, 0) / data.witnesses.length)}</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(420px, 1fr))', gap: '14px' }}>
        {data.witnesses.map(w => {
          const person = entityById[w.personId];
          if (!person) return null;
          return (
            <div key={w.personId} style={{ ...nx.card, marginBottom: 0 }}>
              <div style={{ padding: '12px 14px', borderBottom: `1px solid ${Tnp.color.border.light}`, background: `linear-gradient(135deg, ${nx.personBg} 0%, transparent 100%)` }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                  <div style={{ width: '36px', height: '36px', borderRadius: '50%', background: nx.person, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '13px', fontWeight: 700 }}>
                    {person.name.split(' ').map(n => n[0]).join('').slice(0, 2)}
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: '13px', fontWeight: 700, color: Tnp.color.text.primary }}>{person.name}</div>
                    <div style={{ fontSize: '11px', color: Tnp.color.text.tertiary }}>{w.role} · {person.matter}</div>
                  </div>
                  {w.depoId && <span style={{ ...nx.tag, background: nx.fuchsiaBg, color: nx.fuchsia }}>{w.scheduled}</span>}
                </div>
              </div>
              <div style={{ padding: '12px 14px' }}>
                <div style={{ fontSize: '11px', color: Tnp.color.text.secondary, lineHeight: 1.55, marginBottom: '10px', fontStyle: 'italic' }}>“{w.narrative}”</div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '8px', marginBottom: '10px' }}>
                  <div>
                    <div style={{ fontSize: '9px', color: Tnp.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Exhibits</div>
                    <div style={{ fontSize: '14px', fontWeight: 700, color: Tnp.color.text.primary, fontFamily: Tnp.font.mono }}>{w.exhibits}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '9px', color: Tnp.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Deposition</div>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: w.depoId ? Tnp.color.text.primary : Tnp.color.text.tertiary, fontFamily: Tnp.font.mono }}>{w.depoId || 'not scheduled'}</div>
                  </div>
                </div>
                <div>
                  <div style={{ fontSize: '9px', fontWeight: 700, color: Tnp.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>Linked entities · {w.linkedEntities.length}</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px' }}>
                    {w.linkedEntities.map(id => {
                      const e = entityById[id];
                      if (!e) return null;
                      const ts = nx.typeStyle(e.type);
                      return <span key={id} style={{ ...nx.tag, background: ts.bg, color: ts.color }}>{ts.icon} {e.name.length > 18 ? e.name.slice(0, 16) + '…' : e.name}</span>;
                    })}
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.NexusPatterns = NexusPatterns;
window.NexusIssues = NexusIssues;
window.NexusWitnesses = NexusWitnesses;
