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

// ---------- Configuration tree (the heart of the system) ----------
const PageConfig = () => {
  const [scope, setScope] = useState("org");
  const [search, setSearch] = useState("");
  const groups = useMemo(()=>{
    const items = D5.configItems.filter(c => !search || c.key.includes(search.toLowerCase()));
    const g = {};
    items.forEach(it => {
      const root = it.key.split(".")[0];
      (g[root] = g[root] || []).push(it);
    });
    return g;
  }, [search]);

  return (
    <div className="page">
      <div className="page-head">
        <div className="eyebrow">8 katman çözümleyici · 1,847 config item</div>
        <h1 className="page-title">Configuration</h1>
        <div className="page-sub">Sistemde sabit kodlanmış hiçbir davranış yok. Her sayı, eşik, sağlayıcı, prompt — burada. Üst scope alt scope'u kilitleyebilir.</div>
      </div>

      <div className="card card-pad" style={{marginBottom:18,padding:"14px 18px"}}>
        <div className="eyebrow" style={{marginBottom:8}}>Resolution chain — for current request</div>
        <div className="row" style={{gap:0,flexWrap:"wrap"}}>
          {[
            ["System","sys",false],["Env","prod",false],["Plan","Pro",false],["Org","Acme","active"],["Workspace","Studio",false],["User","zeki",false],["API key","—",false],["Request","—",false],
          ].map(([lbl,val,act],i)=>(
            <React.Fragment key={i}>
              {i>0 && <div style={{flex:"0 0 16px",height:1,background:"var(--line-2)",alignSelf:"center"}}/>}
              <div style={{padding:"6px 10px",borderRadius:6,border:"1px solid "+(act?"var(--ember)":"var(--line)"),background:act?"rgba(232,118,58,0.1)":"var(--bg-2)",color:act?"var(--ember)":"var(--ink-2)"}}>
                <div style={{fontSize:10,fontFamily:"var(--mono)",letterSpacing:1,color:"var(--ink-4)"}}>{i+1}</div>
                <div style={{fontSize:12.5}}>{lbl}</div>
                <div style={{fontSize:10.5,color:"var(--ink-3)",fontFamily:"var(--mono)"}}>{val}</div>
              </div>
            </React.Fragment>
          ))}
        </div>
      </div>

      <div className="row between" style={{marginBottom:14, gap:14}}>
        <div className="search" style={{flex:1,maxWidth:420}}>
          {I("search",14)}
          <input value={search} onChange={e=>setSearch(e.target.value)} placeholder="engine.pipeline.audit.* …"/>
        </div>
        <div className="pill-tabs">
          {["system","env","plan","org","workspace","user"].map(s =>
            <span key={s} className={"pt "+(scope===s?"on":"")} onClick={()=>setScope(s)}>{s}</span>
          )}
        </div>
        <button className="btn">{I("download",14)} export YAML</button>
      </div>

      <div className="grid" style={{gridTemplateColumns:"1fr 320px", gap:18}}>
        <div className="card" style={{padding:0}}>
          <div className="cfg-row" style={{background:"var(--bg-2)",fontFamily:"var(--mono)",fontSize:10.5,letterSpacing:".06em",textTransform:"uppercase",color:"var(--ink-3)"}}>
            <div>Key</div><div>Value</div><div>Source</div><div>Tier</div><div>Lock</div>
          </div>
          {Object.entries(groups).map(([root, items])=>(
            <React.Fragment key={root}>
              <div style={{padding:"10px 14px",fontFamily:"var(--serif)",fontSize:13,background:"var(--bg-1)",borderBottom:"1px solid var(--line)",color:"var(--ink-3)"}}>{root}</div>
              {items.map(c=>(
                <div key={c.key} className="cfg-row">
                  <div className="key">{c.key}</div>
                  <div className="mono" style={{fontSize:12,color:"var(--ink)"}}>{c.val}</div>
                  <div className="src">{c.src}</div>
                  <div><span className={"cfg-tier "+(c.tier==="team"?"team":c.tier==="pro"?"team":c.tier==="ent"?"ent":"")}>{c.tier}</span></div>
                  <div className={"lock "+(c.locked?"on":"")}>{c.locked? "🔒 locked" : "—"}</div>
                </div>
              ))}
            </React.Fragment>
          ))}
        </div>

        <aside style={{position:"sticky",top:74,alignSelf:"flex-start"}}>
          <div className="card card-pad" style={{marginBottom:14}}>
            <div className="eyebrow" style={{marginBottom:8}}>Selected · engine.pipeline.audit.enabled</div>
            <div className="kv" style={{gridTemplateColumns:"110px 1fr"}}>
              <div className="k">Type</div><div className="v mono" style={{fontSize:12}}>boolean</div>
              <div className="k">Resolved</div><div className="v mono">true</div>
              <div className="k">Source</div><div className="v"><span className="tag ember"><span className="dot"/>plan</span></div>
              <div className="k">Default</div><div className="v mono">true</div>
              <div className="k">Override?</div><div className="v">yes — by org admin</div>
              <div className="k">Last changed</div><div className="v">can@acme.co · 22m ago</div>
              <div className="k">Tier</div><div className="v">free+</div>
              <div className="k">Feature flag</div><div className="v">enabled · 100%</div>
            </div>
            <div className="divider"/>
            <div className="row" style={{gap:8}}>
              <button className="btn btn-sm">Override here</button>
              <button className="btn btn-sm">Lock for children</button>
              <button className="btn btn-sm danger">Reset</button>
            </div>
          </div>
          <div className="notice"><strong>"What if" simulator.</strong> Try a value to preview which downstream items this would change before saving.</div>
        </aside>
      </div>
    </div>
  );
};

