// NEXUS PLATFORM — Hypotheses + Matrix + Activity
const Tna = window.ArbiterTokens;

function NexusHypotheses({ data }) {
  const nx = window.__nx;
  const strengthColor = (s) => ({
    'Primary': { bg: nx.artifactBg, color: nx.artifact },
    'Primary defense': { bg: nx.artifactBg, color: nx.artifact },
    'Backup': { bg: nx.eventBg, color: nx.event },
    'Unlikely': { bg: Tna.color.bg.secondary, color: Tna.color.text.secondary },
  }[s] || { bg: Tna.color.bg.secondary, color: Tna.color.text.secondary });

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={nx.stat}><span style={nx.statLabel}>Hypotheses tracked</span><span style={nx.statValue}>{data.hypotheses.length}</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Primary</span><span style={{ ...nx.statValue, color: nx.artifact }}>{data.hypotheses.filter(h => h.strength.startsWith('Primary')).length}</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Backup</span><span style={{ ...nx.statValue, color: nx.event }}>{data.hypotheses.filter(h => h.strength === 'Backup').length}</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Avg support Δ</span><span style={{ ...nx.statValue, color: nx.fuchsia }}>+{Math.round(data.hypotheses.reduce((s, h) => s + (h.support - h.rebuts), 0) / data.hypotheses.length)}</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '14px' }}>
        {data.hypotheses.map(h => {
          const sc = strengthColor(h.strength);
          const delta = h.support - h.rebuts;
          const total = h.support + h.rebuts;
          const supportPct = total ? (h.support / total) * 100 : 0;
          return (
            <div key={h.id} style={{ ...nx.card, marginBottom: 0 }}>
              <div style={{ padding: '14px 16px', borderBottom: `1px solid ${Tna.color.border.light}` }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
                    <span style={{ fontSize: '10px', fontFamily: Tna.font.mono, color: nx.fuchsia, fontWeight: 700 }}>{h.id}</span>
                    <span style={{ ...nx.tag, background: sc.bg, color: sc.color, fontSize: '11px', padding: '3px 10px' }}>{h.strength}</span>
                    <span style={{ fontSize: '13px', fontWeight: 700, color: Tna.color.text.primary }}>{h.name}</span>
                  </div>
                  <div style={{ display: 'flex', gap: '8px' }}>
                    <span style={{ ...nx.tag, background: nx.artifactBg, color: nx.artifact }}>↑ {h.support} supports</span>
                    <span style={{ ...nx.tag, background: nx.crimsonBg, color: nx.crimson }}>↓ {h.rebuts} rebuts</span>
                    <span style={{ ...nx.tag, background: delta > 0 ? nx.fuchsiaBg : Tna.color.bg.secondary, color: delta > 0 ? nx.fuchsia : Tna.color.text.secondary, fontWeight: 700 }}>Δ {delta > 0 ? '+' : ''}{delta}</span>
                  </div>
                </div>
                <div style={{ fontSize: '12px', color: Tna.color.text.secondary, lineHeight: 1.6, marginBottom: '10px' }}>{h.theory}</div>
                {/* Support vs rebut bar */}
                <div style={{ height: '8px', borderRadius: '4px', overflow: 'hidden', display: 'flex', marginBottom: '10px' }}>
                  <div style={{ width: `${supportPct}%`, background: nx.artifact, display: 'flex', alignItems: 'center', justifyContent: 'flex-end', color: '#fff', fontSize: '8px', fontWeight: 700, paddingRight: '4px' }}>{h.support}</div>
                  <div style={{ width: `${100 - supportPct}%`, background: nx.crimson, display: 'flex', alignItems: 'center', paddingLeft: '4px', color: '#fff', fontSize: '8px', fontWeight: 700 }}>{h.rebuts}</div>
                </div>
                {/* Favored by */}
                <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                  {h.favoredBy.map(f => <span key={f} style={{ ...nx.tag, background: Tna.color.bg.secondary, color: Tna.color.text.secondary }}>{f}</span>)}
                </div>
                <div style={{ marginTop: '8px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <span style={{ fontSize: '10px', color: Tna.color.text.tertiary }}>{h.matter} · owner: {h.owner}</span>
                  <button style={nx.btnGhost}>Compare →</button>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function NexusMatrix({ data }) {
  const nx = window.__nx;
  const m = data.matrix;
  const ms = data.matrixStats;

  const max = Math.max(...m.matters.flatMap(ma => m.types.map(t => m.counts[ma]?.[t] || 0)));
  const totalByMatter = {};
  m.matters.forEach(ma => { totalByMatter[ma] = m.types.reduce((s, t) => s + (m.counts[ma]?.[t] || 0), 0); });
  const totalByType = {};
  m.types.forEach(t => { totalByType[t] = m.matters.reduce((s, ma) => s + (m.counts[ma]?.[t] || 0), 0); });
  const grandTotal = Object.values(totalByMatter).reduce((s, v) => s + v, 0);

  const totalCells = m.matters.length * m.types.length;
  const filledCells = m.matters.reduce((s, ma) => s + m.types.filter(t => (m.counts[ma]?.[t] || 0) > 0).length, 0);
  const coveragePct = ((filledCells / totalCells) * 100).toFixed(0);
  const emptyCells = totalCells - filledCells;
  const avgCellValue = (grandTotal / filledCells).toFixed(1);

  const sevColor = (s) => s === 'high' ? { bg: 'rgba(194,48,48,0.08)', color: nx.crimson }
    : s === 'medium' ? { bg: 'rgba(245,158,11,0.08)', color: nx.event }
    : { bg: Tna.color.bg.secondary, color: Tna.color.text.secondary };

  const tt = ms.typeByType;
  const ttMax = Math.max(...tt.types.flatMap(a => tt.types.map(b => tt.counts[a]?.[b] || 0)));
  const ttTotal = Object.values(tt.counts).reduce((s, row) => s + Object.values(row).reduce((a, b) => a + b, 0), 0);

  const ranked = [...ms.density].sort((a, b) => b.ratio - a.ratio);
  const maxRatio = Math.max(...ms.density.map(d => d.ratio));

  return (
    <div>
      {/* AI banner */}
      <div style={nx.card}>
        <div style={{ padding: '12px 16px', background: nx.fuchsiaBg, fontSize: '12px', color: Tna.color.text.secondary, lineHeight: 1.6, borderLeft: `3px solid ${nx.fuchsia}` }}>
          <div style={{ fontSize: '10px', fontWeight: 700, color: nx.fuchsia, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>◆ Matter × Entity Matrix — AI Analysis</div>
          Cross-matter canonical-entity coverage: <b>{coveragePct}%</b> of matter-type cells are populated. <b>Redstone v. Meridian</b> has the deepest coverage ({totalByMatter['Redstone v. Meridian']} entities). <b>{ms.gaps.length} gaps</b> identified with actionable recommendations below. Strongest co-occurrence axis: <b>person ↔ document</b> ({tt.counts.person.document.toLocaleString()} cross-links).
        </div>
      </div>

      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={nx.stat}>
          <span style={nx.statLabel}>Matters × Types</span>
          <span style={nx.statValue}>{totalCells}</span>
          <span style={{ ...nx.statDelta, color: Tna.color.text.tertiary }}>{m.matters.length} matters × {m.types.length} types</span>
        </div>
        <div style={nx.stat}>
          <span style={nx.statLabel}>Matrix coverage</span>
          <span style={{ ...nx.statValue, color: parseFloat(coveragePct) >= 75 ? nx.artifact : parseFloat(coveragePct) >= 50 ? nx.fuchsia : nx.event }}>{coveragePct}%</span>
          <span style={{ ...nx.statDelta, color: Tna.color.text.tertiary }}>{filledCells} of {totalCells} cells</span>
        </div>
        <div style={nx.stat}>
          <span style={nx.statLabel}>Empty cells</span>
          <span style={{ ...nx.statValue, color: nx.event }}>{emptyCells}</span>
          <span style={{ ...nx.statDelta, color: Tna.color.text.tertiary }}>actionable gaps</span>
        </div>
        <div style={nx.stat}>
          <span style={nx.statLabel}>Total cross-links</span>
          <span style={{ ...nx.statValue, color: nx.fuchsia }}>{ttTotal.toLocaleString()}</span>
          <span style={{ ...nx.statDelta, color: Tna.color.text.tertiary }}>type × type edges</span>
        </div>
        <div style={nx.stat}>
          <span style={nx.statLabel}>Avg cell density</span>
          <span style={nx.statValue}>{avgCellValue}</span>
          <span style={{ ...nx.statDelta, color: Tna.color.text.tertiary }}>entities / populated cell</span>
        </div>
        <div style={nx.stat}>
          <span style={nx.statLabel}>Cross-matter bridges</span>
          <span style={{ ...nx.statValue, color: nx.violet }}>{ms.crossMatter.length}</span>
          <span style={{ ...nx.statDelta, color: Tna.color.text.tertiary }}>entities in ≥2 matters</span>
        </div>
      </div>

      {/* Depth ranking + Cross-matter bridges */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: '14px', marginBottom: '16px' }}>
        <div style={nx.card}>
          <div style={nx.cardH}><span>Matter depth ranking — links per entity</span><span style={{ fontSize: '10px', color: Tna.color.text.tertiary }}>higher density = stronger cross-linkage</span></div>
          <div>
            {ranked.map((d, i) => {
              const ratioColor = d.ratio >= 1.3 ? nx.artifact : d.ratio >= 1.0 ? nx.fuchsia : nx.event;
              return (
                <div key={d.matter} style={{ padding: '8px 16px', borderBottom: i < ranked.length - 1 ? `1px solid ${Tna.color.border.light}` : 'none', display: 'flex', alignItems: 'center', gap: '10px' }}>
                  <span style={{ fontFamily: Tna.font.mono, fontSize: '11px', color: Tna.color.text.tertiary, minWidth: '20px', fontWeight: 700 }}>#{d.rank}</span>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: Tna.color.text.primary, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{d.matter}</div>
                    <div style={{ fontSize: '10px', color: Tna.color.text.tertiary, fontFamily: Tna.font.mono }}>{d.entities.toLocaleString()} entities · {d.links.toLocaleString()} links</div>
                  </div>
                  <div style={{ width: '160px', height: '6px', background: Tna.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                    <div style={{ width: `${(d.ratio / maxRatio) * 100}%`, height: '100%', background: ratioColor }} />
                  </div>
                  <span style={{ fontFamily: Tna.font.mono, fontSize: '14px', color: ratioColor, fontWeight: 700, minWidth: '48px', textAlign: 'right' }}>{d.ratio.toFixed(2)}×</span>
                </div>
              );
            })}
          </div>
        </div>

        <div style={nx.card}>
          <div style={nx.cardH}>Cross-matter bridges</div>
          <div>
            {ms.crossMatter.map((b, i) => (
              <div key={i} style={{ padding: '10px 16px', borderBottom: i < ms.crossMatter.length - 1 ? `1px solid ${Tna.color.border.light}` : 'none' }}>
                <div style={{ fontSize: '12px', fontWeight: 600, color: Tna.color.text.primary, marginBottom: '4px' }}>{b.entity}</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '3px', marginBottom: '4px' }}>
                  {b.matters.map(mat => <span key={mat} style={{ ...nx.tag, background: nx.violetBg, color: nx.violet }}>{mat.length > 22 ? mat.slice(0, 20) + '…' : mat}</span>)}
                </div>
                <div style={{ fontSize: '10px', color: Tna.color.text.tertiary, fontStyle: 'italic' }}>{b.note}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Main density matrix — enhanced with row sparklines */}
      <div style={nx.card}>
        <div style={nx.cardH}><span>Matter × Type density heatmap</span><span style={{ fontSize: '10px', color: Tna.color.text.tertiary }}>darker = higher entity count · profile sparkline shows per-matter type distribution</span></div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={{ ...nx.th, textAlign: 'left' }}>Matter</th>
              {m.types.map(t => {
                const ts = nx.typeStyle(t);
                return <th key={t} style={{ ...nx.th, textAlign: 'center', minWidth: '100px' }}><span style={{ color: ts.color }}>{ts.icon}</span> {ts.label}</th>;
              })}
              <th style={{ ...nx.th, textAlign: 'right' }}>Total</th>
              <th style={{ ...nx.th, textAlign: 'right' }}>Profile</th>
            </tr>
          </thead>
          <tbody>
            {m.matters.map(mat => {
              const rowValues = m.types.map(t => m.counts[mat]?.[t] || 0);
              const rowMax = Math.max(...rowValues);
              return (
                <tr key={mat}>
                  <td style={{ ...nx.td, fontWeight: 600, color: Tna.color.text.primary, maxWidth: '220px' }}>{mat}</td>
                  {m.types.map((t, ti) => {
                    const v = rowValues[ti];
                    const intensity = max ? v / max : 0;
                    const ts = nx.typeStyle(t);
                    return (
                      <td key={t} style={{ ...nx.td, textAlign: 'center', padding: '6px 8px' }}>
                        <div style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: '52px', height: '28px', borderRadius: '4px', background: v === 0 ? Tna.color.bg.secondary : `${ts.color}${Math.round(intensity * 80 + 15).toString(16).padStart(2, '0')}`, color: v === 0 ? Tna.color.text.tertiary : intensity > 0.5 ? '#fff' : ts.color, fontFamily: Tna.font.mono, fontWeight: 700, fontSize: '12px', cursor: v === 0 ? 'default' : 'pointer' }}>
                          {v === 0 ? '—' : v}
                        </div>
                      </td>
                    );
                  })}
                  <td style={{ ...nx.td, textAlign: 'right', fontFamily: Tna.font.mono, color: nx.fuchsia, fontWeight: 700 }}>{totalByMatter[mat]}</td>
                  <td style={{ ...nx.td, textAlign: 'right', padding: '6px 12px' }}>
                    <svg width="82" height="22" viewBox="0 0 82 22" style={{ overflow: 'visible' }}>
                      {rowValues.map((v, i) => {
                        const barH = rowMax ? (v / rowMax) * 20 : 0;
                        const ts = nx.typeStyle(m.types[i]);
                        return <rect key={i} x={i * 14} y={22 - barH} width="10" height={barH} fill={v === 0 ? Tna.color.border.light : ts.color} rx="1" />;
                      })}
                    </svg>
                  </td>
                </tr>
              );
            })}
            <tr>
              <td style={{ ...nx.th, textAlign: 'left' }}>Column total</td>
              {m.types.map(t => {
                const ts = nx.typeStyle(t);
                return <td key={t} style={{ ...nx.th, textAlign: 'center', color: ts.color, fontFamily: Tna.font.mono, fontWeight: 700 }}>{totalByType[t]}</td>;
              })}
              <td style={{ ...nx.th, textAlign: 'right', color: nx.fuchsia, fontFamily: Tna.font.mono, fontWeight: 700 }}>{grandTotal}</td>
              <td style={{ ...nx.th }}></td>
            </tr>
          </tbody>
        </table>
      </div>

      {/* Type × Type + Gaps */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: '14px' }}>
        <div style={nx.card}>
          <div style={nx.cardH}><span>Type × Type link co-occurrence</span><span style={{ fontSize: '10px', color: Tna.color.text.tertiary }}>which types connect to which · all matters</span></div>
          <div style={{ padding: '10px 8px' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr>
                  <th style={{ fontSize: '9px', fontWeight: 700, color: Tna.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', padding: '4px' }}></th>
                  {tt.types.map(t => {
                    const ts = nx.typeStyle(t);
                    return <th key={t} style={{ fontSize: '9px', fontWeight: 700, color: ts.color, textTransform: 'uppercase', letterSpacing: '0.06em', padding: '4px', textAlign: 'center' }}>{ts.icon} {ts.label}</th>;
                  })}
                </tr>
              </thead>
              <tbody>
                {tt.types.map(a => {
                  const tsA = nx.typeStyle(a);
                  return (
                    <tr key={a}>
                      <th style={{ fontSize: '9px', fontWeight: 700, color: tsA.color, textTransform: 'uppercase', letterSpacing: '0.06em', padding: '4px 8px', textAlign: 'right' }}>{tsA.icon} {tsA.label}</th>
                      {tt.types.map(b => {
                        const v = tt.counts[a]?.[b] || 0;
                        const intensity = v / ttMax;
                        const blend = a === b ? Tna.color.bg.secondary : `${nx.fuchsia}${Math.round(intensity * 80 + 15).toString(16).padStart(2, '0')}`;
                        return (
                          <td key={b} style={{ padding: '3px', textAlign: 'center' }}>
                            <div style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', width: '100%', height: '34px', borderRadius: '4px', background: blend, color: a === b ? Tna.color.text.tertiary : intensity > 0.5 ? '#fff' : nx.fuchsia, fontFamily: Tna.font.mono, fontWeight: 700, fontSize: '11px' }}>
                              {v === 0 ? '—' : v >= 1000 ? `${(v / 1000).toFixed(1)}K` : v}
                            </div>
                          </td>
                        );
                      })}
                    </tr>
                  );
                })}
              </tbody>
            </table>
            <div style={{ padding: '10px 4px 0', fontSize: '10px', color: Tna.color.text.tertiary, display: 'flex', alignItems: 'center', gap: '8px' }}>
              <span>Low</span>
              <div style={{ flex: 1, height: '6px', background: `linear-gradient(90deg, ${nx.fuchsia}20 0%, ${nx.fuchsia} 100%)`, borderRadius: '3px' }} />
              <span>High</span>
              <span style={{ flex: 1, textAlign: 'right', fontFamily: Tna.font.mono }}>max: {ttMax.toLocaleString()}</span>
            </div>
          </div>
        </div>

        <div style={nx.card}>
          <div style={{ ...nx.cardH, color: nx.event }}>◆ Gap analysis — AI recommendations</div>
          <div>
            {ms.gaps.map((g, i) => {
              const sc = sevColor(g.severity);
              const ts = nx.typeStyle(g.type);
              return (
                <div key={i} style={{ padding: '10px 16px', borderBottom: i < ms.gaps.length - 1 ? `1px solid ${Tna.color.border.light}` : 'none' }}>
                  <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '10px', marginBottom: '4px' }}>
                    <div style={{ flex: 1 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '6px', marginBottom: '3px' }}>
                        <span style={{ fontSize: '11px', fontWeight: 700, color: Tna.color.text.primary }}>{g.matter}</span>
                        <span style={{ color: ts.color, fontSize: '11px' }}>{ts.icon}</span>
                        <span style={{ fontSize: '10px', color: ts.color, textTransform: 'capitalize' }}>{g.type}</span>
                      </div>
                      <div style={{ fontSize: '11px', color: Tna.color.text.secondary, lineHeight: 1.5 }}>{g.recommendation}</div>
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '4px', alignItems: 'flex-end', flexShrink: 0 }}>
                      <span style={{ ...nx.tag, background: sc.bg, color: sc.color }}>{g.severity}</span>
                      <span style={{ fontSize: '10px', fontFamily: Tna.font.mono, color: nx.fuchsia, fontWeight: 700 }}>{(g.confidence * 100).toFixed(0)}%</span>
                    </div>
                  </div>
                  <button style={{ ...nx.btnGhost, padding: '2px 0', fontSize: '10px' }}>Resolve gap →</button>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

function NexusActivity({ data }) {
  const nx = window.__nx;
  const sev = (s) => s === 'error' ? { bg: nx.crimsonBg, color: nx.crimson }
    : s === 'warn' ? { bg: nx.eventBg, color: nx.event }
    : { bg: nx.fuchsiaBg, color: nx.fuchsia };

  return (
    <div style={nx.card}>
      <div style={nx.cardH}>
        <span>Activity log — {data.activity.length} events</span>
        <button style={nx.btnSecondary}>Export CSV</button>
      </div>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={nx.th}>Time</th>
            <th style={nx.th}>Actor</th>
            <th style={nx.th}>Action</th>
            <th style={nx.th}>Target</th>
            <th style={nx.th}>Severity</th>
          </tr>
        </thead>
        <tbody>
          {data.activity.map(ev => {
            const ss = sev(ev.severity);
            return (
              <tr key={ev.id}>
                <td style={{ ...nx.td, fontFamily: Tna.font.mono, color: Tna.color.text.tertiary, fontSize: '11px' }}>{ev.time}</td>
                <td style={{ ...nx.td, color: Tna.color.text.primary, fontWeight: 500 }}>
                  <span style={{ display: 'inline-block', width: '6px', height: '6px', borderRadius: '50%', background: ss.color, marginRight: '8px' }} />
                  {ev.actor}
                </td>
                <td style={{ ...nx.td, color: Tna.color.text.secondary }}>{ev.action}</td>
                <td style={{ ...nx.td, color: Tna.color.text.primary, fontWeight: 500, maxWidth: '440px' }}>{ev.target}</td>
                <td style={nx.td}><span style={{ ...nx.tag, background: ss.bg, color: ss.color }}>{ev.severity}</span></td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

window.NexusHypotheses = NexusHypotheses;
window.NexusMatrix = NexusMatrix;
window.NexusActivity = NexusActivity;
