// PERSONA PLATFORM — Views Part 2: Psychometrics tab + Profile Detail
const { useState: usePnV2State } = React;
const Tpnv2 = window.ArbiterTokens;

// ── OCEAN Detail Chart ────────────────────────────────────────────────────
function OceanDetailChart({ ocean }) {
  const pn = window.__pn;
  return (
    <div>
      {pn.oceanTraits.map(t => (
        <div key={t.key} style={{ marginBottom: '12px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: '4px' }}>
            <div>
              <span style={{ fontSize: '12px', fontWeight: 700, color: Tpnv2.color.text.primary }}>{t.label}</span>
              <span style={{ fontSize: '10px', color: Tpnv2.color.text.tertiary, marginLeft: '8px' }}>{t.desc}</span>
            </div>
            <span style={{ fontSize: '14px', fontFamily: Tpnv2.font.mono, fontWeight: 800, color: t.color }}>{ocean[t.key]}</span>
          </div>
          <div style={{ height: '8px', background: Tpnv2.color.bg.secondary, borderRadius: '4px', overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${ocean[t.key]}%`, background: `linear-gradient(90deg, ${t.color}55, ${t.color})`, borderRadius: '4px' }} />
          </div>
        </div>
      ))}
    </div>
  );
}

// ── PSYCHOMETRICS TAB ─────────────────────────────────────────────────────
function PersonaPsychTab({ data, onSelectPerson }) {
  const pn = window.__pn;
  const profiled = data.people.filter(p => p.psych);

  return (
    <div>
      {/* Summary strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={pn.stat}><span style={pn.statLabel}>Profiles modeled</span><span style={{ ...pn.statValue, color: pn.indigo }}>{profiled.length}</span><span style={{ ...pn.statDelta, color: Tpnv2.color.text.tertiary }}>of {data.people.length} in registry</span></div>
        <div style={pn.stat}><span style={pn.statLabel}>Avg Neuroticism</span><span style={{ ...pn.statValue, color: pn.crimson }}>{Math.round(profiled.reduce((s, p) => s + p.psych.ocean.n, 0) / profiled.length)}</span><span style={{ ...pn.statDelta, color: Tpnv2.color.text.tertiary }}>stress reactivity index</span></div>
        <div style={pn.stat}><span style={pn.statLabel}>Avg Conscientiousness</span><span style={{ ...pn.statValue, color: pn.emerald }}>{Math.round(profiled.reduce((s, p) => s + p.psych.ocean.c, 0) / profiled.length)}</span><span style={{ ...pn.statDelta, color: Tpnv2.color.text.tertiary }}>self-discipline score</span></div>
        <div style={pn.stat}><span style={pn.statLabel}>Deception indicators</span><span style={{ ...pn.statValue, color: pn.amber }}>{profiled.reduce((s, p) => s + p.psych.deception.length, 0)}</span><span style={{ ...pn.statDelta, color: Tpnv2.color.text.tertiary }}>across all subjects</span></div>
      </div>

      {/* Grid of profiles */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
        {profiled.map(p => {
          const tc = pn.typeColor(p.type);
          const rc = pn.riskColor(p.risk);
          return (
            <div key={p.id} style={{ ...pn.card, marginBottom: 0, borderTop: `2px solid ${tc.color}` }}>
              {/* Card header */}
              <div style={{ ...pn.cardH, background: tc.bg, cursor: 'pointer' }} onClick={() => onSelectPerson(p.id)}>
                <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                  <span style={{ fontWeight: 700, color: Tpnv2.color.text.primary }}>{p.name}</span>
                  <span style={{ ...pn.tag, background: tc.bg, color: tc.color }}>{p.type}</span>
                  <span style={{ ...pn.tag, background: rc.bg, color: rc.color }}>{p.risk}</span>
                </div>
                <span style={{ fontSize: '11px', color: pn.indigo, fontWeight: 600 }}>Full dossier →</span>
              </div>

              <div style={{ padding: '14px 16px' }}>
                {/* OCEAN chart */}
                <OceanDetailChart ocean={p.psych.ocean} />

                {/* Vulnerabilities + Biases */}
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '10px', marginTop: '14px', paddingTop: '14px', borderTop: `1px solid ${Tpnv2.color.border.light}` }}>
                  <div>
                    <div style={{ fontSize: '10px', fontWeight: 700, color: pn.crimson, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Vulnerabilities</div>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
                      {p.psych.vulnerabilities.map(v => (
                        <span key={v} style={{ ...pn.tag, background: pn.crimsonBg, color: pn.crimson }}>{v}</span>
                      ))}
                    </div>
                  </div>
                  <div>
                    <div style={{ fontSize: '10px', fontWeight: 700, color: pn.amber, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Cognitive Biases</div>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px' }}>
                      {p.psych.biases.map(b => (
                        <span key={b} style={{ ...pn.tag, background: pn.amberBg, color: pn.amber }}>{b}</span>
                      ))}
                    </div>
                  </div>
                </div>

                {/* Assessed metadata */}
                <div style={{ marginTop: '10px', fontSize: '10px', color: Tpnv2.color.text.tertiary }}>
                  Assessed by {p.psych.assessedBy} · {p.psych.assessedDate}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ── PROFILE DETAIL VIEW ───────────────────────────────────────────────────
function PersonaDetailView({ personId, data, onBack }) {
  const pn = window.__pn;
  const p = data.people.find(x => x.id === personId);
  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);

  return (
    <div>
      <button onClick={onBack} style={{ ...pn.btnSecondary, marginBottom: '16px', display: 'inline-flex', alignItems: 'center', gap: '5px' }}>
        ← Back
      </button>

      {/* Dossier header */}
      <div style={{ ...pn.card, padding: 0, marginBottom: '16px', borderTop: `3px solid ${tc.color}` }}>
        <div style={{ padding: '20px 24px', background: `linear-gradient(135deg, ${tc.bg} 0%, transparent 70%)` }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div style={{ display: 'flex', gap: '18px', alignItems: 'flex-start' }}>
              <div style={{ width: '56px', height: '56px', borderRadius: '10px', background: Tpnv2.color.bg.secondary, border: `2px solid ${tc.color}33`, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: '26px', 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: '5px' }}>
                  <h2 style={{ margin: 0, fontSize: '22px', fontWeight: 800, letterSpacing: '-0.02em', color: Tpnv2.color.text.primary }}>{p.name}</h2>
                  <span style={{ ...pn.tag, background: tc.bg, color: tc.color }}>{p.type}</span>
                  <span style={{ ...pn.tag, background: rc.bg, color: rc.color }}>{p.risk} Risk</span>
                  <span style={{ ...pn.tag, background: Tpnv2.color.bg.secondary, color: Tpnv2.color.text.secondary }}>{p.status}</span>
                </div>
                <div style={{ fontSize: '13px', color: Tpnv2.color.text.secondary }}>
                  {p.title && `${p.title} · `}
                  <span style={{ fontWeight: 700, color: Tpnv2.color.navy400 }}>{p.organization || 'Independent'}</span>
                  {p.aliases.length > 0 && <span style={{ color: Tpnv2.color.text.tertiary }}> · aka {p.aliases.join(', ')}</span>}
                </div>
                <div style={{ fontSize: '11px', color: Tpnv2.color.text.tertiary, marginTop: '4px' }}>
                  {p.roles.join(' · ')} · DOB: {p.dob || 'Unknown'}
                </div>
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontFamily: Tpnv2.font.mono, fontSize: '13px', color: pn.indigo, fontWeight: 800 }}>{p.id}</div>
              <div style={{ fontSize: '10px', color: Tpnv2.color.text.tertiary, marginTop: '2px' }}>Updated {p.lastUpdated}</div>
              {p.counsel.length > 0 && <div style={{ fontSize: '10px', color: Tpnv2.color.text.tertiary, marginTop: '2px' }}>{p.counsel[0]}</div>}
            </div>
          </div>
        </div>
      </div>

      {/* Detail body: 2 columns */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: '16px' }}>

        {/* LEFT — intelligence */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>

          {/* Psych panel */}
          {p.psych ? (
            <div style={{ ...pn.card, marginBottom: 0, borderLeft: `3px solid ${pn.indigo}` }}>
              <div style={{ ...pn.cardH, background: pn.indigoBg }}>
                <span style={{ color: pn.indigo, fontWeight: 700 }}>◆ O.C.E.A.N. Psychometric Baseline</span>
                <span style={{ fontSize: '10px', color: Tpnv2.color.text.tertiary }}>Big Five · {p.psych.assessedBy} · {p.psych.assessedDate}</span>
              </div>
              <div style={{ padding: '16px 20px' }}>
                <OceanDetailChart ocean={p.psych.ocean} />
              </div>
            </div>
          ) : (
            <div style={{ ...pn.card, marginBottom: 0 }}>
              <div style={pn.cardH}>Psychometric Assessment</div>
              <div style={{ padding: '20px 16px', textAlign: 'center', color: Tpnv2.color.text.tertiary, fontSize: '12px' }}>
                Behavioral modeling has not yet been conducted for this subject.
              </div>
            </div>
          )}

          {/* Tactical grid: 2x2 */}
          {p.psych && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
              <div style={{ ...pn.card, marginBottom: 0 }}>
                <div style={pn.cardH}>
                  <span>Psychological Vulnerabilities</span>
                  <span style={{ ...pn.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 11px', 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={{ ...pn.card, marginBottom: 0 }}>
                <div style={pn.cardH}>
                  <span>Cognitive Biases</span>
                  <span style={{ ...pn.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 11px', 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={{ ...pn.card, marginBottom: 0 }}>
                <div style={pn.cardH}>Examination Strategy</div>
                <div style={{ padding: '12px 16px', fontSize: '12px', color: Tpnv2.color.text.primary, lineHeight: 1.65 }}>
                  {p.psych.interrogation}
                </div>
              </div>

              <div style={{ ...pn.card, marginBottom: 0 }}>
                <div style={pn.cardH}>
                  <span>Deception Indicators</span>
                  {p.psych.deception.length > 0 && <span style={{ ...pn.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 11px', background: pn.crimsonBg, border: `1px solid rgba(159,18,57,0.12)`, borderRadius: '5px', fontSize: '11px', color: Tpnv2.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: Tpnv2.color.text.tertiary }}>No baseline indicators established.</div>}
                </div>
              </div>
            </div>
          )}

          {/* Associations */}
          {assocs.length > 0 && (
            <div style={{ ...pn.card, marginBottom: 0 }}>
              <div style={pn.cardH}>Network Associations</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: Tpnv2.color.bg.secondary, borderRadius: '6px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', border: `1px solid ${Tpnv2.color.border.light}` }}>
                      <div>
                        <div style={{ fontSize: '12px', fontWeight: 700, color: Tpnv2.color.text.primary }}>{other.name}</div>
                        <div style={{ fontSize: '11px', color: Tpnv2.color.text.secondary, marginTop: '2px', lineHeight: 1.5 }}>{a.detail}</div>
                      </div>
                      <div style={{ display: 'flex', gap: '5px', flexShrink: 0, marginLeft: '12px' }}>
                        <span style={{ ...pn.tag, background: otc.bg, color: otc.color }}>{other.type}</span>
                        <span style={{ ...pn.tag, background: Tpnv2.color.bg.card, border: `1px solid ${Tpnv2.color.border.light}`, color: Tpnv2.color.text.secondary }}>{a.type}</span>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>

        {/* RIGHT — factual record */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: '14px' }}>
          <div style={{ ...pn.card, marginBottom: 0 }}>
            <div style={pn.cardH}>Intelligence Summary</div>
            <div style={{ padding: '14px 16px', fontSize: '12px', color: Tpnv2.color.text.primary, lineHeight: 1.7 }}>{p.notes}</div>
          </div>

          <div style={{ ...pn.card, marginBottom: 0 }}>
            <div style={pn.cardH}>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 ${Tpnv2.color.border.light}`, borderRadius: '5px', fontSize: '12px', fontWeight: 600, color: pn.indigo }}>
                   {m}
                </div>
              ))}
            </div>
          </div>

          <div style={{ ...pn.card, marginBottom: 0 }}>
            <div style={pn.cardH}>
              <span>Documents · Records ({docs.length})</span>
              <button style={{ ...pn.btnSecondary, padding: '3px 8px', fontSize: '10px' }}>+ Link</button>
            </div>
            <div style={{ padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: '5px' }}>
              {docs.length === 0
                ? <div style={{ fontSize: '12px', color: Tpnv2.color.text.tertiary }}>No documents linked.</div>
                : docs.map(d => (
                  <div key={d.id} style={{ padding: '8px 11px', border: `1px solid ${Tpnv2.color.border.light}`, borderRadius: '5px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                      <span style={{ fontSize: '12px', fontWeight: 600, color: Tpnv2.color.text.primary, lineHeight: 1.3 }}>{d.title}</span>
                      <span style={{ fontSize: '10px', color: Tpnv2.color.text.tertiary, fontFamily: Tpnv2.font.mono, flexShrink: 0, marginLeft: '8px' }}>{d.date}</span>
                    </div>
                    <span style={{ ...pn.tag, background: Tpnv2.color.bg.secondary, color: Tpnv2.color.text.secondary, fontSize: '9px', marginTop: '4px' }}>{d.type}</span>
                  </div>
                ))}
            </div>
          </div>

          <div style={{ ...pn.card, marginBottom: 0 }}>
            <div style={pn.cardH}>Tags & Flags</div>
            <div style={{ padding: '10px 12px', display: 'flex', flexWrap: 'wrap', gap: '5px' }}>
              {p.tags.map(t => <span key={t} style={{ ...pn.tag, background: Tpnv2.color.bg.secondary, color: Tpnv2.color.text.secondary, padding: '4px 10px' }}>#{t}</span>)}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.PersonaPsychTab = PersonaPsychTab;
window.PersonaDetailView = PersonaDetailView;
window.OceanDetailChart = OceanDetailChart;