// ---------- Members / RBAC / SSO ----------
const PageMembers = () => {
  const [tab, setTab] = useState("members");
  return (
    <div className="page">
      <div className="page-head row between">
        <div>
          <div className="eyebrow">Acme Studios · Pro</div>
          <h1 className="page-title">Members & access</h1>
        </div>
        <button className="btn primary">{I("plus",14)} Invite member</button>
      </div>
      <div className="tabs">
        {[["members","Members"],["roles","Roles & permissions"],["sso","SSO & SCIM"],["sessions","Sessions"]].map(([k,l])=>
          <div key={k} className={"tab "+(tab===k?"active":"")} onClick={()=>setTab(k)}>{l}</div>
        )}
      </div>

      {tab==="members" && (
        <div className="card" style={{padding:0}}>
          <table className="tbl">
            <thead><tr><th>Name</th><th>Email</th><th>Role</th><th>Workspace</th><th>MFA</th><th>Last active</th><th></th></tr></thead>
            <tbody>
              {D5.members.map(m=>(
                <tr key={m.email}>
                  <td><div className="row" style={{gap:10}}><div className="user-avatar" style={{width:26,height:26,fontSize:11,background:m.role==="owner"?"var(--ember)":m.role==="admin"?"var(--plum)":m.role==="editor"?"var(--moss)":"var(--ink-4)"}}>{m.name.split(" ").map(s=>s[0]).join("").slice(0,2)}</div><span style={{fontFamily:"var(--serif)"}}>{m.name}</span></div></td>
                  <td className="mono">{m.email}</td>
                  <td><span className={"tag "+(m.role==="owner"?"ember":m.role==="admin"?"plum":m.role==="editor"?"moss":m.role==="auditor"?"gold":"")}><span className="dot"/>{m.role}</span></td>
                  <td>{m.workspace}</td>
                  <td>{m.mfa? <span className="tag moss"><span className="dot"/>on</span> : <span className="tag ruby"><span className="dot"/>off</span>}</td>
                  <td className="muted mono">{m.last}</td>
                  <td><button className="btn btn-sm">⋯</button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {tab==="roles" && (
        <div className="card" style={{padding:0,overflowX:"auto"}}>
          <table className="tbl">
            <thead><tr><th>Capability</th><th>Owner</th><th>Admin</th><th>Editor</th><th>Viewer</th><th>API-only</th><th>Billing</th><th>Auditor</th></tr></thead>
            <tbody>
              {[
                ["personas.read","✓","✓","✓","✓","✓","—","✓"],
                ["personas.create","✓","✓","✓","—","✓","—","—"],
                ["personas.publish","✓","✓","—","—","—","—","—"],
                ["personas.delete","✓","✓","—","—","—","—","—"],
                ["chat.run","✓","✓","✓","✓","✓","—","—"],
                ["config.read","✓","✓","✓","✓","—","—","✓"],
                ["config.write","✓","✓","—","—","—","—","—"],
                ["api_keys.manage","✓","✓","—","—","—","—","—"],
                ["billing.manage","✓","—","—","—","—","✓","—"],
                ["audit.read","✓","✓","—","—","—","—","✓"],
                ["members.invite","✓","✓","—","—","—","—","—"],
                ["sso.configure","✓","—","—","—","—","—","—"],
              ].map((r,i)=>(
                <tr key={i}>
                  <td className="mono">{r[0]}</td>
                  {r.slice(1).map((v,j)=>(
                    <td key={j} style={{textAlign:"center",color:v==="✓"?"var(--moss)":"var(--ink-4)",fontFamily:"var(--mono)"}}>{v}</td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {tab==="sso" && (
        <div className="grid grid-2" style={{gap:18}}>
          <div className="card card-pad">
            <h3 className="section-title" style={{marginBottom:12}}>SAML 2.0 SSO</h3>
            <div className="kv">
              <div className="k">Status</div><div className="v"><span className="tag moss"><span className="dot"/>configured</span></div>
              <div className="k">IdP</div><div className="v">Okta · acme.okta.com</div>
              <div className="k">ACS URL</div><div className="v mono" style={{fontSize:11.5}}>https://api.persona.dev/auth/saml/acs/org_acme</div>
              <div className="k">Entity ID</div><div className="v mono" style={{fontSize:11.5}}>persona://org/acme</div>
              <div className="k">Enforcement</div><div className="v">required for non-owner roles</div>
            </div>
            <div className="divider"/>
            <div className="row" style={{gap:8}}>
              <button className="btn">Download metadata XML</button>
              <button className="btn">Test SSO</button>
              <button className="btn danger">Disable</button>
            </div>
          </div>
          <div className="card card-pad">
            <h3 className="section-title" style={{marginBottom:12}}>SCIM provisioning</h3>
            <div className="kv">
              <div className="k">SCIM endpoint</div><div className="v mono" style={{fontSize:11.5}}>https://api.persona.dev/scim/v2/org_acme</div>
              <div className="k">Bearer token</div><div className="v mono">scim_⟨rotated 12d ago⟩</div>
              <div className="k">Last sync</div><div className="v">3m ago · 14 users, 0 deprovisioned</div>
              <div className="k">Auto-deprovision</div><div className="v">on (revoke API keys)</div>
            </div>
            <div className="divider"/>
            <div className="notice"><strong>Enterprise feature.</strong> Group-to-role mapping configured in the Okta app.</div>
          </div>
          <div className="card card-pad">
            <h3 className="section-title" style={{marginBottom:12}}>IP allowlist</h3>
            <div className="col" style={{gap:8,fontFamily:"var(--mono)",fontSize:12}}>
              <div className="row between" style={{padding:"8px 0",borderBottom:"1px solid var(--line)"}}><span>185.21.0.0/16</span><span className="muted">acme office</span></div>
              <div className="row between" style={{padding:"8px 0",borderBottom:"1px solid var(--line)"}}><span>2a05:d014::/32</span><span className="muted">aws prod vpc</span></div>
              <div className="row between" style={{padding:"8px 0"}}><span>94.55.0.0/16</span><span className="muted">zeki home (allow)</span></div>
            </div>
            <button className="btn btn-sm" style={{marginTop:10}}>{I("plus",12)} Add CIDR</button>
          </div>
          <div className="card card-pad">
            <h3 className="section-title" style={{marginBottom:12}}>Session policy</h3>
            <div className="col" style={{gap:10}}>
              <div className="row between"><span style={{fontSize:13}}>Idle timeout</span><span className="mono">60 min</span></div>
              <div className="row between"><span style={{fontSize:13}}>Absolute max</span><span className="mono">8 h</span></div>
              <div className="row between"><span style={{fontSize:13}}>Concurrent sessions</span><span className="mono">3 max</span></div>
              <div className="row between"><span style={{fontSize:13}}>Require MFA</span><div className="toggle on"/></div>
              <div className="row between"><span style={{fontSize:13}}>Step-up for billing</span><div className="toggle on"/></div>
            </div>
          </div>
        </div>
      )}

      {tab==="sessions" && (
        <div className="card" style={{padding:0}}>
          <table className="tbl">
            <thead><tr><th>User</th><th>Device</th><th>IP</th><th>Started</th><th>Idle</th><th></th></tr></thead>
            <tbody>
              {[
                ["zeki@persona.dev","macOS · Chrome 142","94.55.x.x","3h ago","2m"],
                ["can@acme.co","macOS · Safari 19","185.21.x.x","5h ago","18m"],
                ["selin@acme.co","Windows · Edge","185.21.x.x","yesterday","stale"],
              ].map((r,i)=>(
                <tr key={i}>
                  <td className="mono">{r[0]}</td><td>{r[1]}</td><td className="mono">{r[2]}</td><td className="muted">{r[3]}</td><td className="muted">{r[4]}</td>
                  <td><button className="btn btn-sm danger">Revoke</button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

// ---------- API Keys ----------
const PageKeys = () => (
  <div className="page">
    <div className="page-head row between">
      <div><div className="eyebrow">Programmatic access</div><h1 className="page-title">API keys</h1></div>
      <button className="btn primary">{I("plus",14)} Create key</button>
    </div>
    <div className="card" style={{padding:0,marginBottom:18}}>
      <table className="tbl">
        <thead><tr><th>Name</th><th>Prefix</th><th>Scopes</th><th>Rate limit</th><th>Last used</th><th></th></tr></thead>
        <tbody>
          {D5.apiKeys.map(k=>(
            <tr key={k.prefix}>
              <td><strong>{k.name}</strong></td>
              <td className="mono">{k.prefix}</td>
              <td>{k.scopes.map(s=><span key={s} className="tag" style={{marginRight:4}}><span className="dot"/>{s}</span>)}</td>
              <td className="mono">{k.rate}</td>
              <td className="muted">{k.last}</td>
              <td><button className="btn btn-sm">Rotate</button> <button className="btn btn-sm danger">Revoke</button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>

    <div className="grid grid-2" style={{gap:18}}>
      <div className="card card-pad">
        <h3 className="section-title" style={{marginBottom:10}}>Quick start</h3>
        <div className="code">{`curl https://api.persona.dev/v1/personas \\
  -H "Authorization: Bearer sk_live_…" \\
  -H "Idempotency-Key: $(uuidgen)" \\
  -d '{
    "brief": "35, lonely bookseller in Istanbul",
    "language": "tr",
    "audit": true
  }'`}</div>
      </div>
      <div className="card card-pad">
        <h3 className="section-title" style={{marginBottom:10}}>OpenAI-compatible shim</h3>
        <div className="code">{`POST /v1/chat/completions
{
  "model": "persona://p_mert",
  "messages": [
    {"role":"user","content":"Bugün dükkânda ne var?"}
  ],
  "stream": true
}`}</div>
      </div>
    </div>
  </div>
);

// ---------- Webhooks ----------
const PageWebhooks = () => (
  <div className="page">
    <div className="page-head row between">
      <div><div className="eyebrow">Outbound events</div><h1 className="page-title">Webhooks</h1></div>
      <button className="btn primary">{I("plus",14)} Add endpoint</button>
    </div>
    <div className="card" style={{padding:0,marginBottom:18}}>
      <table className="tbl">
        <thead><tr><th>Endpoint</th><th>Events</th><th>Status</th><th>Success rate (24h)</th><th>Avg latency</th><th></th></tr></thead>
        <tbody>
          {[
            ["https://api.acme.co/persona/hooks", "persona.created · persona.updated · run.completed", "active", "99.4%", "182 ms"],
            ["https://hooks.slack.com/services/…", "moderation.flagged · drift.detected", "active", "100%", "94 ms"],
            ["https://eu.acme.co/persona/hooks",  "all", "paused", "—", "—"],
          ].map((r,i)=>(
            <tr key={i}>
              <td className="mono">{r[0]}</td><td style={{fontSize:12}}>{r[1]}</td>
              <td><span className={"tag "+(r[2]==="active"?"moss":"gold")}><span className="dot"/>{r[2]}</span></td>
              <td className="mono">{r[3]}</td><td className="mono">{r[4]}</td>
              <td><button className="btn btn-sm">Test</button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
    <div className="card card-pad">
      <h3 className="section-title" style={{marginBottom:10}}>Recent deliveries</h3>
      <table className="tbl">
        <thead><tr><th>Event</th><th>Endpoint</th><th>Status</th><th>Attempts</th><th>When</th></tr></thead>
        <tbody>
          {[
            ["persona.created","acme.co/hooks","200","1","2m ago"],
            ["run.completed","acme.co/hooks","200","1","2m ago"],
            ["moderation.flagged","slack","200","1","1h ago"],
            ["drift.detected","acme.co/hooks","500 → retried","3","2h ago"],
            ["persona.updated","eu.acme.co","timeout · dlq","5","3h ago"],
          ].map((r,i)=>(
            <tr key={i}>
              <td className="mono">{r[0]}</td><td className="mono">{r[1]}</td>
              <td>{r[2].includes("dlq")?<span className="tag ruby"><span className="dot"/>{r[2]}</span>:r[2].includes("retried")?<span className="tag gold"><span className="dot"/>{r[2]}</span>:<span className="tag moss"><span className="dot"/>{r[2]}</span>}</td>
              <td className="mono">{r[3]}</td><td className="muted">{r[4]}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </div>
);

window.PageConfig = PageConfig;
window.PageMembers = PageMembers;
window.PageKeys = PageKeys;
window.PageWebhooks = PageWebhooks;
