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

// ---------- Create / Generation ----------
const PIPELINE_STEPS = [
  { name:"Intent parse",     model:"haiku-4-5",  ms:"~1.2s",  desc:"Parse your brief into structured intent (constraints, language, refusal list).",
    stream:`{ "language": "tr", "archetype": "Sage|Witness", "age_range": [30, 45],\n  "occupation_hints": ["sahaf","akademisyen"],\n  "tone": "melancholic, sparse",\n  "refusals": ["impersonation","minor"] }` },
  { name:"Soul draft",       model:"opus-4-1",   ms:"~6.4s",  desc:"Core desire, fear, conflict, wound, growth potential. Slowest, most expensive.",
    stream:`core_desire   ▸ Anlaşılmak, ama hiç açıklamak zorunda kalmamak.\ncore_fear     ▸ Bir gün okumayı sevmediğini fark etmek.\ncore_conflict ▸ Yalnızlık onu hem koruyor hem küçültüyor.\nwound         ▸ Akademiden ayrıldığı gün kimse aramadı; bunu hâlâ unutamıyor.\ngrowth_arc    ▸ Sessizliğini bir kibre değil, bir hediyeye dönüştürmek.` },
  { name:"Self + Mask enrich", model:"sonnet-4-5", ms:"~4.1s", desc:"Big Five, values, attachment, conversational voice, humor, formality.",
    stream:`big_five     ▸ O 92 · C 71 · E 24 · A 68 · N 56\nattachment   ▸ avoidant-leaning secure\nvalues       ▸ ["sahihlik","bilgi","yalnızlığa saygı"]\nvoice        ▸ "az kelimeli, virgülsüz, kuru bir mizah"\nhumor        ▸ ironik-tonlu, sarkazm yok\nformality    ▸ kibar mesafeli` },
  { name:"Surface ground",   model:"sonnet-4-5", ms:"~3.0s", desc:"Name, age, city, occupation, biography, appearance — must not collide with celebrity index.",
    stream:`name        ▸ Mert Kavaklı\nage         ▸ 35\nlocation    ▸ İstanbul, Beyoğlu\noccupation  ▸ Antikvar sahaf (eski akademisyen)\neducation   ▸ Boğaziçi, Karşılaştırmalı Edebiyat (terk)\nappearance  ▸ Uzun, sıska. Boyalı eski deri ceket. Saatini hep kontrol eder.` },
  { name:"Consistency audit", model:"opus-4-1",   ms:"~5.8s", desc:"Independent LLM judges Soul→Self→Mask→Surface for contradictions. Fails block save.",
    stream:`scoring     ▸ coherence 4.6 · contradiction-rate 0.04\nflags       ▸ none\nverdict     ▸ pass` },
  { name:"Fingerprint + Test", model:"sonnet-4-5", ms:"~7.2s", desc:"Voice fingerprint vector + provocation suite (24 prompts) + cross-persona distinctiveness.",
    stream:`voice_fp    ▸ vec[768] · entropy 0.84\nprovocation ▸ 22 / 24 passed\nfailures    ▸ ["dark-roleplay request", "minor scenario"] (refused — pass)\ndistinct    ▸ 0.61 vs corpus median 0.42` },
];

