/* eslint-disable */
const { useState, useEffect, useRef, useMemo } = React;
const D = window.PERSONA_DATA;

// ---------- Icons ----------
const Ic = ({ d, s=16 }) => (
  <svg className="ic" width={s} height={s} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d={d}/></svg>
);
const ICON = {
  home: "M3 12l9-8 9 8M5 10v10h14V10",
  spark: "M12 3v6 M12 15v6 M3 12h6 M15 12h6 M5.6 5.6l4 4 M14.4 14.4l4 4 M5.6 18.4l4-4 M14.4 9.6l4-4",
  library: "M4 5h6v14H4z M14 5h6v14h-6z",
  chat: "M21 12a8 8 0 1 1-3.5-6.6L21 4l-1 4.4A8 8 0 0 1 21 12z",
  graph: "M4 20V8 M10 20V4 M16 20v-8 M22 20v-12",
  market: "M3 7h18l-2 12H5L3 7z M8 7V5a4 4 0 0 1 8 0v2",
  flask: "M9 3v6L4 20h16L15 9V3 M9 3h6",
  shield: "M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z",
  gear: "M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8z M19 12l2-1.5-1-2-2.3.8L16 8.4l.8-2.3-2-1L13.5 7l-2.5-.5L10 4H8L6.5 6.5 4 6l-1 2 2 1.5L4 12l-1 1.5 1 2 2.3-.8L7.5 16l-.8 2.3 2 1L10 17l2.5.5L14 20h2l1.5-2.5L20 18l1-2-2-1.5L20 12z",
  key: "M14 7a4 4 0 1 1-3.5 5.9L4 19v3h3l1-1v-2h2v-2h2l1.5-1.5A4 4 0 0 1 14 7z",
  bolt: "M13 2 4 14h7l-1 8 9-12h-7z",
  receipt: "M5 3v18l3-2 3 2 3-2 3 2 3-2V3z M9 8h6 M9 12h6 M9 16h4",
  alert: "M12 3 1 21h22z M12 10v5 M12 18h.01",
  user: "M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8z M4 21c0-4 4-7 8-7s8 3 8 7",
  search: "M11 19a8 8 0 1 1 0-16 8 8 0 0 1 0 16z M21 21l-4.3-4.3",
  plus: "M12 5v14 M5 12h14",
  fork: "M6 4v8 M6 16v4 M18 4v8 M6 16a6 6 0 0 0 12 0",
  sparkles: "M5 12l1.5-3 3-1.5-3-1.5L5 3 3.5 6 .5 7.5l3 1.5z M19 14l1.5 3 3 1.5-3 1.5L19 23l-1.5-3L14.5 18.5l3-1.5z",
  dna: "M5 4c0 8 14 8 14 16 M19 4c0 8-14 8-14 16 M5 4h14 M5 20h14 M7 8h10 M7 12h10 M7 16h10",
  globe: "M12 3a15 15 0 0 1 0 18 M12 3a15 15 0 0 0 0 18 M3 12h18 M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18z",
  audit: "M4 4h12l4 4v12H4z M16 4v4h4 M8 12h8 M8 16h6",
  check: "M5 12l5 5L20 7",
  x: "M6 6l12 12 M18 6L6 18",
  lock: "M5 11h14v10H5z M8 11V8a4 4 0 0 1 8 0v3",
  bell: "M6 18V11a6 6 0 1 1 12 0v7l2 2H4z M10 22h4",
  layers: "M12 2 2 8l10 6 10-6z M2 14l10 6 10-6 M2 11l10 6 10-6",
  filter: "M3 5h18l-7 8v6l-4 2v-8z",
  download: "M12 4v12 M6 12l6 6 6-6 M4 22h16",
  drag: "M9 5v14 M15 5v14"
};
const I = (k, s) => <Ic d={ICON[k]} s={s}/>;

// ---------- Brand / Sidebar / Topbar ----------
const Brand = () => (
  <div className="brand">
    <div className="brand-mark"/>
    <div className="brand-name">Persona<em>.</em></div>
  </div>
);

