// PERSONA PLATFORM — Views Part 1: Dashboard + Directory
const { useState: usePnV1State, useMemo: usePnV1Memo } = React;
const Tpnv1 = window.ArbiterTokens;

// ── Shared inner component ────────────────────────────────────────────────
function OceanMiniBar({ ocean }) {
  const pn = window.__pn;
  return (
    <div style={{ display: 'flex', gap: '3px', alignItems: 'flex-end', height: '20px' }}>
      {pn.oceanTraits.map(t => (
        <div key={t.key}
          title={`${t.label}: ${ocean[t.key]}`}
          style={{ width: '9px', height: `${Math.max(4, ocean[t.key] / 100 * 20)}px`, background: t.color, borderRadius: '2px', opacity: 0.85 }}
        />
      ))}
    </div>
  );
}
window.OceanMiniBar = OceanMiniBar;

// ── DASHBOARD ─────────────────────────────────────────────────────────────
function PersonaDashboardTab({ data, onSelectPerson }) {
  const pn = window.__pn;
  const k = data.kpis;
  const profiled = data.people.filter(p => p.psych);
  const highRisk = data.people.filter(p => p.risk === 'Critical' || p.risk === 'High');

  // Composition by type
  const byType = data.people.reduce((a, p) => { a[p.type] = (a[p.type] || 0) + 1; return a; }, {});

  const rowHover = (e, on) => e.currentTarget.style.background = on ? Tpnv1.color.bg.secondary : 'transparent';

  return (
    <div>
      {/* KPI strip — 6 wide */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={pn.stat}><span style={pn.statLabel}>Total profiles</span><span style={pn.statValue}>{k.total.toLocaleString()}</span><span style={{ ...pn.statDelta, color: Tpnv1.color.text.tertiary }}>↑ {k.newThisWeek} this week</span></div>
        <div style={pn.stat}><span style={pn.statLabel}>Psych assessed</span><span style={{ ...pn.statValue, color: pn.indigo }}>{k.psychAssessed}</span><span style={{ ...pn.statDelta, color: Tpnv1.color.text.tertiary }}>{Math.round(k.psychAssessed / k.total * 100)}% coverage</span></div>
        <div style={pn.stat}><span style={pn.statLabel}>Defendants</span><span style={{ ...pn.statValue, color: pn.crimson }}>{k.defendants}</span><span style={{ ...pn.statDelta, color: Tpnv1.color.text.tertiary }}>active matters</span></div>
        <div style={pn.stat}><span style={pn.statLabel}>Witnesses</span><span style={{ ...pn.statValue, color: pn.violet }}>{k.witnesses}</span><span style={{ ...pn.statDelta, color: pn.violet }}>{data.people.filter(p => p.psych && p.type === 'Witness').length} modeled</span></div>
        <div style={pn.stat}><span style={pn.statLabel}>High risk</span><span style={{ ...pn.statValue, color: pn.orange }}>{k.highRisk}</span><span style={{ ...pn.statDelta, color: Tpnv1.color.text.tertiary }}>flagged for review</span></div>
        <div style={pn.stat}><span style={pn.statLabel}>Judges / Officials</span><span style={{ ...pn.statValue, color: pn.emerald }}>{k.judges}</span><span style={{ ...pn.statDelta, color: Tpnv1.color.text.tertiary }}>+ {k.agents} agents indexed</span></div>
      </div>

      {/* Main grid: 2 left + right rail */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1.2fr 300px', gap: '14px' }}>

        {/* Threat matrix */}
        <div style={{ ...pn.card, marginBottom: 0, borderTop: `2px solid ${pn.crimson}` }}>
          <div style={{ ...pn.cardH, color: pn.crimson }}>⬡ Psychometric Threat Matrix — High-Value Targets</div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr>
              <th style={pn.th}>Subject</th>
              <th style={pn.th}>Type / Status</th>
              <th style={pn.th}>Vulnerability #1</th>
              <th style={pn.th}>Risk</th>
              <th style={pn.th}>O.C.E.A.N</th>
            </tr></thead>
            <tbody>
              {profiled.map(p => {
                const tc = pn.typeColor(p.type);
                const rc = pn.riskColor(p.risk);
                return (
                  <tr key={p.id} onClick={() => onSelectPerson(p.id)} style={{ cursor: 'pointer' }}
                    onMouseOver={e => rowHover(e, true)} onMouseOut={e => rowHover(e, false)}>
                    <td style={pn.td}>
                      <div style={{ fontWeight: 700 }}>{p.name}</div>
                      <div style={{ fontSize: '10px', color: pn.indigo, fontFamily: Tpnv1.font.mono }}>{p.id}</div>
                    </td>
                    <td style={pn.td}>
                      <span style={{ ...pn.tag, background: tc.bg, color: tc.color }}>{p.type}</span>
                      <div style={{ fontSize: '10px', color: Tpnv1.color.text.tertiary, marginTop: '3px' }}>{p.status}</div>
                    </td>
                    <td style={pn.td}><span style={{ ...pn.tag, background: pn.crimsonBg, color: pn.crimson }}>{p.psych.vulnerabilities[0]}</span></td>
                    <td style={pn.td}><span style={{ ...pn.tag, background: rc.bg, color: rc.color }}>{p.risk}</span></td>
                    <td style={pn.td}><OceanMiniBar ocean={p.psych.ocean} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {/* All profiles quick table */}
        <div style={{ ...pn.card, marginBottom: 0 }}>
          <div style={pn.cardH}>
            <span>Master Directory</span>
            <span style={{ fontSize: '10px', fontFamily: Tpnv1.font.mono, color: Tpnv1.color.text.tertiary }}>{data.people.length} shown</span>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr>
              <th style={pn.th}>Name</th>
              <th style={pn.th}>Type</th>
              <th style={pn.th}>Primary Matter</th>
            </tr></thead>
            <tbody>
              {data.people.map(p => {
                const tc = pn.typeColor(p.type);
                return (
                  <tr key={p.id} onClick={() => onSelectPerson(p.id)} style={{ cursor: 'pointer' }}
                    onMouseOver={e => rowHover(e, true)} onMouseOut={e => rowHover(e, false)}>
                    <td style={pn.td}>
                      <div style={{ fontWeight: 600 }}>{p.name}</div>
                      {p.aliases.length > 0 && <div style={{ fontSize: '10px', color: Tpnv1.color.text.tertiary }}>aka {p.aliases[0]}</div>}
                    </td>
                    <td style={pn.td}><span style={{ ...pn.tag, background: tc.bg, color: tc.color }}>{p.type}</span></td>
                    <td style={{ ...pn.td, fontSize: '11px', color: Tpnv1.color.text.secondary }}>{p.matters[0]}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {/* Right rail */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: '14px' }}>
          {/* Registry composition */}
          <div style={{ ...pn.card, marginBottom: 0 }}>
            <div style={pn.cardH}>Registry Composition</div>
            <div style={{ padding: '14px 16px' }}>
              {Object.entries(byType).map(([type, count]) => {
                const tc = pn.typeColor(type);
                const pct = Math.round(count / data.people.length * 100);
                return (
                  <div key={type} style={{ marginBottom: '10px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', marginBottom: '4px' }}>
                      <span style={{ color: tc.color, fontWeight: 700 }}>{type}</span>
                      <span style={{ fontFamily: Tpnv1.font.mono, color: Tpnv1.color.text.secondary }}>{count} <span style={{ color: Tpnv1.color.text.tertiary }}>({pct}%)</span></span>
                    </div>
                    <div style={{ height: '5px', background: Tpnv1.color.bg.secondary, borderRadius: '3px', overflow: 'hidden' }}>
                      <div style={{ width: `${pct}%`, height: '100%', background: tc.color, opacity: 0.75 }} />
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* High-risk list */}
          <div style={{ ...pn.card, marginBottom: 0, borderTop: `2px solid ${pn.orange}` }}>
            <div style={{ ...pn.cardH, color: pn.orange }}>flag Priority Watch List</div>
            <div style={{ padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: '6px' }}>
              {highRisk.map(p => {
                const rc = pn.riskColor(p.risk);
                const tc = pn.typeColor(p.type);
                return (
                  <div key={p.id} onClick={() => onSelectPerson(p.id)}
                    style={{ padding: '8px 10px', borderRadius: '6px', border: `1px solid ${Tpnv1.color.border.light}`, cursor: 'pointer' }}
                    onMouseOver={e => e.currentTarget.style.background = Tpnv1.color.bg.secondary}
                    onMouseOut={e => e.currentTarget.style.background = 'transparent'}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <span style={{ fontSize: '12px', fontWeight: 700 }}>{p.name}</span>
                      <span style={{ ...pn.tag, background: rc.bg, color: rc.color }}>{p.risk}</span>
                    </div>
                    <div style={{ display: 'flex', gap: '4px', marginTop: '4px' }}>
                      <span style={{ ...pn.tag, background: tc.bg, color: tc.color, fontSize: '9px' }}>{p.type}</span>
                      <span style={{ fontSize: '10px', color: Tpnv1.color.text.tertiary }}>{p.matters[0]}</span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── DIRECTORY ─────────────────────────────────────────────────────────────
function PersonaDirectoryTab({ data, onSelectPerson }) {
  const pn = window.__pn;
  const [search, setSearch] = usePnV1State('');
  const [typeFilter, setTypeFilter] = usePnV1State('All');

  const filtered = usePnV1Memo(() => {
    const q = search.toLowerCase();
    return data.people.filter(p =>
      (typeFilter === 'All' || p.type === typeFilter) &&
      (!q || p.name.toLowerCase().includes(q) || p.id.toLowerCase().includes(q) || (p.organization || '').toLowerCase().includes(q) || p.matters.some(m => m.toLowerCase().includes(q)))
    );
  }, [data.people, search, typeFilter]);

  const rowHover = (e, on) => e.currentTarget.style.background = on ? Tpnv1.color.bg.secondary : 'transparent';

  return (
    <div>
      <div style={{ ...pn.card, marginBottom: 0 }}>
        <div style={{ ...pn.cardH, padding: '12px 16px' }}>
          <div style={{ display: 'flex', gap: '10px', alignItems: 'center' }}>
            <input
              placeholder="Search name, ID, organization, matter…"
              value={search} onChange={e => setSearch(e.target.value)}
              style={{ padding: '6px 12px', width: '320px', borderRadius: '5px', border: `1px solid ${Tpnv1.color.border.light}`, fontSize: '12px', fontFamily: Tpnv1.font.family, background: Tpnv1.color.bg.secondary, color: Tpnv1.color.text.primary }}
            />
            <div style={{ display: 'flex', gap: '4px' }}>
              {['All', 'Defendant', 'Witness', 'Attorney', 'Judge', 'Agent', 'Expert'].map(t => (
                <button key={t} onClick={() => setTypeFilter(t)}
                  style={{ padding: '4px 10px', fontSize: '11px', borderRadius: '5px', border: `1px solid ${typeFilter === t ? pn.indigo : Tpnv1.color.border.light}`, background: typeFilter === t ? pn.indigoBg : Tpnv1.color.bg.card, color: typeFilter === t ? pn.indigo : Tpnv1.color.text.secondary, cursor: 'pointer', fontFamily: Tpnv1.font.family, fontWeight: typeFilter === t ? 700 : 400, transition: 'all 0.12s' }}>
                  {t}
                </button>
              ))}
            </div>
          </div>
          <span style={{ fontSize: '10px', fontFamily: Tpnv1.font.mono, color: Tpnv1.color.text.tertiary }}>{filtered.length} of {data.people.length}</span>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead><tr>
            <th style={pn.th}>ID</th>
            <th style={pn.th}>Name / Aliases</th>
            <th style={pn.th}>Classification</th>
            <th style={pn.th}>Organization / Title</th>
            <th style={pn.th}>Matters</th>
            <th style={pn.th}>Tags</th>
            <th style={pn.th}>Risk</th>
            <th style={pn.th}>Psych</th>
          </tr></thead>
          <tbody>
            {filtered.map(p => {
              const tc = pn.typeColor(p.type);
              const rc = pn.riskColor(p.risk);
              return (
                <tr key={p.id} onClick={() => onSelectPerson(p.id)} style={{ cursor: 'pointer' }}
                  onMouseOver={e => rowHover(e, true)} onMouseOut={e => rowHover(e, false)}>
                  <td style={{ ...pn.td, fontFamily: Tpnv1.font.mono, color: pn.indigo, fontWeight: 700, fontSize: '11px' }}>{p.id}</td>
                  <td style={pn.td}>
                    <div style={{ fontWeight: 700 }}>{p.name}</div>
                    {p.aliases.length > 0 && <div style={{ fontSize: '10px', color: Tpnv1.color.text.tertiary }}>aka {p.aliases.join(', ')}</div>}
                  </td>
                  <td style={pn.td}>
                    <span style={{ ...pn.tag, background: tc.bg, color: tc.color }}>{p.type}</span>
                    <div style={{ fontSize: '10px', color: Tpnv1.color.text.tertiary, marginTop: '3px' }}>{p.roles.join(', ')}</div>
                  </td>
                  <td style={pn.td}>
                    <div style={{ fontWeight: 500, fontSize: '12px' }}>{p.organization || '—'}</div>
                    <div style={{ fontSize: '10px', color: Tpnv1.color.text.tertiary }}>{p.title}</div>
                  </td>
                  <td style={{ ...pn.td, fontSize: '11px', color: Tpnv1.color.text.secondary, maxWidth: '200px' }}>
                    {p.matters.join(' · ')}
                  </td>
                  <td style={pn.td}>
                    <div style={{ display: 'flex', gap: '3px', flexWrap: 'wrap' }}>
                      {p.tags.slice(0, 2).map(t => (
                        <span key={t} style={{ ...pn.tag, background: Tpnv1.color.bg.secondary, color: Tpnv1.color.text.secondary }}>{t}</span>
                      ))}
                    </div>
                  </td>
                  <td style={pn.td}><span style={{ ...pn.tag, background: rc.bg, color: rc.color }}>{p.risk}</span></td>
                  <td style={{ ...pn.td, textAlign: 'center' }}>
                    {p.psych ? <span style={{ color: pn.indigo, fontSize: '14px' }}><Icons.Star size={11}/></span> : <span style={{ color: Tpnv1.color.text.tertiary, fontSize: '12px' }}>—</span>}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.PersonaDashboardTab = PersonaDashboardTab;
window.PersonaDirectoryTab = PersonaDirectoryTab;
