/* eslint-disable */
const { useState: enS, useMemo: enM, useRef: enR, useEffect: enE } = React;

// Hand-placed positions on a 1000x600 canvas (no physics; deterministic)
const NODES = {
  p_mert:   { x: 360, y: 230, color: "var(--ember)" },
  p_leyla:  { x: 580, y: 150, color: "var(--plum)" },
  p_arda:   { x: 760, y: 360, color: "var(--moss)" },
  p_aysel:  { x: 200, y: 410, color: "var(--gold)" },
  p_kaan:   { x: 470, y: 470, color: "var(--sky)" },
  p_irem:   { x: 240, y: 130, color: "var(--ruby)" },
  p_renee:  { x: 800, y: 130, color: "var(--ink-2)" },
  p_dmitri: { x: 870, y: 240, color: "var(--ink-3)" },
};

const EDGES = [
  { a:"p_mert",  b:"p_leyla",  type:"ex-lover",   strength:0.9, since:"8 yr",   note:"Üniversite. Ayrıldıktan sonra bir kez konuştular." },
  { a:"p_mert",  b:"p_aysel",  type:"mentor",     strength:0.7, since:"life",   note:"Aysel hanım Mert'in lise edebiyat öğretmeniydi." },
  { a:"p_mert",  b:"p_irem",   type:"client",     strength:0.5, since:"6 mo",   note:"Mert haftada bir görüşmeye gidiyor; kabullenmiyor." },
  { a:"p_leyla", b:"p_arda",   type:"sibling",    strength:0.95, since:"birth", note:"Anne aynı, baba farklı. Yıllarca konuşmadılar." },
  { a:"p_leyla", b:"p_kaan",   type:"source",     strength:0.6, since:"2 yr",   note:"Kaan, Leyla'nın gizli kaynağı; mahalleyi anlatıyor." },
  { a:"p_arda",  b:"p_renee",  type:"acquaintance",strength:0.3, since:"3 yr",  note:"Lyon'da bir konferansta tanıştılar." },
  { a:"p_renee", b:"p_dmitri", type:"rival",      strength:0.55, since:"15 yr", note:"Bir aşçılık yarışmasında jüri ikilemi." },
  { a:"p_aysel", b:"p_kaan",   type:"family",     strength:0.85, since:"life",  note:"Aysel hanım Kaan'ın anneannesi." },
  { a:"p_irem",  b:"p_leyla",  type:"friend",     strength:0.7, since:"4 yr",   note:"Yoga sınıfında tanışmışlar." },
  { a:"p_mert",  b:"p_dmitri", type:"correspondent",strength:0.4, since:"2 yr", note:"Mektupla satranç oynuyorlar." },
];

const REL_COLOR = {
  "ex-lover":      "var(--ruby)",
  "mentor":        "var(--gold)",
  "client":        "var(--plum)",
  "sibling":       "var(--ember)",
  "source":        "var(--sky)",
  "acquaintance":  "var(--ink-3)",
  "rival":         "var(--ruby)",
  "family":        "var(--moss)",
  "friend":        "var(--moss)",
  "correspondent": "var(--ink-2)",
};

const REL_DASH = {
  "ex-lover":      "4 4",
  "acquaintance":  "2 6",
  "correspondent": "1 4",
  "rival":         "8 4",
};