const PageCreate = ({ go, runState, setRunState }) => {
  const [brief, setBrief] = useState("35 yaşında, yalnız, entelektüel bir adam. Eskiden akademisyendi, şimdi bir antikvar sahaf işletiyor. Konuşmaları kısa ve melankolik. Türkçe, İstanbul.");
  const [adv, setAdv] = useState({
    language:"tr", archetype:"sage", style:"literary",
    audit:true, fingerprint:true, suite:true, locale:"İstanbul",
    primaryModel:"opus-4-1",
  });

  const start = () => {
    setRunState({ running:true, step:0, done:false });
    let s = 0;
    const tick = () => {
      s++;
      if (s >= PIPELINE_STEPS.length) {
        setRunState({ running:false, step:PIPELINE_STEPS.length, done:true });
      } else {
        setRunState({ running:true, step:s, done:false });
        setTimeout(tick, 1400);
      }
    };
    setTimeout(tick, 1400);
  };

  return (
    <div className="page" style={{display:"grid",gridTemplateColumns:"380px 1fr",gap:28,maxWidth:1500}}>
      <div>
        <div className="page-head">
          <div className="eyebrow">Step 1 — brief</div>
          <h1 className="page-title">A character, in your own words.</h1>
          <div className="page-sub">Soul → Self → Mask → Surface. Persona writes downward; you write upward.</div>
        </div>

        <div className="field" style={{marginBottom:14}}>
          <label>Brief — write like you'd describe someone to a friend</label>
          <textarea className="textarea" value={brief} onChange={e=>setBrief(e.target.value)} rows={6}/>
        </div>

        <div className="grid grid-2" style={{gap:10, marginBottom:14}}>
          <div className="field"><label>Language</label>
            <select className="select" value={adv.language} onChange={e=>setAdv({...adv,language:e.target.value})}>
              <option value="tr">Türkçe</option><option value="en">English</option><option value="es">Español</option><option value="de">Deutsch</option><option value="fr">Français</option><option value="ja">日本語</option><option value="zh">中文</option>
            </select>
          </div>
          <div className="field"><label>Archetype hint</label>
            <select className="select" value={adv.archetype} onChange={e=>setAdv({...adv,archetype:e.target.value})}>
              <option value="sage">Sage</option><option value="witness">Witness</option><option value="caregiver">Caregiver</option><option value="trickster">Trickster</option><option value="craftsman">Craftsman</option><option value="auto">— let model choose —</option>
            </select>
          </div>
          <div className="field"><label>Locale</label>
            <input className="input" value={adv.locale} onChange={e=>setAdv({...adv,locale:e.target.value})}/>
          </div>
          <div className="field"><label>Voice style</label>
            <select className="select" value={adv.style} onChange={e=>setAdv({...adv,style:e.target.value})}>
              <option value="literary">Literary, sparse</option><option value="warm">Warm, conversational</option><option value="clinical">Clinical, precise</option><option value="streetwise">Streetwise, blunt</option>
            </select>
          </div>
        </div>

        <div className="card flat" style={{padding:16, marginBottom:14}}>
          <div className="eyebrow" style={{marginBottom:10}}>Pipeline knobs</div>
          {[
            ["Consistency audit (extra Opus call)", "audit", "+$0.18"],
            ["Voice fingerprint vector", "fingerprint", "+$0.04"],
            ["Provocation test suite (24 prompts)", "suite", "+$0.22"],
          ].map(([lbl,k,cost])=>(
            <div key={k} className="row between" style={{padding:"8px 0",borderTop:"1px solid var(--line)"}}>
              <div>
                <div style={{fontSize:13.5}}>{lbl}</div>
                <div className="muted" style={{fontSize:11.5}}>{cost} · org-default: on</div>
              </div>
              <div className={"toggle "+(adv[k]?"on":"")} onClick={()=>setAdv({...adv,[k]:!adv[k]})}/>
            </div>
          ))}
        </div>

        <div className="row between" style={{marginBottom:8}}>
          <div className="muted" style={{fontSize:12}}>Estimated: <span style={{color:"var(--ink)"}}>~27s</span> · <span style={{color:"var(--ink)"}}>$0.84</span> · <span style={{color:"var(--ink)"}}>4,030 tokens</span></div>
        </div>
        <button className="btn primary" style={{width:"100%",justifyContent:"center"}} disabled={runState.running} onClick={start}>
          {runState.running? "Generating…" : "Generate persona"}
        </button>
      </div>

      <div>
        <div className="page-head">
          <div className="eyebrow">Step 2 — pipeline</div>
          <h2 className="page-title" style={{fontSize:22}}>{runState.done ? "Done. Meet Mert." : runState.running ? "Building character…" : "Ready when you are."}</h2>
        </div>

        <div className="pipeline">
          {PIPELINE_STEPS.map((s,i)=>{
            const status = runState.done ? "done" : i < runState.step ? "done" : i===runState.step && runState.running ? "running" : "queued";
            return (
              <div key={i} className={"pipe-step "+status}>
                <div className="num">{status==="done"?"✓":i+1}</div>
                <div className="body">
                  <div className="row between">
                    <div className="nm">{s.name}</div>
                    <div className="meta" style={{margin:0}}>
                      <span className="m">{s.model}</span><span className="m">{s.ms}</span>
                    </div>
                  </div>
                  <div className="desc">{s.desc}</div>
                  {(status==="running" || status==="done") && (
                    <div className="stream">{s.stream}</div>
                  )}
                </div>
              </div>
            );
          })}
        </div>

        {runState.done && (
          <div className="row" style={{marginTop:16,gap:10}}>
            <button className="btn primary" onClick={()=>go("detail", D2.personas[0])}>Open persona →</button>
            <button className="btn">Save & create another</button>
            <button className="btn ghost">Discard</button>
          </div>
        )}
      </div>
    </div>
  );
};

