/* eslint-disable */
const { useState: cS, useMemo: cM } = React;
const Dc = window.PERSONA_DATA;

// Inject sample layered data for personas missing it
const layeredPersonas = Dc.personas.map(p => {
  if (p.soul) return p;
  // Synthesize plausible layers
  const seed = (p.id.charCodeAt(2)+p.id.charCodeAt(4)) % 5;
  return {
    ...p,
    soul: {
      coreDesire: ({
        p_leyla: "Yalan söyleyenleri yakalamak — ama önce kendini.",
        p_arda: "Karmaşayı azaltmak; zarif bir sistem bırakmak.",
        p_aysel: "Hâlâ işe yaradığını hissetmek.",
        p_kaan: "Görünmez kalmak ve çoğunu görmek.",
        p_irem: "İyileştiğini bilmeden iyileştirmek.",
        p_renee: "Sadeliğe nihayet izin vermek.",
        p_dmitri: "Birinin yenilmesini değil, anlamasını izlemek.",
      })[p.id] || "—",
      coreFear: ({
        p_leyla: "Sustuğu için suç ortağı olmak.",
        p_arda: "Anlamsızı düzeltmiş olmak.",
        p_aysel: "Telefonun bir gün hiç çalmaması.",
        p_kaan: "Yanlış kişiyi sevmek.",
        p_irem: "Empatinin bir gün biteceği.",
        p_renee: "Yemeğin tadının onsuz aynı olması.",
        p_dmitri: "Eşit bir oyunda bile kaybetmek.",
      })[p.id] || "—",
      coreConflict: "—", wound: "—", growthArc: "—"
    },
    self: {
      bigFive: ({
        p_leyla: { O:78, C:64, E:51, A:42, N:64 },
        p_arda:  { O:71, C:88, E:30, A:48, N:38 },
        p_aysel: { O:62, C:74, E:68, A:81, N:44 },
        p_kaan:  { O:55, C:50, E:60, A:62, N:48 },
        p_irem:  { O:72, C:78, E:48, A:78, N:42 },
        p_renee: { O:80, C:82, E:55, A:70, N:36 },
        p_dmitri:{ O:68, C:84, E:25, A:38, N:48 },
      })[p.id] || { O:60,C:60,E:50,A:60,N:50 },
      archetype: p.archetype.replace("The ",""),
      values: ["—","—","—"],
      attachment: ["secure","avoidant","anxious-secure","fearful-avoidant","secure-leaning"][seed],
      temperament: ["Sanguine","Choleric","Phlegmatic","Melancholic","Sanguine-Phlegmatic"][seed]
    }
  };
});
const layeredById = Object.fromEntries(layeredPersonas.map(p=>[p.id,p]));

