/* eslint-disable */
const D4 = window.PERSONA_DATA;

// ---------- Chat Runtime ----------
const PageChat = ({ persona, go }) => {
  const p = persona || D4.personas[0];
  const [devMode, setDevMode] = useState(true);
  const [input, setInput] = useState("");
  const [thinking, setThinking] = useState(false);
  const [msgs, setMsgs] = useState([
    { who:"user", text:"Selam Mert. Bugün dükkânda ne var?" },
    { who:"persona", text:"Pek bir şey. Bir adam Hesse soruyordu, gitti. Bu saatte camdan iki dilim ışık geçer, onu seyretmek bedava.", model:"sonnet-4-5", tokens:38, lat:0.9, cost:0.0024 },
    { who:"user", text:"Akademiyi özlüyor musun hâlâ?" },
    { who:"persona", text:"Özlemek doğru kelime değil. Bazen yatağa girerken, bir cümlenin sonunu unutmuş gibi hissediyorum. Sadece o.", model:"sonnet-4-5", tokens:42, lat:1.1, cost:0.0028 },
  ]);
  const send = () => {
    if (!input.trim()) return;
    const u = input;
    setMsgs(m => [...m, {who:"user",text:u}]);
    setInput("");
    setThinking(true);
    setTimeout(()=>{
      setMsgs(m => [...m, {who:"persona", text:"Belki. Dükkânın arkasında küçük bir avlu var, oraya çıkıyorum. Bir kediyi taklit ediyorum: yavaş, şüpheli, kibirli. İşe yarıyor.", model:"sonnet-4-5", tokens:36, lat:1.0, cost:0.0023}]);
      setThinking(false);
    }, 1600);
  };

  return (
    <div className="chat-wrap">
      <div className="chat-side">
        <div className="row between" style={{marginBottom:14}}>
          <h3 className="section-title" style={{fontSize:15}}>Active</h3>
          <button className="btn btn-sm">{I("plus",12)} New</button>
        </div>
        {[
          ["Mert Kavaklı","portrait-soul","Akademiyi özlüyor musun…","2m"],
          ["Aysel Hanım","portrait-mask","Çayın hâlâ ocakta…","1h"],
          ["Leyla Demir","portrait-plum","O kaynak güvenilmez…","yesterday"],
          ["Renée Mercier","portrait-strip","Le beurre, toujours…","2d"],
        ].map(([nm,cls,prev,when],i)=>(
          <div key={i} className="row" style={{gap:10,padding:"10px 8px",borderRadius:8,cursor:"pointer",background:i===0?"var(--bg-2)":"transparent",marginBottom:4}}>
            <div style={{width:36,height:36,borderRadius:6,overflow:"hidden",flexShrink:0}}>
              <PortraitPlaceholder cls={cls}/>
            </div>
            <div style={{flex:1,minWidth:0}}>
              <div style={{fontSize:13.5,fontFamily:"var(--serif)"}}>{nm}</div>
              <div className="muted" style={{fontSize:11.5,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>{prev}</div>
            </div>
            <div className="muted mono" style={{fontSize:10.5}}>{when}</div>
          </div>
        ))}
        <div className="divider"/>
        <div className="eyebrow" style={{marginBottom:8}}>Channels</div>
        <div className="col" style={{gap:6,fontSize:12.5}}>
          <div className="row" style={{gap:8}}>{I("globe",14)}<span>OpenAI-compatible API</span></div>
          <div className="row" style={{gap:8}}>{I("globe",14)}<span>MCP server</span></div>
          <div className="row" style={{gap:8}}>{I("chat",14)}<span>Web playground</span></div>
        </div>
      </div>

      <div className="chat-main">
        <div className="row between" style={{padding:"12px 40px",borderBottom:"1px solid var(--line)"}}>
          <div className="row" style={{gap:12}}>
            <div style={{width:32,height:40,borderRadius:6,overflow:"hidden"}}><PortraitPlaceholder cls={p.portrait}/></div>
            <div>
              <div style={{fontFamily:"var(--serif)",fontSize:16}}>{p.name}</div>
              <div className="muted" style={{fontSize:11.5}}>v3 · sonnet-4-5 · memory: long-term on</div>
            </div>
          </div>
          <div className="row" style={{gap:10}}>
            <div className="drift">{I("check",12)} drift 0.21 · in tolerance</div>
            <div className="row" style={{gap:6}}>
              <span className="muted" style={{fontSize:12}}>Dev mode</span>
              <div className={"toggle "+(devMode?"on":"")} onClick={()=>setDevMode(!devMode)}/>
            </div>
            <button className="icon-btn">{I("gear")}</button>
          </div>
        </div>

        <div className="chat-msgs">
          {msgs.map((m,i)=>(
            <div key={i} className={"chat-msg "+m.who}>
              <div className="who">{m.who==="user"?"you":p.name}</div>
              <div className="bub">{m.text}</div>
              {devMode && m.who==="persona" && (
                <div className="devbar">
                  <span>model: {m.model}</span>
                  <span>tokens: {m.tokens}</span>
                  <span>latency: {m.lat}s</span>
                  <span>cost: ${m.cost.toFixed(4)}</span>
                  <span>req: req_8x21_{i}</span>
                </div>
              )}
            </div>
          ))}
          {thinking && (
            <div className="chat-msg">
              <div className="who">{p.name}</div>
              <div className="bub muted" style={{fontStyle:"italic"}}>düşünüyor<span style={{letterSpacing:2}}>…</span></div>
            </div>
          )}
        </div>

        <div className="chat-input-wrap">
          <div className="chat-input">
            <textarea value={input} onChange={e=>setInput(e.target.value)} placeholder={`${p.name}'e bir şey yaz…`} onKeyDown={e=>{ if(e.key==="Enter"&&!e.shiftKey){ e.preventDefault(); send(); } }}/>
            <div className="row" style={{gap:6}}>
              <button className="btn btn-sm">{I("download",12)} attach</button>
              <button className="btn primary btn-sm" onClick={send}>Send ↵</button>
            </div>
          </div>
          <div className="row between" style={{marginTop:8}}>
            <div className="muted" style={{fontSize:11.5}}>Memory: 142 short-term · 38 long-term embeddings · 4.2k tokens of context</div>
            <div className="row" style={{gap:14,fontSize:11.5}}>
              <span className="muted">⌘↵ send · ⇧↵ newline · ⌘/ slash menu</span>
            </div>
          </div>
        </div>
      </div>

      <div className="chat-right">
        <div className="eyebrow" style={{marginBottom:8}}>Drift over conversation</div>
        <LineChart data={D4.drift} h={68} color="var(--gold)" threshold={0.32}/>
        <div className="muted" style={{fontSize:11.5,marginTop:4,marginBottom:14}}>cosine distance from baseline voice fingerprint · <span style={{color:"var(--ruby)"}}>—</span> threshold 0.32</div>

        <div className="card flat card-pad" style={{marginBottom:14,padding:14}}>
          <div className="eyebrow" style={{marginBottom:6}}>Last response · audit</div>
          <div className="col" style={{gap:6,fontSize:12.5}}>
            <div className="row between"><span>In-character</span><span className="tag moss btn-sm"><span className="dot"/>0.94</span></div>
            <div className="row between"><span>Voice match</span><span className="tag moss btn-sm"><span className="dot"/>0.91</span></div>
            <div className="row between"><span>Refusal needed</span><span className="muted">no</span></div>
            <div className="row between"><span>Tool calls</span><span className="muted">none</span></div>
          </div>
        </div>

        <div className="eyebrow" style={{marginBottom:8}}>Memory · long-term</div>
        <div className="col" style={{gap:8,fontSize:12.5}}>
          {[
            "Conversed with Zeki 4× in last 7 days",
            "Knows: Zeki teaches comp lit at Bilgi",
            "Earlier said: 'Tarkovsky'i izlerken uyumak ayıp değil'",
            "Refused: dark roleplay (1 attempt, 2 days ago)",
            "Visited topics: Hesse, Pamuk, kediler, Beyoğlu",
          ].map((t,i)=>(
            <div key={i} className="row" style={{gap:8,alignItems:"flex-start"}}>
              <span style={{color:"var(--ember)",marginTop:2}}>•</span>
              <span>{t}</span>
            </div>
          ))}
        </div>

        <div className="divider"/>
        <div className="eyebrow" style={{marginBottom:8}}>Quick guards</div>
        <div className="col" style={{gap:8}}>
          <div className="row between"><span style={{fontSize:13}}>Refuse impersonation</span><div className="toggle on"/></div>
          <div className="row between"><span style={{fontSize:13}}>Output moderation</span><div className="toggle on"/></div>
          <div className="row between"><span style={{fontSize:13}}>PII redaction</span><div className="toggle on"/></div>
          <div className="row between"><span style={{fontSize:13}}>Pause on drift</span><div className="toggle"/></div>
        </div>
      </div>
    </div>
  );
};

// ---------- Lineage ----------
const PageLineage = () => {
  const [tab, setTab] = useState("lineage");
  // Simple tree layout
  const nodes = [
    { id:"t0", name:"Yalnız Akademisyen", kind:"template", x:140, y:60 },
    { id:"v1", name:"Mert v1", kind:"persona", x:140, y:160 },
    { id:"v2", name:"Mert v2", kind:"persona", x:60, y:260 },
    { id:"v3", name:"Mert v3 (current)", kind:"current", x:60, y:360 },
    { id:"f1", name:"Erhan v1 (fork)", kind:"fork", x:240, y:260 },
    { id:"f2", name:"Erhan v2", kind:"persona", x:240, y:360 },
    { id:"f3", name:"Aysel Hanım (refork)", kind:"persona", x:380, y:260 },
  ];
  const edges = [["t0","v1"],["v1","v2"],["v2","v3"],["v1","f1"],["f1","f2"],["v1","f3"]];

  return (
    <div className="page">
      <div className="page-head">
        <div className="eyebrow">Mert Kavaklı · ancestry</div>
        <h1 className="page-title">Lineage</h1>
        <div className="page-sub">Forks branch from any version. Every edit is auditable; every version is restorable.</div>
      </div>
      <div className="tabs">
        <div className={"tab "+(tab==="lineage"?"active":"")} onClick={()=>setTab("lineage")}>Lineage tree</div>
        <div className={"tab "+(tab==="diff"?"active":"")} onClick={()=>setTab("diff")}>Diff (v2 → v3)</div>
      </div>

      {tab==="lineage" && (
        <svg viewBox="0 0 500 460" className="lineage-svg" preserveAspectRatio="xMidYMid meet">
          {edges.map(([a,b],i)=>{
            const A = nodes.find(n=>n.id===a), B = nodes.find(n=>n.id===b);
            const mid = (A.y+B.y)/2;
            return <path key={i} d={`M ${A.x} ${A.y+24} C ${A.x} ${mid} ${B.x} ${mid} ${B.x} ${B.y-24}`} stroke="var(--line-2)" fill="none" strokeWidth="1.5"/>;
          })}
          {nodes.map(n=>{
            const fill = n.kind==="current"?"var(--ember)":n.kind==="template"?"var(--bg-3)":n.kind==="fork"?"var(--plum)":"var(--bg-2)";
            const stroke = n.kind==="current"?"var(--ember)":"var(--line-2)";
            const tcolor = n.kind==="current"?"#1a0d04":"var(--ink)";
            return (
              <g key={n.id} transform={`translate(${n.x-72},${n.y-22})`}>
                <rect width="144" height="44" rx="8" fill={fill} stroke={stroke}/>
                <text x="72" y="20" textAnchor="middle" fontSize="12" fontFamily="var(--serif)" fill={tcolor}>{n.name}</text>
                <text x="72" y="34" textAnchor="middle" fontSize="9.5" fill={n.kind==="current"?"#3d1f0a":"var(--ink-3)"} fontFamily="var(--mono)" letterSpacing="1">{n.kind.toUpperCase()}</text>
              </g>
            );
          })}
        </svg>
      )}

      {tab==="diff" && (
        <div className="card card-pad">
          <h3 className="section-title" style={{marginBottom:12}}>Mert · v2 → v3</h3>
          <div className="grid grid-2" style={{gap:14}}>
            <div className="code">{`Soul.coreFear:
- "Bir gün okumayı bitirememek."
+ "Bir gün okumayı sevmediğini fark etmek."

Self.bigFive.E:
- 31
+ 24

Mask.voice:
- "Az kelimeli ama sıcak."
+ "Az kelimeli, virgülsüz, kuru bir mizah."

Surface.appearance: (unchanged)`}</div>
            <div className="col" style={{gap:10}}>
              <div className="notice"><strong>Cascade summary.</strong> 2 Soul edits cascaded into 4 Self changes and 1 Mask change. Surface untouched.</div>
              <div className="card flat card-pad" style={{padding:14}}>
                <div className="eyebrow" style={{marginBottom:6}}>Audit verdict on v3</div>
                <div className="row" style={{gap:8}}>
                  <span className="tag moss"><span className="dot"/>pass</span>
                  <span className="muted" style={{fontSize:12}}>coherence improved 4.4 → 4.6</span>
                </div>
              </div>
              <div className="row" style={{gap:8}}>
                <button className="btn">Restore v2</button>
                <button className="btn primary">Approve & lock v3</button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ---------- Marketplace ----------
const MARKETPLACE = [
  { id:"m1", name:"The Gentle Therapist", creator:"@gulin", price:"Free", downloads:"4.2k", rating:4.7, cls:"portrait-mask", arch:"Healer", tags:["en","tr"]},
  { id:"m2", name:"Skeptical Detective", creator:"@noir.studio", price:"$9", downloads:"2.1k", rating:4.5, cls:"portrait-strip", arch:"Witness", tags:["en"]},
  { id:"m3", name:"Babaanne Selma", creator:"@persona.team", price:"Free", downloads:"8.4k", rating:4.9, cls:"portrait-ruby", arch:"Caregiver", tags:["tr"]},
  { id:"m4", name:"The Reluctant Mentor", creator:"@oguz", price:"$12", downloads:"890", rating:4.4, cls:"portrait-self", arch:"Sage", tags:["en","de"]},
  { id:"m5", name:"Dockworker w/ a poem habit", creator:"@kentish", price:"$5", downloads:"1.3k", rating:4.6, cls:"portrait-plum", arch:"Witness", tags:["en"]},
  { id:"m6", name:"Aikido Sensei (Kyoto)", creator:"@hanshi", price:"$19", downloads:"540", rating:4.8, cls:"portrait-soul", arch:"Sage", tags:["ja","en"]},
  { id:"m7", name:"Paranoid Sysadmin", creator:"@root.fm", price:"Free", downloads:"3.7k", rating:4.3, cls:"portrait-sky", arch:"Witness", tags:["en"]},
  { id:"m8", name:"Sufi Hat Sokağı Tüccarı", creator:"@persona.team", price:"$7", downloads:"720", rating:4.7, cls:"portrait-mask", arch:"Trickster", tags:["tr"]},
];

const PageMarket = ({ go }) => (
  <div className="page">
    <div className="market-hero" style={{marginBottom:22}}>
      <div className="eyebrow" style={{marginBottom:8}}>Marketplace · 1,840 personas</div>
      <h1 className="page-title" style={{fontSize:38, maxWidth:740}}>Borrow a soul. <span className="muted">Or sell yours.</span></h1>
      <div className="page-sub" style={{maxWidth:680}}>Curated by humans, audited by Persona. Creators keep 70% of revenue. Every persona ships with its full Soul→Surface; nothing hidden.</div>
      <div className="row" style={{marginTop:14,gap:10}}>
        <button className="btn primary">Browse all</button>
        <button className="btn">Become a creator</button>
      </div>
    </div>

    <div className="row between" style={{marginBottom:14}}>
      <h3 className="section-title">Trending this week</h3>
      <div className="pill-tabs">
        <span className="pt on">All</span><span className="pt">Free</span><span className="pt">Paid</span><span className="pt">New</span><span className="pt">Staff picks</span>
      </div>
    </div>
    <div className="grid grid-4">
      {MARKETPLACE.map(m=>(
        <div key={m.id} className="card market-card">
          <div className={"persona-portrait market-cover "+m.cls}><span className="placeholder-ph">[ portrait ]</span></div>
          <div className="market-body">
            <div className="row between"><div className="market-creator">{m.creator}</div><div className="mono" style={{fontSize:12}}>★ {m.rating}</div></div>
            <div style={{fontFamily:"var(--serif)",fontSize:16,marginTop:4}}>{m.name}</div>
            <div className="row between" style={{marginTop:8}}>
              <span className="tag ember"><span className="dot"/>{m.arch}</span>
              <span style={{fontSize:13,fontFamily:"var(--mono)"}}>{m.price}</span>
            </div>
            <div className="muted mono" style={{fontSize:11,marginTop:8}}>{m.downloads} downloads · {m.tags.join(", ")}</div>
          </div>
        </div>
      ))}
    </div>
  </div>
);

window.PageChat = PageChat;
window.PageLineage = PageLineage;
window.PageMarket = PageMarket;