const NAV = [
  { sec: "Studio" },
  { id:"home", label:"Overview", icon:"home" },
  { id:"create", label:"Create persona", icon:"spark", pill:"⌘N" },
  { id:"library", label:"Library", icon:"library", pill:"152" },
  { id:"chat", label:"Chat runtime", icon:"chat" },
  { id:"lineage", label:"Lineage", icon:"fork" },
  { id:"ensemble", label:"Ensemble", icon:"dna", pill:"new" },
  { id:"compare", label:"Compare", icon:"layers" },
  { id:"market", label:"Marketplace", icon:"market" },
  { sec: "Quality" },
  { id:"runs", label:"Generation runs", icon:"bolt" },
  { id:"audits", label:"Audits & Tests", icon:"flask" },
  { id:"moderation", label:"Moderation", icon:"shield", pill:"4" },
  { sec: "Workspace" },
  { id:"members", label:"Members & RBAC", icon:"user" },
  { id:"keys", label:"API keys", icon:"key" },
  { id:"webhooks", label:"Webhooks", icon:"bolt" },
  { id:"billing", label:"Billing & usage", icon:"receipt" },
  { id:"audit", label:"Audit log", icon:"audit" },
  { id:"config", label:"Configuration", icon:"gear", pill:"1.8k" },
  { sec: "Developer" },
  { id:"docs", label:"API reference", icon:"globe", pill:"v1" },
];

const Sidebar = ({ route, setRoute }) => (
  <aside className="sidebar">
    <Brand/>
    <div className="workspace-switch" onClick={()=>setRoute("workspaces")}>
      <div className="ws-avatar">A</div>
      <div className="ws-meta">
        <div className="ws-org">Acme Studios · Pro</div>
        <div className="ws-name">Studio · Personas</div>
      </div>
      <div className="ws-chev">⌄</div>
    </div>
    <nav className="nav">
      {NAV.map((n,i) => n.sec ? (
        <div key={"s"+i} className="nav-section">{n.sec}</div>
      ) : (
        <div key={n.id} className={"nav-item " + (route===n.id?"active":"")} onClick={()=>setRoute(n.id)}>
          {I(n.icon)}
          <span>{n.label}</span>
          {n.pill && <span className="pill">{n.pill}</span>}
        </div>
      ))}
    </nav>
    <div className="sidebar-foot">
      <div className="user-avatar">ZÜ</div>
      <div className="user-meta">
        <div className="user-name">Zeki Ünal</div>
        <div className="user-email">zeki@persona.dev</div>
      </div>
      {I("bell",16)}
    </div>
  </aside>
);

const Topbar = ({ crumbs }) => (
  <div className="topbar">
    <div className="crumbs">
      {crumbs.map((c,i)=>(
        <React.Fragment key={i}>
          {i>0 && <span className="sep">/</span>}
          <span className={i===crumbs.length-1?"here":""}>{c}</span>
        </React.Fragment>
      ))}
    </div>
    <div className="spacer"/>
    <div className="search">
      {I("search",14)}
      <input placeholder="Search personas, runs, configs…" />
      <span className="kbd">⌘K</span>
    </div>
    <button className="icon-btn" title="Notifications">{I("bell")}</button>
    <button className="icon-btn" title="Help">?</button>
  </div>
);

// ---------- Mini chart sparkline ----------
const Spark = ({ data, w=120, h=32, color="var(--ember)" }) => {
  const max = Math.max(...data), min = Math.min(...data);
  const pts = data.map((v,i)=>`${(i/(data.length-1))*w},${h - ((v-min)/(max-min||1))*h}`).join(" ");
  return <svg width={w} height={h}><polyline points={pts} fill="none" stroke={color} strokeWidth="1.5"/></svg>;
};

