// PERSONA — Full entity detail page (mirrors CaseDetail pattern)
const { useState: usePnEpState } = React;
const Tpnep = window.ArbiterTokens;

function PersonaEntityPage({ person: p, data, onBack }) {
  const pn = window.__pn;
  const [activeTab, setActiveTab] = usePnEpState('overview');

  if (!p) return null;
  const tc = pn.typeColor(p.type);
  const rc = pn.riskColor(p.risk);
  const docs = data.documents.filter(d => d.personId === p.id);
  const assocs = data.associations.filter(a => a.source === p.id || a.target === p.id);

  const tabs = [
    { id: 'overview',      label: 'Overview' },
    { id: 'psychometrics', label: 'Psychometrics' },
    { id: 'network',       label: 'Network' },
    { id: 'documents',     label: `Documents (${docs.length})` },
    { id: 'strategy',      label: 'Strategy' },
    { id: 'prep',          label: 'Prep Checklist' },
    { id: 'audit',         label: 'Audit Trail' },
  ];

  // ── Shared styles (mirrors cs from CaseDetail) ──────────────────────────
  const ep = {
    container: { flex: 1, overflow: 'auto', background: Tpnep.color.bg.primary },
    hero: { padding: '20px 24px 16px', borderBottom: `1px solid ${Tpnep.color.border.light}`, background: Tpnep.color.bg.card },
    tabs: { display: 'flex', borderBottom: `1px solid ${Tpnep.color.border.light}`, background: Tpnep.color.bg.card, padding: '0 24px' },
    tab: { padding: '10px 16px', fontSize: '12px', fontWeight: 500, color: Tpnep.color.text.tertiary, cursor: 'pointer', border: 'none', background: 'none', borderBottom: '2px solid transparent', fontFamily: Tpnep.font.family, transition: 'all 0.15s', marginBottom: '-1px' },
    tabActive: { color: pn.indigo, borderBottom: `2px solid ${pn.indigo}`, fontWeight: 600 },
    body2col: { padding: '20px 24px', display: 'grid', gridTemplateColumns: '1fr 300px', gap: '20px' },
    body1col: { padding: '20px 24px' },
    sec: { background: Tpnep.color.bg.card, border: `1px solid ${Tpnep.color.border.light}`, borderRadius: Tpnep.radius.lg, overflow: 'hidden', marginBottom: '16px' },
    secH: { padding: '10px 16px', borderBottom: `1px solid ${Tpnep.color.border.light}`, fontSize: '12px', fontWeight: 600, color: Tpnep.color.text.primary, display: 'flex', alignItems: 'center', justifyContent: 'space-between' },
    tag: { display: 'inline-flex', alignItems: 'center', padding: '2px 8px', borderRadius: '10px', fontSize: '10px', fontWeight: 600 },
    th: { fontSize: '10px', fontWeight: 600, color: Tpnep.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.08em', padding: '8px 12px', textAlign: 'left', background: Tpnep.color.bg.secondary, borderBottom: `1px solid ${Tpnep.color.border.light}` },
    td: { fontSize: '12px', color: Tpnep.color.text.primary, padding: '10px 12px', borderBottom: `1px solid ${Tpnep.color.border.light}`, verticalAlign: 'middle' },
  };

  // ── Tab: Overview ───────────────────────────────────────────────────────
  const renderOverview = () => (
    <div style={ep.body2col}>
      <div>
        {/* Intel summary */}
        <div style={ep.sec}>
          <div style={{ padding: '12px 16px', background: `rgba(79,70,229,0.03)`, borderBottom: `1px solid ${Tpnep.color.border.light}` }}>
            <div style={{ fontSize: '10px', fontWeight: 700, color: pn.indigo, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '4px' }}>◆ Intelligence Summary</div>
            <div style={{ fontSize: '13px', color: Tpnep.color.text.primary, lineHeight: 1.65 }}>{p.notes}</div>
          </div>
        </div>

        {/* OCEAN snapshot if available */}
        {p.psych && (
          <div style={ep.sec}>
            <div style={ep.secH}>
              <span style={{ color: pn.indigo, fontWeight: 700 }}>O.C.E.A.N. Baseline</span>
              <span style={{ fontSize: '10px', color: Tpnep.color.text.tertiary }}>{p.psych.assessedBy} · {p.psych.assessedDate}</span>
            </div>
            <div style={{ padding: '14px 16px' }}>
              {pn.oceanTraits.map(t => (
                <div key={t.key} style={{ marginBottom: '10px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                    <span style={{ fontSize: '11px', fontWeight: 600, color: Tpnep.color.text.primary }}>{t.label}</span>
                    <span style={{ fontSize: '12px', fontFamily: Tpnep.font.mono, fontWeight: 800, color: t.color }}>{p.psych.ocean[t.key]}</span>
                  </div>
                  <div style={{ height: '6px', background: Tpnep.color.bg.secondary, borderRadius: '3px', overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: `${p.psych.ocean[t.key]}%`, background: `linear-gradient(90deg, ${t.color}55, ${t.color})`, borderRadius: '3px' }} />
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Associations */}
        {assocs.length > 0 && (
          <div style={ep.sec}>
            <div style={ep.secH}>Network Associations <span style={{ fontSize: '11px', fontFamily: Tpnep.font.mono, color: Tpnep.color.text.tertiary }}>{assocs.length}</span></div>
            <div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: '8px' }}>
              {assocs.map((a, i) => {
                const otherId = a.source === p.id ? a.target : a.source;
                const other = data.people.find(x => x.id === otherId);
                if (!other) return null;
                const otc = pn.typeColor(other.type);
                return (
                  <div key={i} style={{ padding: '10px 14px', background: Tpnep.color.bg.secondary, borderRadius: '6px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', border: `1px solid ${Tpnep.color.border.light}` }}>
                    <div>
                      <div style={{ fontSize: '12px', fontWeight: 700 }}>{other.name}</div>
                      <div style={{ fontSize: '11px', color: Tpnep.color.text.secondary, marginTop: '2px', lineHeight: 1.5 }}>{a.detail}</div>
                    </div>
                    <div style={{ display: 'flex', gap: '5px', flexShrink: 0, marginLeft: '12px' }}>
                      <span style={{ ...ep.tag, background: otc.bg, color: otc.color }}>{other.type}</span>
                      <span style={{ ...ep.tag, background: Tpnep.color.bg.card, border: `1px solid ${Tpnep.color.border.light}`, color: Tpnep.color.text.secondary }}>{a.type}</span>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        )}
      </div>

      {/* Right sidebar */}
      <div>
        {/* Key facts */}
        <div style={ep.sec}>
          <div style={ep.secH}>Profile Details</div>
          {[
            { l: 'ID', v: p.id, mono: true, color: pn.indigo },
            { l: 'Type', v: p.type },
            { l: 'Status', v: p.status },
            { l: 'Risk Level', v: p.risk },
            { l: 'DOB', v: p.dob || '—' },
            { l: 'Title', v: p.title || '—' },
            { l: 'Organization', v: p.organization || '—' },
            { l: 'Aliases', v: p.aliases.length > 0 ? p.aliases.join(', ') : '—' },
            { l: 'Last Updated', v: p.lastUpdated },
          ].map(r => (
            <div key={r.l} style={{ padding: '8px 16px', borderBottom: `1px solid ${Tpnep.color.border.light}`, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: '11px', color: Tpnep.color.text.tertiary, fontWeight: 500 }}>{r.l}</span>
              <span style={{ fontSize: '12px', fontWeight: r.color ? 700 : 500, color: r.color || Tpnep.color.text.primary, fontFamily: r.mono ? Tpnep.font.mono : Tpnep.font.family }}>{r.v}</span>
            </div>
          ))}
        </div>

        {/* Matters */}
        <div style={ep.sec}>
          <div style={ep.secH}>Associated Matters</div>
          <div style={{ padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: '5px' }}>
            {p.matters.map(m => (
              <div key={m} style={{ padding: '7px 11px', border: `1px solid ${Tpnep.color.border.light}`, borderRadius: '5px', fontSize: '12px', fontWeight: 600, color: pn.indigo }}> {m}</div>
            ))}
          </div>
        </div>

        {/* Roles & Tags */}
        <div style={ep.sec}>
          <div style={ep.secH}>Roles</div>
          <div style={{ padding: '10px 12px', display: 'flex', flexWrap: 'wrap', gap: '5px' }}>
            {p.roles.map(r => <span key={r} style={{ ...ep.tag, background: tc.bg, color: tc.color, padding: '4px 10px' }}>{r}</span>)}
          </div>
        </div>
        <div style={ep.sec}>
          <div style={ep.secH}>Tags</div>
          <div style={{ padding: '10px 12px', display: 'flex', flexWrap: 'wrap', gap: '5px' }}>
            {p.tags.map(t => <span key={t} style={{ ...ep.tag, background: Tpnep.color.bg.secondary, color: Tpnep.color.text.secondary, padding: '4px 10px' }}>#{t}</span>)}
          </div>
        </div>
      </div>
    </div>
  );

  // ── Tab: Psychometrics ─────────────────────────────────────────────────
  const renderPsych = () => {
    if (!p.psych) return (
      <div style={{ ...ep.body1col }}>
        <div style={ep.sec}>
          <div style={{ padding: '40px', textAlign: 'center', color: Tpnep.color.text.tertiary, fontSize: '13px' }}>
            Psychometric assessment has not been conducted for this subject.
          </div>
        </div>
      </div>
    );
    return (
      <div style={ep.body1col}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
          {/* OCEAN */}
          <div style={{ ...ep.sec, marginBottom: 0, borderLeft: `3px solid ${pn.indigo}` }}>
            <div style={{ ...ep.secH, background: pn.indigoBg }}><span style={{ color: pn.indigo, fontWeight: 700 }}>◆ O.C.E.A.N. Personality Baseline</span></div>
            <div style={{ padding: '16px 20px' }}>
              {pn.oceanTraits.map(t => (
                <div key={t.key} style={{ marginBottom: '14px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: '4px' }}>
                    <div>
                      <span style={{ fontSize: '12px', fontWeight: 700, color: Tpnep.color.text.primary }}>{t.label}</span>
                      <span style={{ fontSize: '10px', color: Tpnep.color.text.tertiary, marginLeft: '8px' }}>{t.desc}</span>
                    </div>
                    <span style={{ fontSize: '16px', fontFamily: Tpnep.font.mono, fontWeight: 800, color: t.color }}>{p.psych.ocean[t.key]}</span>
                  </div>
                  <div style={{ height: '8px', background: Tpnep.color.bg.secondary, borderRadius: '4px', overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: `${p.psych.ocean[t.key]}%`, background: `linear-gradient(90deg, ${t.color}55, ${t.color})`, borderRadius: '4px' }} />
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Vulnerabilities + Biases + Deception stacked */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
            <div style={{ ...ep.sec, marginBottom: 0 }}>
              <div style={ep.secH}><span>Psychological Vulnerabilities</span><span style={{ ...ep.tag, background: pn.crimsonBg, color: pn.crimson }}>{p.psych.vulnerabilities.length}</span></div>
              <div style={{ padding: '12px 16px', display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
                {p.psych.vulnerabilities.map(v => <div key={v} style={{ padding: '7px 12px', background: pn.crimsonBg, border: `1px solid rgba(159,18,57,0.15)`, borderRadius: '5px', fontSize: '11px', color: pn.crimson, fontWeight: 600 }}>⬡ {v}</div>)}
              </div>
            </div>
            <div style={{ ...ep.sec, marginBottom: 0 }}>
              <div style={ep.secH}><span>Cognitive Biases</span><span style={{ ...ep.tag, background: pn.amberBg, color: pn.amber }}>{p.psych.biases.length}</span></div>
              <div style={{ padding: '12px 16px', display: 'flex', flexWrap: 'wrap', gap: '6px' }}>
                {p.psych.biases.map(b => <div key={b} style={{ padding: '7px 12px', background: pn.amberBg, border: `1px solid rgba(180,83,9,0.15)`, borderRadius: '5px', fontSize: '11px', color: pn.amber, fontWeight: 600 }}>◎ {b}</div>)}
              </div>
            </div>
            <div style={{ ...ep.sec, marginBottom: 0 }}>
              <div style={ep.secH}><span>Deception Indicators</span>{p.psych.deception.length > 0 && <span style={{ ...ep.tag, background: pn.crimsonBg, color: pn.crimson }}>{p.psych.deception.length} flagged</span>}</div>
              <div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: '6px' }}>
                {p.psych.deception.length > 0 ? p.psych.deception.map((d, i) => (
                  <div key={i} style={{ padding: '8px 12px', background: pn.crimsonBg, border: `1px solid rgba(159,18,57,0.12)`, borderRadius: '5px', fontSize: '11px', color: Tpnep.color.text.primary, lineHeight: 1.5 }}>
                    <span style={{ color: pn.crimson, fontWeight: 700 }}><Icons.Flag size={11}/></span>{d}
                  </div>
                )) : <div style={{ fontSize: '12px', color: Tpnep.color.text.tertiary }}>No baseline indicators established.</div>}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  };

  // ── Tab: Strategy ──────────────────────────────────────────────────────
  const renderStrategy = () => (
    <div style={ep.body1col}>
      {p.psych ? (
        <div style={ep.sec}>
          <div style={{ ...ep.secH, color: pn.indigo }}><span>Examination & Interrogation Strategy</span></div>
          <div style={{ padding: '20px 24px', fontSize: '13px', color: Tpnep.color.text.primary, lineHeight: 1.75 }}>{p.psych.interrogation}</div>
        </div>
      ) : (
        <div style={ep.sec}><div style={{ padding: '40px', textAlign: 'center', color: Tpnep.color.text.tertiary }}>No strategic assessment available.</div></div>
      )}
    </div>
  );

  // ── Tab: Documents ────────────────────────────────────────────────────
  const renderDocuments = () => (
    <div style={ep.body1col}>
      <div style={ep.sec}>
        <div style={ep.secH}><span>Documents & Records</span><button style={{ padding: '3px 10px', borderRadius: '5px', border: `1px solid ${Tpnep.color.border.light}`, background: Tpnep.color.bg.card, fontSize: '11px', cursor: 'pointer', fontFamily: Tpnep.font.family }}>+ Link</button></div>
        {docs.length === 0 ? (
          <div style={{ padding: '32px', textAlign: 'center', color: Tpnep.color.text.tertiary, fontSize: '12px' }}>No documents linked to this profile.</div>
        ) : (
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={ep.th}>ID</th><th style={ep.th}>Title</th><th style={ep.th}>Type</th><th style={ep.th}>Date</th></tr></thead>
            <tbody>
              {docs.map(d => (
                <tr key={d.id} style={{ cursor: 'pointer' }}
                  onMouseOver={e => e.currentTarget.style.background = Tpnep.color.bg.secondary}
                  onMouseOut={e => e.currentTarget.style.background = 'transparent'}>
                  <td style={{ ...ep.td, fontFamily: Tpnep.font.mono, color: pn.indigo, fontWeight: 700, fontSize: '11px' }}>{d.id}</td>
                  <td style={{ ...ep.td, fontWeight: 600 }}>{d.title}</td>
                  <td style={ep.td}><span style={{ ...ep.tag, background: Tpnep.color.bg.secondary, color: Tpnep.color.text.secondary }}>{d.type}</span></td>
                  <td style={{ ...ep.td, fontFamily: Tpnep.font.mono, fontSize: '11px', color: Tpnep.color.text.secondary }}>{d.date}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );

  // ── Tab: Network ──────────────────────────────────────────────────────
  const renderNetwork = () => (
    <div style={ep.body1col}>
      {assocs.length === 0 ? (
        <div style={ep.sec}><div style={{ padding: '32px', textAlign: 'center', color: Tpnep.color.text.tertiary, fontSize: '12px' }}>No associations indexed for this subject.</div></div>
      ) : (
        <div style={ep.sec}>
          <div style={ep.secH}>Association Matrix <span style={{ fontSize: '11px', fontFamily: Tpnep.font.mono, color: Tpnep.color.text.tertiary }}>{assocs.length} edges</span></div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead><tr><th style={ep.th}>Subject</th><th style={ep.th}>Relationship</th><th style={ep.th}>Detail</th><th style={ep.th}>Type</th></tr></thead>
            <tbody>
              {assocs.map((a, i) => {
                const otherId = a.source === p.id ? a.target : a.source;
                const other = data.people.find(x => x.id === otherId);
                if (!other) return null;
                const otc = pn.typeColor(other.type);
                const dir = a.source === p.id ? '→' : '←';
                return (
                  <tr key={i} style={{ cursor: 'default' }}
                    onMouseOver={e => e.currentTarget.style.background = Tpnep.color.bg.secondary}
                    onMouseOut={e => e.currentTarget.style.background = 'transparent'}>
                    <td style={ep.td}><div style={{ fontWeight: 700 }}>{other.name}</div><span style={{ ...ep.tag, background: otc.bg, color: otc.color, fontSize: '9px', marginTop: '3px' }}>{other.type}</span></td>
                    <td style={{ ...ep.td, fontWeight: 700, color: pn.indigo }}>{dir} {a.type}</td>
                    <td style={{ ...ep.td, fontSize: '11px', color: Tpnep.color.text.secondary, maxWidth: '400px' }}>{a.detail}</td>
                    <td style={ep.td}><span style={{ ...ep.tag, background: Tpnep.color.bg.secondary, color: Tpnep.color.text.secondary }}>{a.type}</span></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );

  const renderPrep = () => (
    <div style={ep.body1col}>
      {window.PnPrepChecklist ? <window.PnPrepChecklist personId={p.id} /> : null}
    </div>
  );
  const renderAudit = () => (
    <div style={ep.body1col}>
      {window.PnAuditTimeline ? <window.PnAuditTimeline personId={p.id} limit={50} /> : null}
    </div>
  );

  const renderTab = () => {
    switch (activeTab) {
      case 'overview':      return renderOverview();
      case 'psychometrics': return renderPsych();
      case 'strategy':      return renderStrategy();
      case 'documents':     return renderDocuments();
      case 'network':       return renderNetwork();
      case 'prep':          return renderPrep();
      case 'audit':         return renderAudit();
      default:              return renderOverview();
    }
  };

  return (
    <div style={ep.container}>
      {/* ── Hero header (mirrors CaseDetail hero) ── */}
      <div style={{ ...ep.hero, borderTop: `3px solid ${tc.color}` }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: '14px' }}>
          <div style={{ display: 'flex', gap: '16px', alignItems: 'flex-start' }}>
            <div style={{ width: '52px', height: '52px', borderRadius: '10px', background: tc.bg, border: `2px solid ${tc.color}33`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '24px', flexShrink: 0 }}>
              {p.type === 'Defendant' ? '' : p.type === 'Witness' ? '' : p.type === 'Judge' ? '' : p.type === 'Agent' ? '' : ''}
            </div>
            <div>
              <div style={{ display: 'flex', gap: '8px', alignItems: 'center', marginBottom: '4px' }}>
                <h1 style={{ margin: 0, fontSize: '22px', fontWeight: 800, letterSpacing: '-0.02em', color: Tpnep.color.text.primary }}>{p.name}</h1>
                <span style={{ ...ep.tag, background: tc.bg, color: tc.color }}>{p.type}</span>
                <span style={{ ...ep.tag, background: rc.bg, color: rc.color }}>{p.risk} Risk</span>
                <span style={{ ...ep.tag, background: Tpnep.color.bg.secondary, color: Tpnep.color.text.secondary }}>{p.status}</span>
                {p.psych && <span style={{ ...ep.tag, background: pn.indigoBg, color: pn.indigo }}>◆ Psych Modeled</span>}
              </div>
              <div style={{ fontSize: '13px', color: Tpnep.color.text.secondary }}>
                {p.title && `${p.title} · `}
                <span style={{ fontWeight: 700 }}>{p.organization || 'Independent'}</span>
                {p.aliases.length > 0 && <span style={{ color: Tpnep.color.text.tertiary }}> · aka {p.aliases.join(', ')}</span>}
              </div>
              <div style={{ fontSize: '11px', color: Tpnep.color.text.tertiary, marginTop: '3px' }}>
                {p.roles.join(' · ')} · {p.matters.join(' · ')}
              </div>
            </div>
          </div>
          <div style={{ textAlign: 'right', flexShrink: 0, display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: '6px' }}>
            <div style={{ fontFamily: Tpnep.font.mono, fontSize: '14px', color: pn.indigo, fontWeight: 800 }}>{p.id}</div>
            <div style={{ fontSize: '10px', color: Tpnep.color.text.tertiary }}>Updated {p.lastUpdated}</div>
            {p.counsel && p.counsel.length > 0 && <div style={{ fontSize: '10px', color: Tpnep.color.text.tertiary }}>{p.counsel[0]}</div>}
            {window.PnRiskSparkline && (
              <div style={{ display: 'flex', alignItems: 'center', gap: '6px', padding: '4px 8px', borderRadius: '5px', background: Tpnep.color.bg.secondary, border: `1px solid ${Tpnep.color.border.light}` }}>
                <span style={{ fontSize: '9px', fontWeight: 700, color: Tpnep.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Risk</span>
                <window.PnRiskSparkline personId={p.id} w={80} h={18} color={rc.color} />
              </div>
            )}
            {window.PnDossierButton && <window.PnDossierButton personId={p.id} label="Export dossier" />}
          </div>
        </div>
      </div>

      {/* ── Tab bar ── */}
      <div style={ep.tabs}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => setActiveTab(t.id)}
            style={{ ...ep.tab, ...(activeTab === t.id ? ep.tabActive : {}) }}>
            {t.label}
          </button>
        ))}
      </div>

      {/* ── Tab body ── */}
      {renderTab()}
    </div>
  );
}

window.PersonaEntityPage = PersonaEntityPage;
