// NEXUS PLATFORM — Chains + Threads tabs
const { useState: useNxChState } = React;
const Tnch = window.ArbiterTokens;

function NexusChains({ data }) {
  const nx = window.__nx;
  const [activeChain, setActiveChain] = useNxChState(data.chains[0]?.id || null);
  const chain = data.chains.find(c => c.id === activeChain) || data.chains[0];

  const renderNode = (node, depth = 0, isLast = true) => {
    const ts = nx.typeStyle(node.type);
    const ls = node.rel ? nx.linkStyle(node.rel) : null;
    return (
      <div key={node.id}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '10px 16px', paddingLeft: `${16 + depth * 36}px`, borderBottom: `1px solid ${Tnch.color.border.light}` }}>
          {depth > 0 && <span style={{ color: Tnch.color.border.medium, fontSize: '14px' }}>└</span>}
          {ls && <span style={{ ...nx.tag, background: `${ls.color}15`, color: ls.color, fontSize: '9px', textTransform: 'uppercase' }}>{ls.label}</span>}
          <span style={{ color: ts.color, fontSize: '13px' }}>{ts.icon}</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: '12px', fontWeight: 600, color: Tnch.color.text.primary }}>{node.label}</div>
            <div style={{ fontSize: '10px', color: Tnch.color.text.tertiary, fontFamily: Tnch.font.mono }}>{node.id} · {ts.label}</div>
          </div>
          <span style={{ ...nx.tag, background: ts.bg, color: ts.color }}>{ts.label}</span>
        </div>
        {(node.children || []).map((c, i) => renderNode(c, depth + 1, i === node.children.length - 1))}
      </div>
    );
  };

  return (
    <div>
      {/* Chain selector */}
      <div style={{ display: 'flex', gap: '8px', marginBottom: '14px', flexWrap: 'wrap' }}>
        {data.chains.map(c => (
          <button key={c.id} onClick={() => setActiveChain(c.id)}
            style={{ padding: '6px 14px', borderRadius: '8px', border: `1px solid ${activeChain === c.id ? nx.fuchsia : Tnch.color.border.light}`,
              background: activeChain === c.id ? nx.fuchsiaBg : Tnch.color.bg.card,
              color: activeChain === c.id ? nx.fuchsia : Tnch.color.text.secondary,
              fontSize: '11px', fontWeight: 600, cursor: 'pointer', fontFamily: Tnch.font.family }}>{c.name}</button>
        ))}
        <div style={{ flex: 1 }} />
        <button style={nx.btnPrimary}>+ Build chain</button>
      </div>

      <div style={nx.card}>
        <div style={{ padding: '12px 16px', background: nx.fuchsiaBg, fontSize: '12px', color: Tnch.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' }}>◆ Causation Chain Analysis</div>
          {chain.id === 'CH-01' && <>The <b>LBO Closing → Apex formation → $14.2M → Singapore bank</b> chain is the cleanest causal narrative. Every node is grounded in a document or artifact, and the temporal sequencing is tight (18-month gap between LBO and Apex formation is itself evidence).</>}
          {chain.id === 'CH-02' && <>The <b>May 2021 Pricing Summit</b> gathers four carrier executives in a single physical event that supports the Sherman §1 horizontal-conspiracy theory. The meeting minutes corroborate attendance and topics.</>}
          {chain.id === 'CH-03' && <>The <b>Verge 2019 engineering notebook</b> predates '842 issuance by two years; the source-code repo corroborates the notebook dates. Together they form the foundation of the invalidity defense.</>}
        </div>
      </div>

      <div style={nx.card}>
        <div style={nx.cardH}><span>{chain.name}</span><span style={{ fontSize: '10px', color: Tnch.color.text.tertiary }}>{chain.matter}</span></div>
        {renderNode(chain.root)}
      </div>
    </div>
  );
}

function NexusThreads({ 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}>Saved threads</span><span style={nx.statValue}>{data.threads.length}</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Primary narratives</span><span style={{ ...nx.statValue, color: nx.fuchsia }}>{data.threads.filter(t => t.savedFor.includes('Trial') || t.savedFor.includes('MSJ')).length}</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Entities in threads</span><span style={nx.statValue}>{new Set(data.threads.flatMap(t => t.entityIds)).size}</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Avg docs per thread</span><span style={nx.statValue}>{Math.round(data.threads.reduce((s, t) => s + t.docCount, 0) / data.threads.length)}</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(420px, 1fr))', gap: '14px' }}>
        {data.threads.map(t => {
          const entCounts = {};
          t.entityIds.forEach(id => {
            const e = entityById[id];
            if (e) entCounts[e.type] = (entCounts[e.type] || 0) + 1;
          });
          return (
            <div key={t.id} style={{ ...nx.card, marginBottom: 0 }}>
              <div style={{ padding: '12px 14px', borderBottom: `1px solid ${Tnch.color.border.light}`, background: `linear-gradient(135deg, ${nx.fuchsiaBg} 0%, transparent 100%)` }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '6px' }}>
                  <span style={{ fontSize: '10px', fontFamily: Tnch.font.mono, color: nx.fuchsia, fontWeight: 700 }}>{t.id}</span>
                  <span style={{ fontSize: '10px', color: Tnch.color.text.tertiary }}>Updated {t.lastEdited}</span>
                </div>
                <div style={{ fontSize: '14px', fontWeight: 700, color: Tnch.color.text.primary, marginBottom: '3px' }}>{t.name}</div>
                <div style={{ fontSize: '11px', color: Tnch.color.text.tertiary }}>{t.matter} · owner: {t.owner}</div>
              </div>
              <div style={{ padding: '12px 14px' }}>
                <div style={{ fontSize: '11px', color: Tnch.color.text.secondary, lineHeight: 1.55, marginBottom: '10px' }}>{t.note}</div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '8px', marginBottom: '10px' }}>
                  <div>
                    <div style={{ fontSize: '9px', color: Tnch.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Entities</div>
                    <div style={{ fontSize: '16px', fontWeight: 700, color: nx.fuchsia, fontFamily: Tnch.font.mono }}>{t.entityIds.length}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '9px', color: Tnch.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Links</div>
                    <div style={{ fontSize: '16px', fontWeight: 700, color: nx.org, fontFamily: Tnch.font.mono }}>{t.linkIds.length}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: '9px', color: Tnch.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Docs</div>
                    <div style={{ fontSize: '16px', fontWeight: 700, color: nx.doc, fontFamily: Tnch.font.mono }}>{t.docCount}</div>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: '4px', marginBottom: '10px', flexWrap: 'wrap' }}>
                  {Object.entries(entCounts).map(([type, n]) => {
                    const ts = nx.typeStyle(type);
                    return <span key={type} style={{ ...nx.tag, background: ts.bg, color: ts.color }}>{ts.icon} {n}</span>;
                  })}
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: '10px', borderTop: `1px solid ${Tnch.color.border.light}` }}>
                  <span style={{ fontSize: '10px', color: Tnch.color.text.tertiary }}>For: {t.savedFor}</span>
                  <button style={nx.btnGhost}>Load in Canvas →</button>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.NexusChains = NexusChains;
window.NexusThreads = NexusThreads;