const PageCompare = ({ go }) => {
  const [aId, setAId] = cS("p_mert");
  const [bId, setBId] = cS("p_leyla");
  const a = layeredById[aId], b = layeredById[bId];

  const PortPick = ({ id, set, side }) => (
    <div className="card card-pad" style={{padding:14}}>
      <div className="layer-eyebrow" style={{marginBottom:8}}>Persona {side}</div>
      <select className="select" value={id} onChange={e=>set(e.target.value)}>
        {layeredPersonas.map(p => <option key={p.id} value={p.id}>{p.name} — {p.archetype}</option>)}
      </select>
    </div>
  );

  const cell = (label, av, bv, kind="text") => {
    const same = av === bv;
    return (
      <>
        <div className="cmp-k">{label}</div>
        <div className={"cmp-v "+(kind==="serif"?"serif":"")}>{av}</div>
        <div className={"cmp-v "+(kind==="serif"?"serif":"")+(same?" cmp-same":" cmp-diff")}>{bv}</div>
      </>
    );
  };

  const numCell = (label, av, bv) => {
    const diff = bv - av;
    return (
      <>
        <div className="cmp-k">{label}</div>
        <div className="cmp-v mono">{av}</div>
        <div className="cmp-v mono">
          <span>{bv}</span>
          {diff !== 0 && <span style={{marginLeft:8, color: Math.abs(diff)>=20?"var(--ruby)":Math.abs(diff)>=10?"var(--gold)":"var(--ink-3)", fontSize:11}}>
            {diff>0?"+":""}{diff}
          </span>}
        </div>
      </>
    );
  };

  // Distance metric
  const bigFiveDist = cM(()=>{
    const ka = Object.keys(a.self.bigFive);
    const sumSq = ka.reduce((s,k)=>s+Math.pow((a.self.bigFive[k]-b.self.bigFive[k])/100,2),0);
    return Math.sqrt(sumSq).toFixed(2);
  },[a,b]);

  return (
    <div className="page" style={{maxWidth:1400}}>
      <div className="page-head">
        <div className="eyebrow" style={{marginBottom:8}}>Studio · Compare</div>
        <div className="row between" style={{alignItems:"flex-end", gap:20}}>
          <div>
            <h1 className="page-title">Two souls, one table. <span className="muted">Where do they overlap, where do they push?</span></h1>
            <div className="page-sub">Pick any two personas to read them against each other — Soul to Surface. Diffs surface in ember; convergences fade.</div>
          </div>
          <div className="row" style={{gap:8}}>
            <button className="btn btn-sm">Save as ensemble pair</button>
            <button className="btn primary btn-sm" onClick={()=>go && go("ensemble")}>Open in ensemble →</button>
          </div>
        </div>
      </div>

      <div className="grid grid-2" style={{gap:14, marginBottom:18}}>
        <PortPick id={aId} set={setAId} side="A"/>
        <PortPick id={bId} set={setBId} side="B"/>
      </div>

      {/* Hero strip */}
      <div className="cmp-hero">
        <div className="cmp-hero-side">
          <div className={"persona-portrait "+a.portrait} style={{width:80, height:100}}><span className="placeholder-ph" style={{fontSize:9}}>portrait</span></div>
          <div>
            <div className="layer-eyebrow">A</div>
            <div style={{fontFamily:"var(--serif)",fontSize:24,lineHeight:1.1}}>{a.name}</div>
            <div className="muted" style={{fontSize:12,marginTop:4,maxWidth:280}}>{a.tagline}</div>
          </div>
        </div>
        <div className="cmp-hero-mid">
          <div className="cmp-distance">
            <div className="layer-eyebrow" style={{marginBottom:6}}>distance</div>
            <div style={{fontFamily:"var(--serif)",fontSize:36,fontStyle:"italic"}}>{bigFiveDist}</div>
            <div className="muted mono" style={{fontSize:10.5,letterSpacing:".06em"}}>BIG-FIVE EUCLIDEAN</div>
          </div>
        </div>
        <div className="cmp-hero-side rev">
          <div style={{textAlign:"right"}}>
            <div className="layer-eyebrow">B</div>
            <div style={{fontFamily:"var(--serif)",fontSize:24,lineHeight:1.1}}>{b.name}</div>
            <div className="muted" style={{fontSize:12,marginTop:4,maxWidth:280,marginLeft:"auto"}}>{b.tagline}</div>
          </div>
          <div className={"persona-portrait "+b.portrait} style={{width:80, height:100}}><span className="placeholder-ph" style={{fontSize:9}}>portrait</span></div>
        </div>
      </div>

      {/* Layer comparisons */}
      <div className="layer layer-soul" style={{marginTop:18}}>
        <div className="layer-head"><span className="layer-eyebrow">Layer 01 · Soul</span><h2 className="layer-title">Ruh</h2></div>
        <div className="cmp-grid">
          <div className="cmp-h">field</div><div className="cmp-h">{a.name.split(" ")[0]}</div><div className="cmp-h">{b.name.split(" ")[0]}</div>
          {cell("Core desire", a.soul.coreDesire, b.soul.coreDesire, "serif")}
          {cell("Core fear", a.soul.coreFear, b.soul.coreFear, "serif")}
          {cell("Core conflict", a.soul.coreConflict, b.soul.coreConflict, "serif")}
        </div>
      </div>

      <div className="layer layer-self">
        <div className="layer-head"><span className="layer-eyebrow">Layer 02 · Self</span><h2 className="layer-title">Benlik</h2></div>
        <div className="cmp-grid">
          <div className="cmp-h">trait</div><div className="cmp-h">{a.name.split(" ")[0]}</div><div className="cmp-h">{b.name.split(" ")[0]}</div>
          {numCell("Openness (O)", a.self.bigFive.O, b.self.bigFive.O)}
          {numCell("Conscientiousness (C)", a.self.bigFive.C, b.self.bigFive.C)}
          {numCell("Extraversion (E)", a.self.bigFive.E, b.self.bigFive.E)}
          {numCell("Agreeableness (A)", a.self.bigFive.A, b.self.bigFive.A)}
          {numCell("Neuroticism (N)", a.self.bigFive.N, b.self.bigFive.N)}
          {cell("Attachment", a.self.attachment, b.self.attachment)}
          {cell("Temperament", a.self.temperament, b.self.temperament)}
        </div>
      </div>

      <div className="layer layer-surface">
        <div className="layer-head"><span className="layer-eyebrow">Layer 04 · Surface</span><h2 className="layer-title">Yüzey</h2></div>
        <div className="cmp-grid">
          <div className="cmp-h">field</div><div className="cmp-h">{a.name.split(" ")[0]}</div><div className="cmp-h">{b.name.split(" ")[0]}</div>
          {cell("Age", a.age, b.age)}
          {cell("City", a.city, b.city)}
          {cell("Occupation", a.occupation, b.occupation)}
          {cell("Language", a.lang, b.lang)}
          {cell("Archetype", a.archetype, b.archetype)}
        </div>
      </div>

      <div className="card card-pad" style={{marginTop:18}}>
        <div className="row between" style={{marginBottom:10}}>
          <h3 className="section-title">If they met…</h3>
          <span className="tag gold"><span className="dot"/>generated</span>
        </div>
        <div style={{fontFamily:"var(--serif)", fontSize:18, fontStyle:"italic", lineHeight:1.6, color:"var(--ink-2)", maxWidth:780}}>
          "{a.name.split(" ")[0]} would notice {b.name.split(" ")[0]}'s silences before her sentences. {b.name.split(" ")[0]} would mistake his patience for indifference. They'd both leave thinking the other had been unkind."
        </div>
        <div className="row" style={{gap:8, marginTop:14}}>
          <button className="btn btn-sm">Regenerate</button>
          <button className="btn primary btn-sm" onClick={()=>go && go("ensemble")}>Run as scenario →</button>
        </div>
      </div>
    </div>
  );
};

window.PageCompare = PageCompare;