const BarChart = ({ data, h=120, color="var(--ember)" }) => {
  const max = Math.max(...data.map(d=>d.personas||d.cost||d.val));
  return (
    <div style={{display:"flex",alignItems:"flex-end",gap:3,height:h}}>
      {data.map((d,i)=>{
        const v = d.personas||d.cost||d.val;
        return <div key={i} style={{flex:1,height:`${(v/max)*100}%`,background:color,opacity: i===data.length-1?1:0.55, borderRadius:2,minHeight:2}}/>;
      })}
    </div>
  );
};

// ---------- Pages ----------
const PortraitPlaceholder = ({ cls="portrait-strip" }) => (
  <div className={"persona-portrait "+cls}>
    <span className="placeholder-ph">[ portrait ]</span>
  </div>
);

const PersonaCard = ({ p, onClick }) => (
  <div className="card persona-card" onClick={onClick}>
    <PortraitPlaceholder cls={p.portrait}/>
    <div className="persona-meta">
      <div className="persona-name">{p.name}</div>
      <div className="persona-blurb">{p.tagline}</div>
      <div className="persona-tags">
        <span className="tag ember"><span className="dot"/>{p.archetype}</span>
        <span className="tag"><span className="dot"/>{p.lang}</span>
        {p.visibility==="public" && <span className="tag moss"><span className="dot"/>public</span>}
        {p.visibility==="workspace" && <span className="tag sky"><span className="dot"/>workspace</span>}
        {p.visibility==="private" && <span className="tag"><span className="dot"/>private</span>}
      </div>
    </div>
  </div>
);

// Overview
const PageOverview = ({ go }) => (
  <div className="page">
    <div className="page-head">
      <div className="eyebrow" style={{marginBottom:8}}>Acme Studios — Studio workspace</div>
      <h1 className="page-title">Good evening, Zeki. <span className="muted">Your characters are rehearsing.</span></h1>
      <div className="page-sub">152 personas in this workspace · 4 generation runs in last hour · all moderation checks passing.</div>
    </div>

    <div className="grid grid-4" style={{marginBottom:18}}>
      <div className="card stat"><div className="lbl">Personas</div><div className="val">152</div><div className="delta">+12 this week</div></div>
      <div className="card stat"><div className="lbl">Runs (24h)</div><div className="val">218</div><div className="delta">+18%</div></div>
      <div className="card stat"><div className="lbl">Median cost / persona</div><div className="val">$0.81</div><div className="delta">−4%</div></div>
      <div className="card stat"><div className="lbl">Coherence (avg)</div><div className="val">4.42<span style={{color:"var(--ink-3)",fontSize:14}}>/5</span></div><div className="delta">+0.08</div></div>
    </div>

    <div className="grid grid-2" style={{gap:18, marginBottom:22}}>
      <div className="card card-pad">
        <div className="row between" style={{marginBottom:14}}>
          <h3 className="section-title">Generation throughput · 28d</h3>
          <span className="tag"><span className="dot"/>personas / day</span>
        </div>
        <BarChart data={D.usageByDay} h={140} color="var(--ember)"/>
      </div>
      <div className="card card-pad">
        <div className="row between" style={{marginBottom:14}}>
          <h3 className="section-title">Cost · 28d</h3>
          <span className="tag gold"><span className="dot"/>$ USD</span>
        </div>
        <BarChart data={D.usageByDay.map(d=>({val:d.cost}))} h={140} color="var(--gold)"/>
      </div>
    </div>

    <div className="row between" style={{marginBottom:12}}>
      <h3 className="section-title">Recently created</h3>
      <button className="btn btn-sm" onClick={()=>go("library")}>View library →</button>
    </div>
    <div className="grid grid-4">
      {D.personas.slice(0,4).map(p => <PersonaCard key={p.id} p={p} onClick={()=>go("detail",p)}/>)}
    </div>

    <div style={{marginTop:28}} className="grid grid-2">
      <div className="card card-pad">
        <h3 className="section-title" style={{marginBottom:10}}>Recent runs</h3>
        <table className="tbl">
          <thead><tr><th>Run</th><th>Persona</th><th>Status</th><th>Cost</th><th>Latency</th></tr></thead>
          <tbody>
          {D.recentRuns.map(r=>(
            <tr key={r.id}>
              <td className="mono">{r.id}</td>
              <td>{r.persona}</td>
              <td>{r.status==="completed" ? <span className="tag moss"><span className="dot"/>completed</span> : <span className="tag ruby"><span className="dot"/>{r.err||"failed"}</span>}</td>
              <td className="mono">${r.cost.toFixed(2)}</td>
              <td className="mono">{r.lat}s</td>
            </tr>
          ))}
          </tbody>
        </table>
      </div>
      <div className="card card-pad">
        <h3 className="section-title" style={{marginBottom:10}}>Today, in your workspace</h3>
        <div className="col" style={{gap:14}}>
          <div className="row" style={{gap:12,alignItems:"flex-start"}}>
            <div className="tag ember"><span className="dot"/>moderation</div>
            <div><div style={{fontSize:13.5}}>4 items in review queue.</div><div className="muted" style={{fontSize:12}}>1 critical (minor reference). SLA: 44h remaining.</div></div>
          </div>
          <div className="row" style={{gap:12,alignItems:"flex-start"}}>
            <div className="tag gold"><span className="dot"/>drift</div>
            <div><div style={{fontSize:13.5}}>"Mert Kavaklı" voice drift detected at 0.34.</div><div className="muted" style={{fontSize:12}}>Last 6 conversations · threshold 0.32.</div></div>
          </div>
          <div className="row" style={{gap:12,alignItems:"flex-start"}}>
            <div className="tag moss"><span className="dot"/>tests</div>
            <div><div style={{fontSize:13.5}}>Provocation suite: 21 / 24 personas passing.</div><div className="muted" style={{fontSize:12}}>3 failed jailbreak resistance — review needed.</div></div>
          </div>
          <div className="row" style={{gap:12,alignItems:"flex-start"}}>
            <div className="tag sky"><span className="dot"/>billing</div>
            <div><div style={{fontSize:13.5}}>Token usage at 62% of monthly quota.</div><div className="muted" style={{fontSize:12}}>$842 of $1,350. Resets in 11 days.</div></div>
          </div>
        </div>
      </div>
    </div>
  </div>
);

