// NEXUS PLATFORM — Documents + Timeline tabs
const Tndoc = window.ArbiterTokens;

function NexusDocuments({ data }) {
  const nx = window.__nx;
  const documents = data.entities.filter(e => e.type === 'document');
  const artifactCount = data.entities.filter(e => e.type === 'artifact').length;

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={nx.stat}><span style={nx.statLabel}>Linked documents</span><span style={{ ...nx.statValue, color: nx.doc }}>{data.kpis.linkedDocuments.toLocaleString()}</span><span style={{ ...nx.statDelta, color: Tndoc.color.text.tertiary }}>of {(data.kpis.totalEntities * 1000).toLocaleString()} corpus</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Key documents</span><span style={nx.statValue}>{documents.length}</span><span style={{ ...nx.statDelta, color: Tndoc.color.text.tertiary }}>indexed + linked</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Artifacts</span><span style={{ ...nx.statValue, color: nx.artifact }}>{artifactCount}</span><span style={{ ...nx.statDelta, color: Tndoc.color.text.tertiary }}>wires, exhibits, amounts</span></div>
        <div style={nx.stat}><span style={nx.statLabel}>Orphan docs</span><span style={{ ...nx.statValue, color: nx.event }}>142</span><span style={{ ...nx.statDelta, color: Tndoc.color.text.tertiary }}>high-relevance, no links yet</span></div>
      </div>

      <div style={nx.card}>
        <div style={nx.cardH}><span>Linked documents — {documents.length}</span><button style={nx.btnSecondary}>Link orphan docs →</button></div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={nx.th}>ID</th>
              <th style={nx.th}>Document</th>
              <th style={nx.th}>Summary</th>
              <th style={nx.th}>Matter</th>
              <th style={nx.th}>Date</th>
              <th style={{ ...nx.th, textAlign: 'right' }}>Links</th>
              <th style={nx.th}>Linked entity types</th>
              <th style={nx.th}>Priority</th>
            </tr>
          </thead>
          <tbody>
            {documents.map(d => {
              const docLinks = data.links.filter(l => l.from === d.id || l.to === d.id);
              const linkedTypes = new Set();
              docLinks.forEach(l => {
                const otherId = l.from === d.id ? l.to : l.from;
                const other = data.entities.find(e => e.id === otherId);
                if (other) linkedTypes.add(other.type);
              });
              return (
                <tr key={d.id}>
                  <td style={{ ...nx.td, fontFamily: Tndoc.font.mono, color: nx.doc, fontWeight: 700, fontSize: '11px' }}>{d.id}</td>
                  <td style={{ ...nx.td, fontWeight: 600, color: Tndoc.color.text.primary, maxWidth: '240px' }}>{d.name}</td>
                  <td style={{ ...nx.td, color: Tndoc.color.text.secondary, fontSize: '11px', maxWidth: '320px' }}>{d.summary}</td>
                  <td style={{ ...nx.td, color: Tndoc.color.text.secondary, fontSize: '11px', maxWidth: '170px' }}>{d.matter}</td>
                  <td style={{ ...nx.td, fontFamily: Tndoc.font.mono, fontSize: '11px', color: Tndoc.color.text.tertiary }}>{d.dateRange || '—'}</td>
                  <td style={{ ...nx.td, textAlign: 'right', fontFamily: Tndoc.font.mono, color: nx.fuchsia, fontWeight: 700 }}>{d.linkCount}</td>
                  <td style={nx.td}>
                    <div style={{ display: 'flex', gap: '3px' }}>
                      {[...linkedTypes].map(t => {
                        const ts = nx.typeStyle(t);
                        return <span key={t} title={ts.label} style={{ ...nx.tag, background: ts.bg, color: ts.color, padding: '2px 6px' }}>{ts.icon}</span>;
                      })}
                    </div>
                  </td>
                  <td style={nx.td}>
                    <span style={{ ...nx.tag, background: d.priority === 'key' ? 'rgba(194,48,48,0.08)' : d.priority === 'high' ? 'rgba(245,158,11,0.08)' : Tndoc.color.bg.secondary, color: d.priority === 'key' ? nx.crimson : d.priority === 'high' ? nx.event : Tndoc.color.text.secondary }}>{d.priority}</span>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function NexusTimeline({ data }) {
  const nx = window.__nx;
  // Include events + documents with date ranges that are single-point-like
  const items = [...data.entities.filter(e => e.type === 'event'), ...data.entities.filter(e => e.type === 'document' && e.dateRange && /^\d{4}/.test(e.dateRange))]
    .map(e => ({ ...e, sortDate: (e.dateRange || '').split(/[-—]/)[0].trim() }))
    .filter(e => e.sortDate)
    .sort((a, b) => a.sortDate.localeCompare(b.sortDate));

  // Group by year
  const byYear = {};
  items.forEach(e => {
    const year = (e.dateRange || '').slice(0, 4);
    (byYear[year] = byYear[year] || []).push(e);
  });

  return (
    <div>
      <div style={nx.card}>
        <div style={{ padding: '12px 16px', background: nx.eventBg, fontSize: '12px', color: Tndoc.color.text.secondary, lineHeight: 1.6, borderLeft: `3px solid ${nx.event}` }}>
          <div style={{ fontSize: '10px', fontWeight: 700, color: nx.event, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>◆ Timeline Analysis</div>
          Across {items.length} dated entities, three temporal clusters emerge: (1) the <b>2017 Blackwell '842 issuance</b> and its 2019 prior-art counter, (2) the <b>2021-2022 Redstone LBO</b> leading to Apex formation (Dec 2023) and Osei departure (Feb 2024), and (3) the <b>2026 depositions + SEC activity</b> wave.
        </div>
      </div>

      <div style={nx.card}>
        <div style={nx.cardH}><span>Chronological entity timeline</span><span style={{ fontSize: '10px', color: Tndoc.color.text.tertiary }}>{items.length} dated entities across {Object.keys(byYear).length} years</span></div>
        {Object.entries(byYear).map(([year, es]) => (
          <div key={year}>
            <div style={{ padding: '6px 16px', background: Tndoc.color.bg.secondary, fontSize: '10px', fontWeight: 700, color: Tndoc.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em', display: 'flex', justifyContent: 'space-between' }}>
              <span>{year}</span>
              <span>{es.length} {es.length === 1 ? 'entity' : 'entities'}</span>
            </div>
            {es.map((e, i) => {
              const ts = nx.typeStyle(e.type);
              return (
                <div key={e.id} style={{ display: 'flex', alignItems: 'center', gap: '12px', padding: '8px 16px', borderBottom: `1px solid ${Tndoc.color.border.light}` }}>
                  <span style={{ fontFamily: Tndoc.font.mono, fontSize: '10px', color: Tndoc.color.text.tertiary, minWidth: '90px' }}>{e.dateRange}</span>
                  <div style={{ width: '3px', height: '32px', borderRadius: '2px', background: ts.color, flexShrink: 0 }} />
                  <span style={{ color: ts.color, fontSize: '13px' }}>{ts.icon}</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: '12px', fontWeight: 600, color: Tndoc.color.text.primary }}>{e.name}</div>
                    <div style={{ fontSize: '11px', color: Tndoc.color.text.secondary, marginTop: '2px', lineHeight: 1.5 }}>{e.summary}</div>
                  </div>
                  <span style={{ ...nx.tag, background: ts.bg, color: ts.color }}>{ts.label}</span>
                  <span style={{ fontSize: '10px', fontFamily: Tndoc.font.mono, color: nx.fuchsia, fontWeight: 700, minWidth: '40px', textAlign: 'right' }}>{e.linkCount}↔</span>
                </div>
              );
            })}
          </div>
        ))}
      </div>
    </div>
  );
}

window.NexusDocuments = NexusDocuments;
window.NexusTimeline = NexusTimeline;