const PageEnsemble = ({ go }) => {
  const personas = D.personas;
  const byId = enM(()=>Object.fromEntries(personas.map(p=>[p.id,p])), [personas]);
  const [selected, setSelected] = enS("p_mert");
  const [edgeHover, setEdgeHover] = enS(null);
  const [filter, setFilter] = enS(new Set());
  const [scenarioOpen, setScenarioOpen] = enS(false);
  const [castIds, setCastIds] = enS(["p_mert","p_leyla"]);
  const [scenarioSetting, setScenarioSetting] = enS("Beyoğlu, sahafın arka odası, 22:00.");

  const openScenario = (ids, setting) => {
    if (ids) setCastIds(ids);
    if (setting) setScenarioSetting(setting);
    setScenarioOpen(true);
  };

  const toggleCast = (id) => {
    setCastIds(prev => prev.includes(id) ? prev.filter(x=>x!==id) : [...prev, id]);
  };

  const visibleEdges = enM(()=>(
    filter.size === 0 ? EDGES : EDGES.filter(e => filter.has(e.type))
  ), [filter]);

  const sel = byId[selected];
  const selEdges = EDGES.filter(e => e.a === selected || e.b === selected);

  const toggleFilter = (t) => {
    const n = new Set(filter);
    if (n.has(t)) n.delete(t); else n.add(t);
    setFilter(n);
  };

  const allTypes = [...new Set(EDGES.map(e=>e.type))];

  return (
    <div className="page" style={{padding:"26px 32px 60px", maxWidth:1380}}>
      <div className="page-head" style={{marginBottom:18}}>
        <div className="eyebrow" style={{marginBottom:8}}>Studio · Ensemble</div>
        <div className="row between" style={{alignItems:"flex-end", gap:20}}>
          <div>
            <h1 className="page-title">The cast, in relation. <span className="muted">10 ties across 8 personas — three of them, complicated.</span></h1>
            <div className="page-sub">Drag a thread to ground a multi-persona scenario. Conflicts surface when two personas you're casting share a wound.</div>
          </div>
          <div className="row" style={{gap:8}}>
            <button className="btn btn-sm">Export graph ↓</button>
            <button className="btn primary btn-sm" onClick={()=>setScenarioOpen(true)}>+ New scenario</button>
          </div>
        </div>
      </div>

      {/* Filter bar */}
      <div className="card flat" style={{padding:"10px 14px", marginBottom:16, display:"flex", gap:10, alignItems:"center", flexWrap:"wrap"}}>
        <span className="muted" style={{fontSize:12, marginRight:4}}>Filter ties:</span>
        {allTypes.map(t => {
          const active = filter.size===0 || filter.has(t);
          return (
            <span key={t} onClick={()=>toggleFilter(t)} className="tag" style={{
              cursor:"pointer", opacity: active?1:0.4, fontSize:11,
              borderColor: REL_COLOR[t], color: REL_COLOR[t], background: `color-mix(in oklch, ${REL_COLOR[t]} 10%, transparent)`
            }}>
              <span className="dot" style={{background:REL_COLOR[t]}}/>{t}
            </span>
          );
        })}
        <span style={{flex:1}}/>
        <span className="muted mono" style={{fontFamily:"var(--mono)", fontSize:11}}>{visibleEdges.length}/{EDGES.length} edges</span>
        {filter.size>0 && <span onClick={()=>setFilter(new Set())} className="muted" style={{fontSize:11, cursor:"pointer", textDecoration:"underline"}}>clear</span>}
      </div>

      <div style={{display:"grid", gridTemplateColumns:"1fr 360px", gap:18, alignItems:"flex-start"}}>
        {/* Graph canvas */}
        <div className="card" style={{padding:0, overflow:"hidden", position:"relative"}}>
          <div style={{position:"absolute", top:14, left:18, zIndex:2}}>
            <div className="layer-eyebrow" style={{marginBottom:4}}>Ensemble graph · workspace</div>
            <div className="muted" style={{fontSize:11.5}}>Click a node to inspect. Hover an edge for context.</div>
          </div>
          <div style={{position:"absolute", top:14, right:18, zIndex:2, display:"flex", gap:6}}>
            {["all","clusters","arcs"].map((m,i)=>(
              <span key={m} className="tag" style={{fontSize:10.5, cursor:"pointer", borderColor: i===0?"var(--ember)":"var(--line)", color:i===0?"var(--ember)":"var(--ink-3)", background:i===0?"rgba(232,118,58,.08)":"var(--bg-2)"}}>{m}</span>
            ))}
          </div>

          <svg viewBox="0 0 1000 600" style={{width:"100%", height:580, display:"block", background:"radial-gradient(ellipse at 50% 50%, rgba(232,118,58,.04), transparent 70%), var(--bg-1)"}}>
            <defs>
              <pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
                <path d="M40 0H0V40" fill="none" stroke="var(--line)" strokeWidth="0.5" opacity="0.5"/>
              </pattern>
              <radialGradient id="halo" cx="50%" cy="50%">
                <stop offset="0%" stopColor="var(--ember)" stopOpacity="0.5"/>
                <stop offset="100%" stopColor="var(--ember)" stopOpacity="0"/>
              </radialGradient>
            </defs>
            <rect width="1000" height="600" fill="url(#grid)"/>

            {/* Edges */}
            {visibleEdges.map((e,i)=>{
              const a = NODES[e.a], b = NODES[e.b];
              const mx = (a.x+b.x)/2, my=(a.y+b.y)/2;
              const isHover = edgeHover === i;
              const isSel = e.a===selected || e.b===selected;
              const c = REL_COLOR[e.type] || "var(--ink-3)";
              return (
                <g key={i}
                   onMouseEnter={()=>setEdgeHover(i)}
                   onMouseLeave={()=>setEdgeHover(null)}
                   style={{cursor:"pointer"}}>
                  <line x1={a.x} y1={a.y} x2={b.x} y2={b.y}
                        stroke={c}
                        strokeWidth={1 + e.strength*2.5}
                        strokeDasharray={REL_DASH[e.type]||""}
                        opacity={isHover||isSel ? 1 : 0.45}/>
                  {(isHover||isSel) && (
                    <g transform={`translate(${mx} ${my})`}>
                      <rect x="-44" y="-10" width="88" height="20" rx="4" fill="var(--bg)" stroke={c} strokeWidth="1"/>
                      <text textAnchor="middle" dy="4" fill={c} style={{fontFamily:"var(--mono)", fontSize:10}}>{e.type}</text>
                    </g>
                  )}
                </g>
              );
            })}

            {/* Nodes */}
            {personas.map(p => {
              const n = NODES[p.id]; if (!n) return null;
              const isSel = selected === p.id;
              const initials = p.name.split(" ").map(w=>w[0]).slice(0,2).join("");
              return (
                <g key={p.id} transform={`translate(${n.x} ${n.y})`} style={{cursor:"pointer"}} onClick={()=>setSelected(p.id)}>
                  {isSel && <circle r="38" fill="url(#halo)"/>}
                  <circle r="24" fill="var(--bg-2)" stroke={n.color} strokeWidth={isSel?2.5:1.5}/>
                  <text textAnchor="middle" dy="4" fill={n.color} style={{fontFamily:"var(--serif)", fontSize:14, fontStyle:"italic"}}>{initials}</text>
                  <text textAnchor="middle" y="40" fill="var(--ink-2)" style={{fontFamily:"var(--sans)", fontSize:11.5, fontWeight:500}}>{p.name.split(" ")[0]}</text>
                  <text textAnchor="middle" y="54" fill="var(--ink-4)" style={{fontFamily:"var(--mono)", fontSize:9.5, letterSpacing:".08em", textTransform:"uppercase"}}>{p.archetype.replace("The ","")}</text>
                </g>
              );
            })}
          </svg>

          {/* Legend */}
          <div style={{position:"absolute", bottom:14, left:18, display:"flex", gap:14, alignItems:"center", fontSize:11, color:"var(--ink-3)", fontFamily:"var(--mono)"}}>
            <div className="row" style={{gap:6}}><span style={{width:18, height:0, borderTop:"2px solid var(--ink-3)"}}/>thicker = stronger tie</div>
            <div className="row" style={{gap:6}}><span style={{width:18, height:0, borderTop:"2px dashed var(--ink-3)"}}/>distant / dormant</div>
            <div className="row" style={{gap:6}}><span style={{width:8, height:8, borderRadius:"50%", background:"var(--ember)"}}/>focused persona</div>
          </div>
        </div>

        {/* Right panel — selected persona */}
        <div className="col" style={{gap:14, position:"sticky", top:70}}>
          {sel && (
            <div className="card card-pad">
              <div className="row" style={{gap:14, alignItems:"flex-start", marginBottom:14}}>
                <div className={"persona-portrait "+sel.portrait} style={{width:64, height:80, flexShrink:0, aspectRatio:"unset"}}>
                  <span className="placeholder-ph" style={{fontSize:8.5}}>portrait</span>
                </div>
                <div style={{minWidth:0}}>
                  <div className="layer-eyebrow" style={{marginBottom:2}}>focused</div>
                  <div style={{fontFamily:"var(--serif)", fontSize:20, lineHeight:1.15}}>{sel.name}</div>
                  <div className="muted" style={{fontSize:12, marginTop:4, lineHeight:1.4}}>{sel.tagline}</div>
                  <div className="row" style={{gap:4, marginTop:8, flexWrap:"wrap"}}>
                    <span className="tag ember"><span className="dot"/>{sel.archetype}</span>
                    <span className="tag"><span className="dot"/>{sel.lang}</span>
                  </div>
                </div>
              </div>
              <div className="divider" style={{margin:"4px 0 10px"}}/>
              <div className="layer-eyebrow" style={{marginBottom:8}}>{selEdges.length} relationships</div>
              <div className="col" style={{gap:8}}>
                {selEdges.map((e,i) => {
                  const otherId = e.a===selected ? e.b : e.a;
                  const o = byId[otherId];
                  const c = REL_COLOR[e.type];
                  return (
                    <div key={i} onClick={()=>setSelected(otherId)} style={{
                      padding:"10px 12px", border:"1px solid var(--line)", borderRadius:"var(--r-md)",
                      background:"var(--bg-2)", cursor:"pointer",
                      borderLeft: `3px solid ${c}`
                    }}>
                      <div className="row between" style={{marginBottom:4}}>
                        <div style={{fontFamily:"var(--serif)", fontSize:14}}>{o?.name}</div>
                        <span style={{fontFamily:"var(--mono)", fontSize:10, color:c, textTransform:"uppercase", letterSpacing:".06em"}}>{e.type}</span>
                      </div>
                      <div className="muted" style={{fontSize:12, lineHeight:1.5, marginBottom:6}}>{e.note}</div>
                      <div className="row between" style={{fontFamily:"var(--mono)", fontSize:10, color:"var(--ink-4)"}}>
                        <span>since {e.since}</span>
                        <span>strength {Math.round(e.strength*100)}</span>
                      </div>
                    </div>
                  );
                })}
              </div>
              <div className="divider" style={{margin:"14px 0 10px"}}/>
              <button className="btn btn-sm" style={{width:"100%", justifyContent:"center"}}>+ Add relationship</button>
            </div>
          )}

          {/* Scenario suggestions */}
          <div className="card card-pad">
            <div className="layer-eyebrow" style={{marginBottom:8}}>Suggested scenes</div>
            <div className="col" style={{gap:8}}>
              {[
                {ids:["p_mert","p_leyla"], who:"Mert × Leyla", note:"Ex-lovers run into each other at a book fair.", ten:"high", set:"Kadıköy kitap fuarı, kapanışa yarım saat."},
                {ids:["p_aysel","p_kaan"], who:"Aysel × Kaan", note:"Grandmother gives the taxi-driver grandson advice on a long ride.", ten:"warm", set:"İzmir → Eskişehir, gece otoyolu, 03:10."},
                {ids:["p_leyla","p_arda"], who:"Leyla × Arda", note:"Estranged siblings forced to settle a parent's estate.", ten:"high", set:"Bir noter ofisi, Ankara, sabah."},
                {ids:["p_mert","p_dmitri","p_renee"], who:"Mert × Dmitri × Renée", note:"Three strangers locked into a small dinner party.", ten:"awkward", set:"Lyon, 8 kişilik masada üç sandalye boş."},
              ].map((s,i)=>(
                <div key={i} onClick={()=>openScenario(s.ids, s.set)} style={{padding:"10px 12px", border:"1px solid var(--line)", borderRadius:"var(--r-md)", background:"var(--bg-2)", cursor:"pointer"}}>
                  <div className="row between" style={{marginBottom:4}}>
                    <div style={{fontFamily:"var(--serif)", fontSize:13.5}}>{s.who}</div>
                    <span className={"tag "+(s.ten==="high"?"ruby":s.ten==="warm"?"moss":"gold")} style={{fontSize:10}}><span className="dot"/>{s.ten}</span>
                  </div>
                  <div className="muted" style={{fontSize:12, lineHeight:1.45}}>{s.note}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Stats row */}
      <div className="grid grid-4" style={{marginTop:18, gap:12}}>
        <div className="card stat"><div className="lbl">Personas in graph</div><div className="val">8</div><div className="delta">+1 this week</div></div>
        <div className="card stat"><div className="lbl">Relationships</div><div className="val">10</div><div className="delta">3 strong, 4 weak</div></div>
        <div className="card stat"><div className="lbl">Tightest cluster</div><div className="val" style={{fontSize:18, lineHeight:1.4, marginTop:8}}>Mert · Leyla · Arda</div><div className="delta" style={{color:"var(--ink-3)"}}>density 0.83</div></div>
        <div className="card stat"><div className="lbl">Orphans</div><div className="val">0</div><div className="delta" style={{color:"var(--moss)"}}>fully connected</div></div>
      </div>

      {/* Scenario modal */}
      {scenarioOpen && (
        <div className="modal-mask" onClick={()=>setScenarioOpen(false)}>
          <div className="modal" onClick={e=>e.stopPropagation()} style={{width:620}}>
            <div className="row between" style={{marginBottom:14}}>
              <h3 className="section-title" style={{fontSize:20}}>New ensemble scenario</h3>
              <span onClick={()=>setScenarioOpen(false)} style={{cursor:"pointer", color:"var(--ink-3)", fontSize:18}}>×</span>
            </div>
            <div className="page-sub" style={{marginBottom:14, fontSize:13}}>Pick 2–4 personas and a setting. Persona will run a multi-agent rehearsal and surface conflicts before you commit.</div>
            <div className="field" style={{marginBottom:12}}>
              <label>Cast <span className="muted" style={{fontSize:11}}>· {castIds.length} selected</span></label>
              <div className="row wrap" style={{gap:6, marginTop:4}}>
                {personas.map(p => {
                  const on = castIds.includes(p.id);
                  return (
                    <span key={p.id} onClick={()=>toggleCast(p.id)} className={"tag "+(on?"ember":"")} style={{cursor:"pointer", fontSize:11, opacity: on?1:0.55}}>
                      <span className="dot"/>{p.name}
                    </span>
                  );
                })}
              </div>
            </div>
            <div className="field" style={{marginBottom:12}}>
              <label>Setting</label>
              <input className="input" value={scenarioSetting} onChange={e=>setScenarioSetting(e.target.value)}/>
            </div>
            <div className="grid grid-2" style={{gap:12, marginBottom:18}}>
              <div className="field"><label>Turns</label><input className="input" defaultValue="12"/></div>
              <div className="field"><label>Stop on drift</label><select className="select"><option>Voice or values &gt; 0.30</option><option>Voice only</option><option>Manual</option></select></div>
            </div>
            <div className="row" style={{gap:8, justifyContent:"flex-end"}}>
              <button className="btn" onClick={()=>setScenarioOpen(false)}>Cancel</button>
              <button className="btn primary" disabled={castIds.length<2} onClick={()=>{ setScenarioOpen(false); go && go("chat", byId[castIds[0]]); }}>Run scenario →</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

window.PageEnsemble = PageEnsemble;