window.PageOverview = PageOverview;
window.Sidebar = Sidebar;
window.Topbar = Topbar;
window.PersonaCard = PersonaCard;
window.PortraitPlaceholder = PortraitPlaceholder;
window.I = I; window.Ic = Ic;
const LineChart = ({ data, h=80, color="var(--gold)", threshold=null, w=300 }) => {
  const vals = data.map(d => d.val ?? d);
  const max = Math.max(...vals, threshold||0) * 1.1;
  const min = 0;
  const pts = vals.map((v,i)=>{
    const x = (i/(vals.length-1))*w;
    const y = h - ((v-min)/(max-min||1))*h;
    return [x,y];
  });
  const path = pts.map((p,i)=>(i===0?"M":"L")+p[0].toFixed(1)+","+p[1].toFixed(1)).join(" ");
  const fillPath = path + ` L ${w},${h} L 0,${h} Z`;
  const thY = threshold!=null ? h - ((threshold-min)/(max-min||1))*h : null;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{width:"100%",height:h,display:"block"}}>
      <path d={fillPath} fill={color} opacity="0.12"/>
      <path d={path} stroke={color} strokeWidth="1.5" fill="none"/>
      {thY!=null && <line x1="0" y1={thY} x2={w} y2={thY} stroke="var(--ruby)" strokeDasharray="3 3" strokeWidth="1" opacity="0.7"/>}
      {pts.slice(-1).map((p,i)=><circle key={i} cx={p[0]} cy={p[1]} r="2.5" fill={color}/>)}
    </svg>
  );
};

window.LineChart = LineChart;
window.BarChart = BarChart; window.Spark = Spark;