// ---------- Library ----------
const PageLibrary = ({ go }) => {
  const [q, setQ] = useState("");
  const [view, setView] = useState("grid");
  const [filter, setFilter] = useState("all");
  const filtered = D2.personas.filter(p => {
    if (filter !== "all" && p.visibility !== filter) return false;
    if (q && !(p.name+p.tagline+p.archetype).toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });
  return (
    <div className="page">
      <div className="page-head row between">
        <div>
          <div className="eyebrow">152 personas · Studio</div>
          <h1 className="page-title">Library</h1>
        </div>
        <div className="row" style={{gap:10}}>
          <button className="btn">{I("download",14)} Export</button>
          <button className="btn primary" onClick={()=>go("create")}>{I("plus",14)} New persona</button>
        </div>
      </div>

      <div className="row" style={{marginBottom:18,gap:12,flexWrap:"wrap"}}>
        <div className="search" style={{flex:1,minWidth:280}}>
          {I("search",14)}
          <input value={q} onChange={e=>setQ(e.target.value)} placeholder="Search by name, tagline, archetype, language…"/>
        </div>
        <div className="pill-tabs">
          {["all","public","workspace","private"].map(k => (
            <span key={k} className={"pt "+(filter===k?"on":"")} onClick={()=>setFilter(k)}>{k}</span>
          ))}
        </div>
        <div className="pill-tabs">
          <span className={"pt "+(view==="grid"?"on":"")} onClick={()=>setView("grid")}>Grid</span>
          <span className={"pt "+(view==="table"?"on":"")} onClick={()=>setView("table")}>Table</span>
        </div>
      </div>

      <div className="row" style={{marginBottom:18,gap:6,flexWrap:"wrap"}}>
        {["sage","witness","caregiver","truth-teller","craftsman"].map(t=>
          <span key={t} className="tag"><span className="dot"/>{t}</span>
        )}
        {["tr","en","fr","ru"].map(t=>
          <span key={t} className="tag sky"><span className="dot"/>lang:{t}</span>
        )}
        <span className="tag moss"><span className="dot"/>quality &gt; 4.0</span>
        <span className="tag" style={{cursor:"pointer"}}>{I("plus",10)} add filter</span>
      </div>

      {view==="grid" ? (
        <div className="grid grid-4">
          {filtered.map(p => <PersonaCard key={p.id} p={p} onClick={()=>go("detail",p)}/>)}
        </div>
      ) : (
        <div className="card" style={{padding:0}}>
        <table className="tbl">
          <thead><tr><th>Name</th><th>Archetype</th><th>Language</th><th>Quality</th><th>Distinct.</th><th>Visibility</th><th>Updated</th></tr></thead>
          <tbody>
            {filtered.map(p=>(
              <tr key={p.id} onClick={()=>go("detail",p)} style={{cursor:"pointer"}}>
                <td><div style={{fontFamily:"var(--serif)",fontSize:15}}>{p.name}</div><div className="muted" style={{fontSize:12}}>{p.tagline}</div></td>
                <td>{p.archetype}</td>
                <td className="mono">{p.lang}</td>
                <td className="mono">{(p.quality||4.0).toFixed(2)}</td>
                <td className="mono">{(p.distinctiveness||0.5).toFixed(2)}</td>
                <td><span className={"tag "+(p.visibility==="public"?"moss":p.visibility==="workspace"?"sky":"")}><span className="dot"/>{p.visibility}</span></td>
                <td className="mono muted">2d ago</td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      )}
    </div>
  );
};

// ---------- DNA Radar ----------
const DNARadar = ({ values, size=240 }) => {
  const cx = size/2, cy = size/2, r = size/2 - 30;
  const labels = Object.keys(values);
  const n = labels.length;
  const pt = (i, val) => {
    const a = -Math.PI/2 + (i/n)*Math.PI*2;
    const rr = r * (val/100);
    return [cx + Math.cos(a)*rr, cy + Math.sin(a)*rr];
  };
  const labelPt = (i) => {
    const a = -Math.PI/2 + (i/n)*Math.PI*2;
    return [cx + Math.cos(a)*(r+18), cy + Math.sin(a)*(r+18)];
  };
  const points = labels.map((k,i) => pt(i, values[k]).join(",")).join(" ");
  return (
    <svg width={size} height={size}>
      {[0.25,0.5,0.75,1].map((rr,i)=>(
        <polygon key={i} className="dna-grid" points={
          labels.map((_,j)=>{
            const a = -Math.PI/2 + (j/n)*Math.PI*2;
            return `${cx+Math.cos(a)*r*rr},${cy+Math.sin(a)*r*rr}`;
          }).join(" ")
        }/>
      ))}
      {labels.map((k,i)=>{
        const a = -Math.PI/2 + (i/n)*Math.PI*2;
        return <line key={k} x1={cx} y1={cy} x2={cx+Math.cos(a)*r} y2={cy+Math.sin(a)*r} className="dna-grid"/>;
      })}
      <polygon points={points} className="dna-shape"/>
      {labels.map((k,i)=>{
        const [x,y] = pt(i,values[k]);
        return <circle key={k} cx={x} cy={y} r={3} className="dna-vertex"/>;
      })}
      {labels.map((k,i)=>{
        const [x,y] = labelPt(i);
        return <text key={k} x={x} y={y} textAnchor="middle" dominantBaseline="middle" className="dna-axis-label">{k}</text>;
      })}
    </svg>
  );
};

const BigFiveBars = ({ values }) => {
  const labels = { O:"Openness", C:"Conscientiousness", E:"Extraversion", A:"Agreeableness", N:"Neuroticism" };
  return (
    <div className="b5">
      {Object.entries(values).map(([k,v])=>(
        <div key={k} className="b5-row">
          <div>{labels[k]}</div>
          <div className="b5-bar"><i style={{width:v+"%"}}/></div>
          <div className="b5-val">{v}</div>
        </div>
      ))}
    </div>
  );
};

window.PageCreate = PageCreate;
window.PageLibrary = PageLibrary;
window.DNARadar = DNARadar;
window.BigFiveBars = BigFiveBars;
