/* ===========================================================
   indie.chat Settings: the ONE place every option lives.

   It used to be three. This page mixed personal and admin sections behind a
   single "Save changes" button that silently governed two of them (MCP saved
   on click, Branding had its own button, a pasted Skill was lost if you left
   without pressing it). admin.html held Users, a "Tools" tab that looked
   workspace-wide but only ever changed the admin's own browser, and an "API
   keys" list nothing read. Connectors, per-agent wiki access and password
   resets had server APIs and no screen at all.

   The rules now, so it stays intuitive as it grows:
   * one page, a section per subject, a left nav grouped into You / Workspace;
   * every card says WHO it affects (your account, this browser, this device,
     everyone), the one thing that was never visible before;
   * switches, choices and lists save the moment you change them; only a FORM
     (a password, a new endpoint, branding that reaches everyone) has a button,
     and that button belongs to its own card, never to the page.
   admin.html redirects here (#users), so old links keep working.
   =========================================================== */
const { useState, useEffect, useRef } = React;
/* the Connections dialog, shared with the app (connections.jsx) */
const { ConnectionsModal } = window.IndieConn;
const L = window.IndieLib;
const t = (k, v) => L.t(k, v);
const tb = (k, v) => L.tb(k, v);

L.seedAdmin();

/* ---------- icons (stroke, same family as the app) ---------- */
const Ic = ({ d }) => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">{d}</svg>
);
const ICONS = {
  account:      <Ic d={<><circle cx="12" cy="8" r="3.6" /><path d="M5 20c1.2-3.6 4-5.4 7-5.4s5.8 1.8 7 5.4" /></>} />,
  preferences:  <Ic d={<><path d="M4 7h10M18 7h2M4 17h4M12 17h8" /><circle cx="16" cy="7" r="2" /><circle cx="10" cy="17" r="2" /></>} />,
  models:       <Ic d={<><rect x="6" y="6" width="12" height="12" rx="2" /><path d="M9 2v4M15 2v4M9 18v4M15 18v4M2 9h4M2 15h4M18 9h4M18 15h4" /></>} />,
  tools:        <Ic d={<><path d="M14.5 6.5a4 4 0 0 0-5.3 5.2L4 17v3h3l5.3-5.2a4 4 0 0 0 5.2-5.3l-2.5 2.5-2.4-.4-.4-2.4z" /></>} />,
  integrations: <Ic d={<><path d="M9 7V3M15 7V3M7 7h10v4a5 5 0 0 1-10 0z" /><path d="M12 16v5" /></>} />,
  memory:       <Ic d={<><path d="M6 4h9l3 3v13H6z" /><path d="M9 10h6M9 14h6M9 18h3" /></>} />,
  "my-agents":  <Ic d={<><rect x="4" y="7" width="16" height="12" rx="3" /><path d="M12 3v4M9 12h.01M15 12h.01M9 16h6" /></>} />,
  users:        <Ic d={<><circle cx="9" cy="8" r="3.2" /><path d="M3 19c.9-3 3.2-4.6 6-4.6s5.1 1.6 6 4.6" /><path d="M16 5.2a3 3 0 0 1 0 5.6M18.5 14.8c1.3.7 2.1 2 2.5 4.2" /></>} />,
  "all-agents": <Ic d={<><rect x="3" y="9" width="12" height="10" rx="2.5" /><path d="M9 5v4M7 13h.01M11 13h.01" /><path d="M18 8.5h1.5A1.5 1.5 0 0 1 21 10v7a2 2 0 0 1-2 2h-1" /></>} />,
  branding:     <Ic d={<><circle cx="12" cy="12" r="9" /><circle cx="8.5" cy="10" r="1.2" /><circle cx="12" cy="7.5" r="1.2" /><circle cx="15.5" cy="10" r="1.2" /><path d="M12 21a2.5 2.5 0 0 1 0-5h1.5a2 2 0 0 0 0-4" /></>} />,
};

/* ---------- the sections, in nav order ---------- */
function sectionList(isAdmin) {
  const s = [
    { id: "account",      group: "you" },
    { id: "preferences",  group: "you" },
    { id: "models",       group: "you" },
    { id: "tools",        group: "you" },
    { id: "integrations", group: "you" },
    /* what your agents know about you between conversations (server.js, /api/memory) */
    { id: "memory",       group: "you" },
    /* each of your agents: its own instructions and (with the brain module)
       its wiki access; the separate Wiki section this replaced only had the latter */
    { id: "my-agents",    group: "you" },
  ];
  if (isAdmin) s.push({ id: "users", group: "ws" }, { id: "all-agents", group: "ws" }, { id: "branding", group: "ws" });
  return s;
}
const sectionLabel = id => t("settings.nav." + id);
/* applyBranding() sets the tab title to the bare brand name, so anything that
   applies branding puts the section back in front of it afterwards. */
const retitle = id => { document.title = sectionLabel(id) + " · " + t("nav.settings") + " · " + ((L.BRAND && L.BRAND.brandName) || "indie.chat"); };
/* admin.html redirects to #users; anything unknown lands on the first section. */
/* Sections that were renamed keep their old address. */
const HASH_ALIASES = { wiki: "my-agents", agents: "all-agents" };
const fromHash = list => {
  const raw = (location.hash || "").replace(/^#/, "");
  const h = HASH_ALIASES[raw] || raw;
  return list.some(s => s.id === h) ? h : list[0].id;
};

/* ---------- shared pieces ---------- */
/* WHO a setting affects. The single most useful fact about any option, and the
   one the old pages never said: the console's "Tools" tab looked like it set
   something for everybody and only ever reached the admin's own browser. */
const SCOPES = ["account", "browser", "device", "everyone"];
function Scope({ of }) {
  if (!SCOPES.includes(of)) return null;
  return <span className={"set-scope " + of} title={t("settings.scopeHint." + of)}>{t("settings.scope." + of)}</span>;
}

function Card({ title, desc, scope, saved, children, id }) {
  return (
    <section className="set-card" id={id}>
      <div className="set-card-head">
        <h2 className="set-title">{title}</h2>
        <span className={"set-saved" + (saved ? " on" : "")} aria-live="polite">{saved ? t("settings.savedNow") : ""}</span>
        <Scope of={scope} />
      </div>
      {desc && <p className="set-desc">{desc}</p>}
      {children}
    </section>
  );
}

/* A brief "Saved" beside the card title: the reassurance an autosaving page
   owes you, since there is no button to have pressed. */
function useSaved() {
  const [on, setOn] = useState(false);
  const timer = useRef(null);
  useEffect(() => () => clearTimeout(timer.current), []);
  const flash = () => { setOn(true); clearTimeout(timer.current); timer.current = setTimeout(() => setOn(false), 1800); };
  return [on, flash];
}

function Msg({ m }) {
  if (!m) return null;
  return <div className={"set-msg " + (m.kind || "")} role={m.kind === "bad" ? "alert" : "status"}>{m.text}</div>;
}

function SwitchRow({ on, onChange, name, desc, disabled, children }) {
  return (
    <div className={"set-sw-row" + (on ? "" : " off")}>
      <div className="set-sw-text">
        <div className="set-sw-name">{name}</div>
        {desc && <div className="set-sw-desc">{desc}</div>}
        {on && children}
      </div>
      <button className={"switch " + (on ? "on" : "")} role="switch" aria-checked={!!on} aria-label={name}
              disabled={disabled} onClick={() => onChange(!on)} />
    </div>
  );
}

/* Two-step delete in place, instead of the browser's confirm() box. */
function DeleteButton({ onConfirm, label }) {
  const [ask, setAsk] = useState(false);
  useEffect(() => { if (!ask) return; const id = setTimeout(() => setAsk(false), 4000); return () => clearTimeout(id); }, [ask]);
  return ask
    ? <button className="mini danger" onClick={() => { setAsk(false); onConfirm(); }}>{t("common.deleteYes")}</button>
    : <button className="mini" onClick={() => setAsk(true)}>{label || t("common.remove")}</button>;
}

const errText = (e, fb) => (e && e.message) || fb;
const initialsOf = n => String(n || "?").split(/\s+/).map(s => s[0]).slice(0, 2).join("").toUpperCase();

/* ========================================================
   YOU
   ======================================================== */
function AccountSection({ me }) {
  const [cur, setCur] = useState("");
  const [nx, setNx] = useState("");
  const [nx2, setNx2] = useState("");
  const [msg, setMsg] = useState(null);
  const [busy, setBusy] = useState(false);

  const change = async e => {
    e.preventDefault();
    if (nx.length < 6) return setMsg({ kind: "bad", text: t("settings.passwordShort") });
    if (nx !== nx2)    return setMsg({ kind: "bad", text: t("settings.passwordMismatch") });
    setBusy(true); setMsg(null);
    try {
      await L.AccountAPI.changePassword(cur, nx);
      setCur(""); setNx(""); setNx2("");
      setMsg({ kind: "ok", text: t("settings.passwordChanged") });
    } catch (err) { setMsg({ kind: "bad", text: errText(err, t("settings.passwordFailed")) }); }
    finally { setBusy(false); }
  };
  const signOut = async () => { try { await L.Auth.logout(); } catch {} location.href = "/indie.chat.html"; };
  const roleText = r => { const k = "role." + r; const v = t(k); return v === k ? r : v; };

  return (<>
    <Card title={t("settings.profileTitle")} scope="account">
      <div className="set-profile">
        <span className="set-avatar">{initialsOf(me.name)}</span>
        <div className="set-profile-id">
          <div className="set-profile-name">{me.name}</div>
          <div className="set-profile-email">{me.email}</div>
        </div>
        <span className="tag-chip gray"><span className="sq" />{roleText(me.role)}</span>
      </div>
    </Card>

    {me.authSource === "box" && me.hasPassword === false ? (
      <Card title={t("settings.boxSignInTitle")} desc={t("settings.boxSignInDesc")} scope="account" />
    ) : me.authSource === "control" && me.hasPassword === false ? (
      <Card title={t("settings.controlTitle", { name: me.via || "" })} desc={t("settings.controlDesc", { name: me.via || "" })} scope="account" />
    ) : (
    <Card title={t("settings.passwordTitle")} desc={t("settings.passwordDesc")} scope="account">
      <form onSubmit={change} className="set-form">
        {/* lets a password manager pair the new password with the account */}
        <input type="text" name="username" autoComplete="username" value={me.email || ""} readOnly hidden />
        <div className="field"><label htmlFor="pw-cur">{t("settings.currentPassword")}</label>
          <input id="pw-cur" type="password" autoComplete="current-password" value={cur} onChange={e => setCur(e.target.value)} /></div>
        <div className="set-2col">
          <div className="field"><label htmlFor="pw-new">{t("settings.newPassword")}</label>
            <input id="pw-new" type="password" autoComplete="new-password" value={nx} onChange={e => setNx(e.target.value)} /></div>
          <div className="field"><label htmlFor="pw-new2">{t("settings.confirmPassword")}</label>
            <input id="pw-new2" type="password" autoComplete="new-password" value={nx2} onChange={e => setNx2(e.target.value)} /></div>
        </div>
        <div className="set-row">
          <Msg m={msg} />
          <button className="btn primary" type="submit" disabled={busy || !cur || !nx || !nx2}>
            {busy ? t("common.pleaseWait") : t("settings.changePassword")}
          </button>
        </div>
      </form>
    </Card>
    )}

    {/* the welcome a new person gets (onboarding.jsx), once more: it shows when the app opens */}
    <Card title={t("settings.welcomeTitle")} desc={t("settings.welcomeDesc")}>
      <button className="btn" onClick={() => L.OnboardingAPI.update({ done: false }).then(() => { location.href = "/"; }).catch(() => {})}>{t("settings.welcomeAgain")}</button>
    </Card>
    {/* through the box with no sign-out page known, signing out here would
        last until the next click: the box signs people in and out */}
    {(me.authSource !== "box" || me.logoutUrl) && (
      <Card title={t("nav.signOut")} desc={t("settings.signOutDesc")}>
        <button className="btn" onClick={signOut}>{t("nav.signOut")}</button>
      </Card>
    )}
  </>);
}

/* Per browser as well (appearance.js): the same person often wants dark on a
   phone at night and light at a desk. The page restyles itself at once, and
   other open tabs follow through the storage event. */
function AppearanceCard() {
  const read = () => ({ choice: window.IndieTheme ? window.IndieTheme.choice() : "light",
                        theme:  window.IndieTheme ? window.IndieTheme.effective() : "light" });
  const [st, setSt] = useState(read);
  const [saved, flash] = useSaved();
  useEffect(() => {
    const on = () => setSt(read());
    window.addEventListener("indie:theme", on);
    return () => window.removeEventListener("indie:theme", on);
  }, []);
  const pick = c => { if (window.IndieTheme) { window.IndieTheme.set(c); flash(); } };
  return (
    <Card title={t("settings.appearance")} desc={t("settings.appearanceDesc")} scope="browser" saved={saved}>
      <div className="lang-row">
        {["light", "dark", "system"].map(c => (
          <button key={c} className={"lang-btn " + (st.choice === c ? "on" : "")} aria-pressed={st.choice === c}
                  onClick={() => pick(c)}>{t("settings.theme." + c)}</button>
        ))}
      </div>
      {st.choice === "system" && <div className="set-foot-note">{t("settings.themeNow." + st.theme)}</div>}
    </Card>
  );
}

function PreferencesSection() {
  const [push, setPush] = useState({ supported: false, permission: "default", subscribed: false });
  const [pushBusy, setPushBusy] = useState(false);
  const [msg, setMsg] = useState(null);
  const refreshPush = () => L.Push.status().then(setPush).catch(() => {});
  useEffect(() => { refreshPush(); }, []);
  const enablePush = async () => {
    setPushBusy(true); setMsg(null);
    try { await L.Push.enable(); await L.Push.test(); await refreshPush(); }
    catch (e) { setMsg({ kind: "bad", text: String((e && e.message) || e) }); }
    finally { setPushBusy(false); }
  };

  return (<>
    {/* Per browser, not per account: the language belongs to the person
        reading the screen, and one account is often used on several machines. */}
    <Card title={t("settings.language")} desc={t("settings.languageHelp")} scope="browser">
      <div className="lang-row">
        {L.langs().map(l => (
          <button key={l.code} className={"lang-btn " + (L.lang() === l.code ? "on" : "")}
                  onClick={() => L.setLang(l.code)}>{l.label}</button>
        ))}
      </div>
    </Card>

    <AppearanceCard />

    <Card title={t("settings.notifTitle")} desc={t("settings.notifDesc")} scope="device">
      {push.supported
        ? (push.subscribed && push.permission === "granted"
            ? <span className="push-on">● {t("push.on")}</span>
            : <button className="btn" onClick={enablePush} disabled={pushBusy}>{pushBusy ? t("push.enabling") : t("push.enable")}</button>)
        : <span className="set-desc">{t("push.unsupported")}</span>}
      <Msg m={msg} />
    </Card>
  </>);
}

function ModelsSection() {
  const firstProvider = () => (L.providersList()[0] || {}).name;
  const [provider, setProv] = useState(() => L.getProvider() || firstProvider());
  const [model, setModelS] = useState(() => (L.load() || {}).model || L.defaultModelFor(provider));
  const [models, setModels] = useState(() => L.modelsFor(provider));
  const [providers, setProviders] = useState(() => L.providersList());
  const [saved, flash] = useSaved();
  const [connV, setConnV] = useState(0);   /* a new own endpoint is a new list under the same name */

  /* The provider's own list, as the chat toolbar asks for it: the built-in
     catalog is only the instant answer. Judged the same way too: a saved pick
     the provider does not serve gives way to one it does. */
  useEffect(() => {
    let gone = false;
    setModels(L.modelsFor(provider));
    L.loadModels(provider).then(list => {
      if (gone || !list || !list.length) return;
      setModels(list);
      if (!list.some(x => x.id === (L.load() || {}).model)) {
        const d = L.defaultModelFor(provider);
        writeModel(list.some(x => x.id === d) ? d : list[0].id);
      }
    }).catch(() => {});
    return () => { gone = true; };
  }, [provider, connV]);

  /* Writes the SAME two values the chat toolbar reads, so this is not a second
     default that can disagree with the first: change it here or there. */
  const writeModel = m => { setModelS(m); const ui = L.load() || {}; L.save({ ...ui, model: m }); };
  const pickProvider = name => { L.setProvider(name); setProv(name); writeModel(L.defaultModelFor(name)); flash(); };
  const pickModel = m => { writeModel(m); flash(); };
  const provLabel = p => p.label || L.providerLabel(p.name) || p.name;
  const cur = models.find(m => m.id === model);

  /* ---- your own endpoint ---- */
  const conn = L.getConn();
  const [base, setBase] = useState(conn.base || "");
  const [key, setKey] = useState(conn.key || "");
  const [emsg, setEmsg] = useState(null);
  const [testing, setTesting] = useState(false);
  const hasCustom = providers.some(p => p.name === "custom");

  /* The key is optional: a local Ollama or vLLM asks for none. */
  const saveEndpoint = () => {
    const b = base.trim().replace(/\/+$/, ""), k = key.trim();
    if (!b) { setEmsg({ kind: "bad", text: t("settings.endpointNeedsUrl") }); return false; }
    /* The base of a built-in provider is not "your own": select that provider
       rather than shadowing it with a copy under another name. */
    const match = (L.ENDPOINTS || []).find(e => (e.base || "").replace(/\/+$/, "") === b);
    if (match) { L.setConn({}); pickProvider(match.name); setProviders(L.providersList());
                 setEmsg({ kind: "ok", text: t("settings.endpointIsBuiltin", { name: L.providerLabel(match.name) }) }); return true; }
    L.setConn(k ? { base: b, key: k } : { base: b });
    setProviders(L.providersList());
    pickProvider("custom");
    setConnV(v => v + 1);
    setEmsg({ kind: "ok", text: t("settings.endpointSaved") });
    return true;
  };
  const removeEndpoint = () => {
    L.setConn({});
    setBase(""); setKey("");
    setProviders(L.providersList());
    if (provider === "custom") pickProvider(firstProvider());
    setEmsg({ kind: "ok", text: t("settings.endpointRemoved") });
  };
  const test = async () => {
    if (!saveEndpoint()) return;
    setTesting(true); setEmsg({ kind: "run", text: t("settings.testing") });
    /* Ask what it serves first: pinging a model it does not have fails the
       test for the wrong reason. */
    const list = await L.loadModels(L.getProvider());
    let m = (L.load() || {}).model || model;
    if (list && list.length && !list.some(x => x.id === m)) { m = list[0].id; writeModel(m); setModels(list); }
    const r = await L.ping(m);
    setTesting(false);
    let host = ""; try { host = new URL(base.trim()).hostname; } catch {}
    if (r.ok)          setEmsg({ kind: "ok",  text: t("settings.connected") + " · " + (L.providerLabel(r.endpoint) || "live") });
    else if (r.status === 403 && /allowlist/i.test(r.body || ""))
                       setEmsg({ kind: "bad", text: t("settings.testNotAllowed", { host }) });
    else if (r.status) setEmsg({ kind: "bad", text: t("settings.testHttp", { status: r.status }) });
    else               setEmsg({ kind: "bad", text: t("settings.unreachable") });
  };

  return (<>
    <Card title={t("settings.defaultModelTitle")} desc={t("settings.defaultModelDesc")} scope="browser" saved={saved}>
      <div className="set-2col">
        <div className="field"><label htmlFor="def-prov">{t("settings.provider")}</label>
          <select id="def-prov" value={provider} onChange={e => pickProvider(e.target.value)}>
            {providers.map(p => <option key={p.name} value={p.name}>{provLabel(p)}</option>)}
          </select></div>
        <div className="field"><label htmlFor="def-model">{t("settings.model")}</label>
          <select id="def-model" value={model} onChange={e => pickModel(e.target.value)}>
            {!cur && model && <option value={model}>{model}</option>}
            {models.map(m => <option key={m.id} value={m.id}>{m.label || m.id}</option>)}
          </select>
          {cur && cur.desc && <div className="help">{cur.desc}</div>}</div>
      </div>
    </Card>

    <Card title={t("settings.ownEndpointTitle")} desc={t("settings.ownEndpointDesc")} scope="browser">
      <div className="field"><label htmlFor="own-base">{t("settings.apiBase")}</label>
        <input id="own-base" value={base} onChange={e => setBase(e.target.value)} placeholder="https://your-host" spellCheck="false" /></div>
      <div className="field"><label htmlFor="own-key">{t("settings.apiKey")}</label>
        <input id="own-key" value={key} onChange={e => setKey(e.target.value)} type="password" placeholder="sk-…" spellCheck="false" autoComplete="off" /></div>
      <div className="set-row">
        <Msg m={emsg} />
        {hasCustom && <button className="btn" onClick={removeEndpoint}>{t("settings.removeEndpoint")}</button>}
        <button className="btn" onClick={test} disabled={testing}>{t("settings.test")}</button>
        <button className="btn primary" onClick={saveEndpoint}>{t("common.save")}</button>
      </div>
    </Card>
  </>);
}

/* The composer switches, translated by id at render: the store is seeded once
   in English and is the user's data from then on. "code" is not shown: it has
   been stored since the start and nothing has ever read it. */
const COMPOSER_TOOLS = ["search", "files", "privacy", "mcp", "filegen"];
function toolText(tool, field) {
  const key = "tool." + tool.id + "." + field;
  const v = t(key);
  return v === key ? tool[field] : v;
}
function ChatToolsSection() {
  const [rows, setRows] = useState(() => L.getJSON(L.ADMIN.tools, []));
  const [saved, flash] = useSaved();
  const set = (id, patch) => {
    const next = rows.map(x => x.id === id ? { ...x, ...patch } : x);
    setRows(next); L.setJSON(L.ADMIN.tools, next); flash();
  };
  const shown = COMPOSER_TOOLS.map(id => rows.find(r => r.id === id)).filter(Boolean);

  return (
    <Card title={t("settings.toolsTitle")} desc={t("settings.toolsDesc")} scope="browser" saved={saved}>
      <div className="set-sw-list">
        {shown.map(tool => (
          <SwitchRow key={tool.id} on={!!tool.enabled} onChange={v => set(tool.id, { enabled: v })}
                     name={toolText(tool, "name")} desc={toolText(tool, "desc")}>
            {tool.id === "privacy" && (
              <div className="set-sub">
                <label className="set-sub-label" htmlFor="pv-mode">{t("admin.filterMode")}</label>
                <select id="pv-mode" className="adm-select" value={tool.mode || "redact"} onChange={e => set("privacy", { mode: e.target.value })}>
                  <option value="redact">{t("admin.redactMode")}</option>
                  <option value="strict">{t("admin.strictMode")}</option>
                </select>
              </div>
            )}
            {tool.id === "search" && (
              <details className="set-adv">
                <summary>{t("settings.advanced")}</summary>
                <div className="set-sub">
                  <label className="set-sub-label" htmlFor="serper">{t("settings.serperOwnKey")}</label>
                  <input id="serper" type="password" value={tool.apiKey || ""} placeholder={t("admin.serperHint")} spellCheck="false"
                         autoComplete="off" onChange={e => set("search", { apiKey: e.target.value })} />
                  <div className="help">{t("settings.serperOwnKeyHelp")}</div>
                </div>
              </details>
            )}
          </SwitchRow>
        ))}
      </div>
    </Card>
  );
}

/* Ask before a server's tools: never, before tools that change things (the
   server marks the others read-only), or before every use. */
function ApprovalSelect({ value, disabled, onChange }) {
  return (
    <select className="set-approval" value={value || "never"} disabled={disabled} title={t("settings.mcpApprovalHint")}
            aria-label={t("settings.mcpApprovalHint")} onChange={e => onChange(e.target.value)}>
      <option value="never">{t("settings.mcpApproval.never")}</option>
      <option value="changes">{t("settings.mcpApproval.changes")}</option>
      <option value="always">{t("settings.mcpApproval.always")}</option>
    </select>
  );
}
function McpCard({ isAdmin }) {
  const [servers, setServers] = useState([]);
  const [name, setName] = useState("");
  const [url, setUrl] = useState("");
  const [everyone, setEveryone] = useState(false);
  const [msg, setMsg] = useState(null);
  const [saved, flash] = useSaved();
  const refresh = () => L.McpServersAPI.list().then(r => setServers(r.servers || [])).catch(() => {});
  useEffect(() => { refresh(); }, []);
  const after = async () => { await refresh(); await L.loadMcpServers(); flash(); };

  const add = async () => {
    const u = url.trim();
    if (!/^https?:\/\//i.test(u)) { setMsg({ kind: "bad", text: t("settings.mcpUrlInvalid") }); return; }
    try {
      await L.McpServersAPI.create({ name: name.trim(), url: u, scope: (isAdmin && everyone) ? "global" : "user" });
      setName(""); setUrl(""); setMsg(null); await after();
    } catch (e) { setMsg({ kind: "bad", text: errText(e, t("settings.mcpAddFailed")) }); }
  };
  const toggle = async (s, on) => { try { await L.McpServersAPI.update(s.id, { enabled: on }); await after(); } catch (e) { setMsg({ kind: "bad", text: errText(e, t("err.updateFailed")) }); } };
  const remove = async s => { try { await L.McpServersAPI.remove(s.id); await after(); } catch (e) { setMsg({ kind: "bad", text: errText(e, t("err.removeFailed")) }); } };
  /* whether an agent needs the person's OK before this server's tools */
  const setApproval = async (s, approval) => { try { await L.McpServersAPI.update(s.id, { approval }); await after(); } catch (e) { setMsg({ kind: "bad", text: errText(e, t("err.updateFailed")) }); } };

  return (
    <Card title={t("settings.mcpTitle")} desc={t("settings.mcpDesc")} scope="account" saved={saved}>
      {servers.length > 0 && (
        <div className="set-list">
          {servers.map(s => {
            const mayEdit = s.mine || (s.scope === "global" && isAdmin);
            return (
              <div className={"set-item" + (s.enabled === false ? " off" : "")} key={s.id}>
                <button className={"mcp-switch " + (s.enabled === false ? "" : "on")} disabled={!mayEdit}
                        role="switch" aria-checked={s.enabled !== false} aria-label={s.name}
                        title={mayEdit ? "" : t("settings.mcpManaged")}
                        onClick={() => mayEdit && toggle(s, s.enabled === false)}><span /></button>
                <span className="set-item-name">{s.name}</span>
                {s.scope === "global" && <Scope of="everyone" />}
                <span className="set-item-meta">{s.url.replace(/^https?:\/\//, "")}</span>
                <ApprovalSelect value={s.approval} disabled={!mayEdit} onChange={v => setApproval(s, v)} />
                {s.managed ? <span className="set-item-note">{t("settings.mcpConfigManaged")}</span>
                  : mayEdit ? <DeleteButton onConfirm={() => remove(s)} /> : <span className="set-item-note">{t("settings.mcpManaged")}</span>}
              </div>
            );
          })}
        </div>
      )}
      {/* a service by its address: for people who know what an MCP server is;
          everyone else connects an account above (Connections) */}
      <details className="set-adv">
        <summary>{t("settings.mcpAddAdvanced")}</summary>
        <div className="set-add">
          <input value={name} onChange={e => setName(e.target.value)} placeholder={t("settings.nameOptional")} spellCheck="false" aria-label={t("settings.nameOptional")} />
          <input value={url} onChange={e => setUrl(e.target.value)} placeholder="https://host/mcp" spellCheck="false" aria-label="URL"
                 onKeyDown={e => { if (e.key === "Enter") { e.preventDefault(); add(); } }} />
          <button className="btn" onClick={add}>{t("common.add")}</button>
        </div>
        {isAdmin && (
          <label className="set-check">
            <input type="checkbox" checked={everyone} onChange={e => setEveryone(e.target.checked)} />
            {t("settings.addForEveryone")}
          </label>
        )}
      </details>
      <Msg m={msg} />
    </Card>
  );
}

/* Connectors had a full API (and appear in docs/apps.md) and no screen: the
   only way to add one was curl. */
function ConnectorsCard({ isAdmin }) {
  /* null = still loading, [] = genuinely none: the empty message used to show
     while the request was in flight, telling people they had no connectors. */
  const [list, setList] = useState(null);
  const [builtin, setBuiltin] = useState([]);
  const [form, setForm] = useState({ name: "", url: "", method: "POST", headers: "" });
  const [everyone, setEveryone] = useState(false);
  const [open, setOpen] = useState(false);
  const [msg, setMsg] = useState(null);
  const [saved, flash] = useSaved();
  const refresh = () => L.ConnectorsAPI.list().then(r => { setList(r.connectors || []); setBuiltin(r.builtin || []); }).catch(() => {});
  useEffect(() => { refresh(); }, []);
  const f = (k, v) => setForm(x => ({ ...x, [k]: v }));

  const add = async () => {
    const name = form.name.trim();
    if (!/^[a-z0-9_]{2,40}$/i.test(name)) { setMsg({ kind: "bad", text: t("settings.connectorNameInvalid") }); return; }
    let headers;
    if (form.headers.trim()) {
      try { headers = JSON.parse(form.headers); } catch { headers = null; }
      if (!headers || typeof headers !== "object" || Array.isArray(headers)) { setMsg({ kind: "bad", text: t("settings.connectorHeadersInvalid") }); return; }
    }
    try {
      await L.ConnectorsAPI.create({ name, url: form.url.trim(), method: form.method, headers, scope: (isAdmin && everyone) ? "global" : "user" });
      setForm({ name: "", url: "", method: "POST", headers: "" }); setMsg(null); setOpen(false);
      await refresh(); flash();
    } catch (e) { setMsg({ kind: "bad", text: errText(e, t("settings.connectorAddFailed")) }); }
  };
  const toggle = async (c, on) => { try { await L.ConnectorsAPI.update(c.id, { enabled: on }); await refresh(); flash(); } catch (e) { setMsg({ kind: "bad", text: errText(e, t("err.updateFailed")) }); } };
  const remove = async c => { try { await L.ConnectorsAPI.remove(c.id); await refresh(); flash(); } catch (e) { setMsg({ kind: "bad", text: errText(e, t("err.removeFailed")) }); } };
  /* An own connector SHADOWS a shared one of the same name. Say so on the row,
     or two rows called "crm" look like a duplicate rather than a choice. */
  const shadowed = c => c.scope === "global" && (list || []).some(x => x.mine && x.name === c.name);

  return (
    <Card title={t("settings.connectorsTitle")} desc={t("settings.connectorsDesc")} scope="account" saved={saved}>
      {list === null ? <div className="set-empty">{t("common.loading")}</div> : list.length > 0 ? (
        <div className="set-list">
          {list.map(c => {
            const mayEdit = c.mine || (c.scope === "global" && isAdmin);
            return (
              <div className={"set-item" + (c.enabled ? "" : " off")} key={c.id}>
                <button className={"mcp-switch " + (c.enabled ? "on" : "")} disabled={!mayEdit}
                        role="switch" aria-checked={!!c.enabled} aria-label={c.name}
                        onClick={() => mayEdit && toggle(c, !c.enabled)}><span /></button>
                <span className="set-item-name set-mono">{c.name}</span>
                {c.scope === "global" && <Scope of="everyone" />}
                <span className="set-item-meta">
                  <b>{c.method}</b> {c.url.replace(/^https?:\/\//, "")}{c.hasHeaders ? " · " + t("settings.connectorHasHeaders") : ""}
                  {shadowed(c) && <em> · {t("settings.connectorShadowed")}</em>}
                </span>
                {mayEdit ? <DeleteButton onConfirm={() => remove(c)} /> : <span className="set-item-note">{t("settings.mcpManaged")}</span>}
              </div>
            );
          })}
        </div>
      ) : <div className="set-empty">{t("settings.connectorsEmpty")}</div>}

      {!open ? (
        <div className="set-row"><button className="btn" onClick={() => setOpen(true)}>+ {t("settings.connectorAdd")}</button></div>
      ) : (
        <div className="set-subform">
          <div className="set-3col">
            <div className="field"><label htmlFor="cn-name">{t("settings.connectorName")}</label>
              <input id="cn-name" className="set-mono" value={form.name} onChange={e => f("name", e.target.value)} placeholder="crm_lookup" spellCheck="false" /></div>
            <div className="field grow"><label htmlFor="cn-url">URL</label>
              <input id="cn-url" value={form.url} onChange={e => f("url", e.target.value)} placeholder="https://api.example.com/lookup" spellCheck="false" /></div>
            <div className="field"><label htmlFor="cn-method">{t("settings.connectorMethod")}</label>
              <select id="cn-method" value={form.method} onChange={e => f("method", e.target.value)}>
                <option value="POST">POST</option><option value="GET">GET</option>
              </select></div>
          </div>
          <div className="field"><label htmlFor="cn-headers">{t("settings.connectorHeaders")}</label>
            <textarea id="cn-headers" className="set-mono" rows={3} value={form.headers} onChange={e => f("headers", e.target.value)}
                      placeholder={'{ "Authorization": "Bearer …" }'} spellCheck="false" />
            <div className="help">{t("settings.connectorHeadersHelp")}</div></div>
          {isAdmin && (
            <label className="set-check">
              <input type="checkbox" checked={everyone} onChange={e => setEveryone(e.target.checked)} />
              {t("settings.addForEveryone")}
            </label>
          )}
          <div className="set-row">
            <Msg m={msg} />
            <button className="btn" onClick={() => { setOpen(false); setMsg(null); }}>{t("common.cancel")}</button>
            <button className="btn primary" onClick={add}>{t("common.add")}</button>
          </div>
        </div>
      )}
      {!open && <Msg m={msg} />}
      {builtin.length > 0 && <div className="set-foot-note">{tb("settings.connectorBuiltin", { names: builtin.join(", ") })}</div>}
    </Card>
  );
}

/* Connections (server.js, connections): services you sign in to with your
   own account. An admin sets each up once (a ready entry for Microsoft 365,
   Google or Nextcloud, or any MCP server with OAuth); then everyone sees a
   Connect button. The sign-in opens in a window of its own and tells this
   page when it is done. */
const CONN_FIELDS = { url: "settings.connUrl", tenant: "settings.connTenant", clientId: "settings.connClientId", clientSecret: "settings.connClientSecret", name: "settings.connName" };
function ConnectionSetup({ kinds, redirectUri, editing, onDone, onCancel }) {
  const [kind, setKind] = useState(editing ? editing.kind : (kinds[0] || {}).key);
  const k = kinds.find(x => x.key === kind) || {};
  const [f, setF] = useState(() => editing ? { url: editing.url, tenant: editing.tenant, clientId: editing.clientId, clientSecret: "", name: editing.name, scopes: editing.scopes } : {});
  const [err, setErr] = useState(null);
  const set = (key, v) => setF(x => ({ ...x, [key]: v }));
  const save = async () => {
    setErr(null);
    const body = { kind, ...f };
    if (!body.clientSecret) delete body.clientSecret;
    try { editing ? await L.ConnectionsAPI.update(editing.id, body) : await L.ConnectionsAPI.create(body); onDone(); }
    catch (e) { setErr(errText(e, t("settings.connFailed"))); }
  };
  return (
    <div className="conn-setup">
      {!editing && (
        <div className="field"><label htmlFor="conn-kind">{t("settings.connKind")}</label>
          <select id="conn-kind" className="adm-select" value={kind} onChange={e => { setKind(e.target.value); setF({}); }}>
            {kinds.map(x => <option key={x.key} value={x.key}>{x.name || t("settings.connCustom")}</option>)}
          </select>
        </div>
      )}
      {k.description && <p className="set-desc">{k.description}</p>}
      {k.fields.map(key => (
        <div className="field" key={key}><label htmlFor={"conn-" + key}>{t(CONN_FIELDS[key])}</label>
          <input id={"conn-" + key} type={key === "clientSecret" ? "password" : "text"} value={f[key] || ""} spellCheck="false" autoComplete="off"
                 placeholder={key === "clientSecret" && editing && editing.hasSecret ? t("settings.connSecretKept") : key === "url" ? (k.url || "https://…/mcp") : key === "tenant" ? "organizations" : ""}
                 onChange={e => set(key, e.target.value)} />
        </div>
      ))}
      <details className="set-adv">
        <summary>{t("settings.connScopes")}</summary>
        <input className="conn-scopes" value={f.scopes != null ? f.scopes : ""} placeholder={k.scopes || t("settings.connScopesFromServer")} spellCheck="false" onChange={e => set("scopes", e.target.value)} />
      </details>
      {(k.fields.includes("clientId")) && <p className="set-foot-note">{tb("settings.connRedirect", { uri: redirectUri })}</p>}
      <div className="set-row">
        {err && <div className="set-msg bad">{err}</div>}
        <button className="btn" onClick={onCancel}>{t("common.cancel")}</button>
        <button className="btn primary" onClick={save}>{t("common.save")}</button>
      </div>
    </div>
  );
}
function ConnectionsCard() {
  const [data, setData] = useState(null);
  const [setup, setSetup] = useState(null);       /* null | "new" | a connection being edited */
  const [busy, setBusy] = useState(null);
  const [msg, setMsg] = useState(null);
  const [saved, flash] = useSaved();
  const load = () => L.ConnectionsAPI.list().then(setData).catch(e => { setData({ connections: [] }); setMsg({ kind: "bad", text: errText(e, t("settings.connFailed")) }); });
  useEffect(() => {
    load();
    const onMsg = e => { if (e.origin === location.origin && e.data && e.data.type === "indie-oauth") { setBusy(null); if (e.data.ok) flash(); load(); } };
    window.addEventListener("message", onMsg);
    return () => window.removeEventListener("message", onMsg);
  }, []);
  const connect = async c => {
    setMsg(null); setBusy(c.id);
    /* opened at once, while the click still counts as the person's: a window
       opened after the request returns is what pop-up blockers stop */
    const w = window.open("", "indie-oauth", "width=560,height=720");
    try {
      const r = await L.ConnectionsAPI.connect(c.id);
      if (w && !w.closed) w.location.href = r.url; else location.href = r.url;
    } catch (e) { if (w) w.close(); setBusy(null); setMsg({ kind: "bad", text: errText(e, t("settings.connFailed")) }); }
  };
  const disconnect = async c => { try { await L.ConnectionsAPI.disconnect(c.id); flash(); load(); } catch (e) { setMsg({ kind: "bad", text: errText(e, t("settings.connFailed")) }); } };
  const remove = async c => { try { await L.ConnectionsAPI.remove(c.id); flash(); load(); } catch (e) { setMsg({ kind: "bad", text: errText(e, t("settings.connFailed")) }); } };
  if (!data) return <Card title={t("settings.connTitle")} desc={t("settings.connDesc")} scope="account"><div className="set-empty">{t("common.loading")}</div></Card>;
  if (!data.connections.length && !data.mayManage) return null;
  return (
    <Card title={t("settings.connTitle")} desc={t("settings.connDesc")} scope="account" saved={saved}>
      {data.connections.length === 0 && <div className="set-empty">{t("settings.connNone")}</div>}
      {data.connections.length > 0 && (
        <div className="set-list">
          {data.connections.map(c => (
            <div className={"set-item conn-item" + (c.enabled ? "" : " off")} key={c.id}>
              <span className="conn-cat">{t("settings.connCat." + c.category)}</span>
              <span className="set-item-name">{c.name}</span>
              <span className="set-item-meta" title={c.description}>
                {c.connected ? t("settings.connConnected") + (c.account ? " · " + c.account : "") : c.expired ? t("settings.connExpired") : c.description}
              </span>
              {c.enabled && (c.connected
                ? <button className="mini" onClick={() => disconnect(c)}>{t("settings.connDisconnect")}</button>
                : <button className="mini primary" disabled={busy === c.id} onClick={() => connect(c)}>{busy === c.id ? "…" : c.expired ? t("settings.connAgain") : t("settings.connConnect")}</button>)}
              {data.mayManage && <button className="mini" onClick={() => setSetup(c)}>{t("common.edit")}</button>}
              {data.mayManage && <DeleteButton onConfirm={() => remove(c)} />}
            </div>
          ))}
        </div>
      )}
      {data.mayManage && (setup
        ? <ConnectionSetup kinds={data.kinds || []} redirectUri={data.redirectUri} editing={setup === "new" ? null : setup}
                           onDone={() => { setSetup(null); flash(); load(); }} onCancel={() => setSetup(null)} />
        : <div className="set-row"><button className="btn" onClick={() => setSetup("new")}>{t("settings.connSetUp")}</button></div>)}
      <Msg m={msg} />
    </Card>
  );
}

/* Skills live in the account (server.js, skills): your own, for your agents,
   and everyone's, which admins write. Shared by the workspace panel's Skills
   tab (indie-app.jsx keeps its own copy of this list). A skill is edited as
   its SKILL.md: the frontmatter carries the name and the description. */
const skillMd = s => "---\nname: " + s.name + "\ndescription: " + (s.description || "") + "\n---\n" + (s.content || "");
function SkillRows({ list, onChanged, setMsg, flash }) {
  const [editing, setEditing] = useState(null);     /* id */
  const [text, setText] = useState("");
  const act = async (fn, ok) => {
    try { await fn(); if (ok) ok(); flash(); onChanged(); }
    catch (e) { setMsg({ kind: "bad", text: errText(e, t("settings.skillFailed")) }); }
  };
  if (!list.length) return null;
  return (
    <div className="set-list">
      {list.map(s => editing === s.id ? (
        <div className="set-item skill-edit" key={s.id}>
          <textarea value={text} onChange={e => setText(e.target.value)} rows={8} spellCheck="false" aria-label={s.name} />
          <div className="set-row" style={{ width: "100%" }}>
            <button className="btn" onClick={() => setEditing(null)}>{t("common.cancel")}</button>
            <button className="btn primary" onClick={() => act(() => L.SkillsAPI.update(s.id, { markdown: text }), () => setEditing(null))}>{t("common.save")}</button>
          </div>
        </div>
      ) : (
        <div className={"set-item" + (s.enabled ? "" : " off")} key={s.id}>
          <button className={"mcp-switch " + (s.enabled ? "on" : "")} role="switch" aria-checked={!!s.enabled} aria-label={s.name} disabled={!s.mayEdit}
                  onClick={() => s.mayEdit && act(() => L.SkillsAPI.update(s.id, { enabled: !s.enabled }))}><span /></button>
          <span className="set-item-name">{s.name}</span>
          <span className="set-item-meta" title={s.description}>{s.description}</span>
          {s.mayEdit && <button className="mini" onClick={() => { setEditing(s.id); setText(skillMd(s)); }}>{t("common.edit")}</button>}
          {s.mayEdit && <DeleteButton onConfirm={() => act(() => L.SkillsAPI.remove(s.id))} />}
        </div>
      ))}
    </div>
  );
}
function SkillAdd({ scope, onChanged, setMsg, flash }) {
  const [text, setText] = useState("");
  const add = async () => {
    const raw = text.trim(); if (!raw) return;
    try { await L.SkillsAPI.create({ scope, markdown: raw }); setText(""); setMsg(null); flash(); onChanged(); }
    catch (e) { setMsg({ kind: "bad", text: errText(e, t("settings.skillFailed")) }); }
  };
  return (
    <div className="skill-add">
      <textarea value={text} onChange={e => setText(e.target.value)} rows={5} spellCheck="false" aria-label={t("settings.addSkill")}
                placeholder={"---\nname: PDF summarizer\ndescription: Summarize a PDF into 5 bullet points\n---\nWhen the user shares a PDF, extract the key points and …"} />
      <div className="set-row" style={{ width: "100%" }}>
        <button className="btn" onClick={add} disabled={!text.trim()}>{t("settings.addSkill")}</button>
      </div>
    </div>
  );
}
function SkillsCards() {
  const [data, setData] = useState(null);           /* null: loading */
  const [msgMine, setMsgMine] = useState(null), [msgAll, setMsgAll] = useState(null);
  const [savedMine, flashMine] = useSaved(), [savedAll, flashAll] = useSaved();
  const load = () => L.SkillsAPI.list().then(setData).catch(e => { setData({ mine: [], everyone: [] }); setMsgMine({ kind: "bad", text: errText(e, t("settings.skillFailed")) }); });
  /* a browser's skills from before arrive in the account first */
  useEffect(() => { L.migrateSkills().catch(() => {}).then(load); }, []);
  if (!data) return <Card title={t("settings.skillsTitle")} desc={t("settings.skillsDesc")} scope="account"><div className="set-empty">{t("common.loading")}</div></Card>;
  return (<>
    <Card title={t("settings.skillsTitle")} desc={t("settings.skillsDesc")} scope="account" saved={savedMine}>
      {data.mine.length === 0 && <div className="set-empty">{t("settings.skillsNone")}</div>}
      <SkillRows list={data.mine} onChanged={load} setMsg={setMsgMine} flash={flashMine} />
      <SkillAdd scope="mine" onChanged={load} setMsg={setMsgMine} flash={flashMine} />
      <Msg m={msgMine} />
    </Card>
    {(data.everyone.length > 0 || data.mayEditEveryone) && (
      <Card title={t("settings.skillsAllTitle")} desc={data.mayEditEveryone ? t("settings.skillsAllDescAdmin") : t("settings.skillsAllDesc")} scope="everyone" saved={savedAll}>
        {data.everyone.length === 0 && <div className="set-empty">{t("settings.skillsNone")}</div>}
        <SkillRows list={data.everyone} onChanged={load} setMsg={setMsgAll} flash={flashAll} />
        {data.mayEditEveryone && <SkillAdd scope="global" onChanged={load} setMsg={setMsgAll} flash={flashAll} />}
        <Msg m={msgAll} />
      </Card>
    )}
  </>);
}

/* Plugins (server.js, plugins): an admin installs one from a .zip or a public
   git repository and makes it required, or leaves it for each person to
   switch on for their own agents. */
function pluginContents(p) {
  const parts = [];
  if (p.skills.length) parts.push(t("settings.pluginSkills", { n: p.skills.length }));
  if (p.servers.length) parts.push(t("settings.pluginServers", { n: p.servers.length }));
  if (p.instructions) parts.push(t("settings.pluginInstructions"));
  if (p.apps.length) parts.push(t("settings.pluginApps", { n: p.apps.length }));
  return parts.join(" · ");
}
function PluginsCard() {
  const [data, setData] = useState(null);
  const [busy, setBusy] = useState(null);           /* "install" | plugin id */
  const [git, setGit] = useState("");
  const [msg, setMsg] = useState(null);
  const [saved, flash] = useSaved();
  const zipIn = useRef(null), replaceIn = useRef({});
  const load = () => L.PluginsAPI.list().then(setData).catch(e => { setData({ plugins: [] }); setMsg({ kind: "bad", text: errText(e, t("settings.pluginFailed")) }); });
  useEffect(() => { load(); }, []);
  const run = async (key, fn) => {
    setBusy(key); setMsg(null);
    try { await fn(); flash(); await load(); }
    catch (e) { setMsg({ kind: "bad", text: errText(e, t("settings.pluginFailed")) }); }
    finally { setBusy(null); }
  };
  if (!data) return <Card title={t("settings.pluginsTitle")} desc={t("settings.pluginsDesc")} scope="everyone"><div className="set-empty">{t("common.loading")}</div></Card>;
  if (!data.plugins.length && !data.mayInstall) return null;
  return (
    <Card title={t("settings.pluginsTitle")} desc={data.mayInstall ? t("settings.pluginsDescAdmin") : t("settings.pluginsDesc")} scope="everyone" saved={saved}>
      {data.plugins.length === 0 && <div className="set-empty">{t("settings.pluginsNone")}</div>}
      {data.plugins.length > 0 && (
        <div className="set-list">
          {data.plugins.map(p => (
            <div className="plugin-item" key={p.id}>
              <div className="plugin-head">
                {!p.required && <button className={"mcp-switch " + (p.on ? "on" : "")} role="switch" aria-checked={!!p.on} aria-label={p.name} title={t("settings.pluginUseHint")}
                                        onClick={() => run(p.id, () => L.PluginsAPI.use(p.id, !p.on))}><span /></button>}
                <span className="set-item-name">{p.name}{p.version ? " " + p.version : ""}</span>
                {p.required && <span className="plugin-req">{t("settings.pluginRequired")}</span>}
                <span className="set-item-meta">{pluginContents(p)}</span>
              </div>
              {p.description && <p className="plugin-desc">{p.description}</p>}
              {p.ignored.length > 0 && <p className="plugin-note">{t("settings.pluginIgnored", { list: p.ignored.map(x => x.startsWith("mcp:") ? t("settings.pluginServerNamed", { name: x.slice(4) }) : x).join(", ") })}</p>}
              {data.mayInstall && (
                <div className="plugin-acts">
                  <label className="set-check"><input type="checkbox" checked={p.required} disabled={busy === p.id}
                                                      onChange={e => run(p.id, () => L.PluginsAPI.setRequired(p.id, e.target.checked))} /> {t("settings.pluginRequire")}</label>
                  <span className="plugin-src" title={p.sourceRef}>{p.source === "git" ? p.sourceRef.replace(/^https:\/\//, "") : p.sourceRef}</span>
                  {p.source === "git"
                    ? <button className="mini" disabled={busy === p.id} onClick={() => run(p.id, () => L.PluginsAPI.update(p.id))}>{busy === p.id ? "…" : t("settings.pluginUpdate")}</button>
                    : <><button className="mini" disabled={busy === p.id} onClick={() => replaceIn.current[p.id] && replaceIn.current[p.id].click()}>{busy === p.id ? "…" : t("settings.pluginReplace")}</button>
                        <input type="file" hidden accept=".zip" ref={el => { replaceIn.current[p.id] = el; }}
                               onChange={e => { const f = e.target.files && e.target.files[0]; e.target.value = ""; if (f) run(p.id, () => L.PluginsAPI.replace(p.id, f)); }} /></>}
                  <DeleteButton onConfirm={() => run(p.id, () => L.PluginsAPI.remove(p.id))} />
                </div>
              )}
            </div>
          ))}
        </div>
      )}
      {data.mayInstall && (
        <div className="plugin-install">
          <button className="btn" disabled={busy === "install"} onClick={() => zipIn.current && zipIn.current.click()}>{busy === "install" ? t("settings.pluginInstalling") : t("settings.pluginFromZip")}</button>
          <input ref={zipIn} type="file" hidden accept=".zip" onChange={e => { const f = e.target.files && e.target.files[0]; e.target.value = ""; if (f) run("install", () => L.PluginsAPI.installZip(f)); }} />
          <span className="plugin-or">{t("settings.pluginOr")}</span>
          <input className="plugin-git" value={git} onChange={e => setGit(e.target.value)} placeholder="https://github.com/…/…" spellCheck="false" aria-label={t("settings.pluginGit")} />
          <button className="btn" disabled={!git.trim() || busy === "install"} onClick={() => run("install", async () => { await L.PluginsAPI.installGit(git.trim()); setGit(""); })}>{t("settings.pluginInstall")}</button>
        </div>
      )}
      <Msg m={msg} />
    </Card>
  );
}

/* A provider's sign-in app for the deployment (server.js, connectors per
   agent): one Google app for Gmail, Drive and Calendar, one Microsoft app
   (Entra ID) for Outlook, OneDrive, the calendar and Teams, on every agent,
   instead of a connection per service. The environment (GOOGLE_CLIENT_ID,
   MICROSOFT_CLIENT_ID) wins and is shown as is. Strings: settings.<provider>*. */
/* Google's console, where each step of the guide happens */
const GOOGLE_CONSOLE = {
  project: "https://console.cloud.google.com/projectcreate",
  apis: [["Gmail API", "https://console.cloud.google.com/apis/library/gmail.googleapis.com"], ["Google Drive API", "https://console.cloud.google.com/apis/library/drive.googleapis.com"],
         ["Google Calendar API", "https://console.cloud.google.com/apis/library/calendar-json.googleapis.com"]],
  audience: "https://console.cloud.google.com/auth/audience",
  clients: "https://console.cloud.google.com/auth/clients",
};
const GOOGLE_TROUBLE = 9;   /* settings.googleT1Q .. T9A: what Google says, and what to do */
const Ext = ({ href, children }) => <a href={href} target="_blank" rel="noopener noreferrer">{children}</a>;
function CopyChip({ text }) {
  const [done, setDone] = useState(false);
  return <button type="button" className="mini set-copy" onClick={() => L.copyText(text).then(ok => { if (ok) { setDone(true); setTimeout(() => setDone(false), 1600); } })}>{done ? t("settings.copied") : t("settings.copy")}</button>;
}
function ProviderClientCard({ provider }) {
  const k = key => "settings." + provider + key;
  const ms = provider === "microsoft";
  const [d, setD] = useState(null);
  const [f, setF] = useState({ clientId: "", clientSecret: "", tenant: "", flow: "redirect" });
  const [msg, setMsg] = useState(null);
  const [saved, flash] = useSaved();
  /* what Google answered when asked (Check): null, { busy } or the result */
  const [check, setCheck] = useState(null);
  /* The way back that fits the address this server is opened at (server.js,
     clientView): straight back only where Google takes the address for
     everyone, else copying an address back. */
  const fits = r => (r.address && r.address.reason === "ok" ? "redirect" : "paste");
  const fill = r => { setD(r); setF({ clientId: r.clientId || "", clientSecret: "", tenant: r.tenant || "", flow: r.address ? (r.configured || r.fromEnv ? r.flow || "redirect" : fits(r)) : "redirect" }); };
  useEffect(() => {
    L.AccountsAPI.client(provider).then(fill).catch(e => setMsg({ kind: "bad", text: errText(e, t(k("Failed"))) }));
  }, []);
  const save = async () => {
    try {
      const r = await L.AccountsAPI.setClient(provider, { clientId: f.clientId.trim(), ...(f.clientSecret.trim() ? { clientSecret: f.clientSecret.trim() } : {}),
                                                         ...(ms ? { tenant: f.tenant.trim() } : {}), ...(d.address ? { flow: f.flow } : {}) });
      fill(r); setMsg(null); flash();
      return true;
    } catch (e) { setMsg({ kind: "bad", text: errText(e, t(k("Failed"))) }); return false; }
  };
  /* with what is in the form, saved or not */
  const runCheck = async () => {
    setMsg(null); setCheck({ busy: true });
    try { setCheck(await L.AccountsAPI.checkClient(provider, d.fromEnv ? {} : { clientId: f.clientId.trim(), ...(f.clientSecret.trim() ? { clientSecret: f.clientSecret.trim() } : {}), flow: f.flow })); }
    catch (e) { setCheck(null); setMsg({ kind: "bad", text: errText(e, t(k("Failed"))) }); }
  };
  if (!d) return <Card title={t(k("Title"))} desc={t(k("Desc"))} scope="everyone">{msg ? <Msg m={msg} /> : <div className="set-empty">{t("common.loading")}</div>}</Card>;
  /* Google: the two ways back, the steps, Google's own answer, and what its errors mean */
  const google = !!d.address;
  const wayUri = google ? (f.flow === "paste" ? d.pasteRedirect : d.redirectUri) : d.redirectUri;
  const verdictClass = google ? (d.address.reason === "ok" ? "ok" : d.address.reason === "local" ? "" : "bad") : "";
  return (
    <Card title={t(k("Title"))} desc={t(k("Desc"))} scope="everyone" saved={saved} id={provider + "-signin"}>
      {google && <p className="set-foot-note set-tip">{tb("settings.googleQuick")}</p>}
      {google && (
        <div className="field set-way">
          <label>{t("settings.googleWayLabel")}</label>
          <p className={"set-verdict " + verdictClass} data-reason={d.address.reason}>{tb("settings.googleAddr." + d.address.reason, { origin: d.address.origin })}</p>
          <div className="conn-choices">
            {["paste", "redirect"].map(w => (
              <label key={w} className={"conn-choice" + (f.flow === w ? " on" : "")}>
                <input type="radio" name="google-flow" value={w} checked={f.flow === w} disabled={d.fromEnv} onChange={() => { setF({ ...f, flow: w }); setCheck(null); }} />
                <span><b>{t("settings.googleWay." + w)}</b>{fits(d) === w && <span className="set-chip">{t("settings.googleWayBest")}</span>} <span className="conn-choice-sub">{t("settings.googleWayHint." + w)}</span></span>
              </label>
            ))}
          </div>
          {d.fromEnv && <div className="help">{tb("settings.googleWayEnv")}</div>}
        </div>
      )}
      {google && (
        <details className="set-guide" open={!d.configured}>
          <summary>{t("settings.googleGuide")}</summary>
          <ol className="set-steps">
            <li>{tb("settings.googleStep1")} <Ext href={GOOGLE_CONSOLE.project}>{t("settings.googleLinkProject")}</Ext></li>
            <li>{tb("settings.googleStep2")} {GOOGLE_CONSOLE.apis.map(([name, href], i) => <React.Fragment key={href}>{i ? ", " : ""}<Ext href={href}>{name}</Ext></React.Fragment>)}. {t("settings.googleStep2b")}</li>
            <li>{tb("settings.googleStep3")} <Ext href={GOOGLE_CONSOLE.audience}>{t("settings.googleLinkAudience")}</Ext>
              <ul>
                <li>{tb("settings.googleStep3a")}</li>
                <li>{tb("settings.googleStep3b")}</li>
              </ul>
            </li>
            <li>{f.flow === "paste" ? tb("settings.googleStep4Paste") : tb("settings.googleStep4Redirect")} <Ext href={GOOGLE_CONSOLE.clients}>{t("settings.googleLinkClients")}</Ext>
              {f.flow === "redirect" && <div className="set-uri"><code>{d.redirectUri}</code><CopyChip text={d.redirectUri} /></div>}
              {f.flow === "paste" && <div className="help">{tb("settings.googleStep4PasteWeb", { uri: d.pasteRedirect })}</div>}
            </li>
            <li>{tb("settings.googleStep5")}</li>
          </ol>
        </details>
      )}
      {d.fromEnv ? <p className="set-foot-note">{tb(k("FromEnv"), { id: d.clientId })}</p> : (<>
        <div className="field">
          <label htmlFor={provider + "-client"}>{t(k("ClientId"))}</label>
          <input id={provider + "-client"} value={f.clientId} spellCheck="false" autoComplete="off"
                 placeholder={ms ? "00000000-0000-0000-0000-000000000000" : "…apps.googleusercontent.com"} onChange={e => setF({ ...f, clientId: e.target.value })} />
        </div>
        <div className="field">
          <label htmlFor={provider + "-secret"}>{t(k("Secret"))}</label>
          <input id={provider + "-secret"} type="password" value={f.clientSecret} autoComplete="off" placeholder={d.hasSecret ? t("settings.connSecretKept") : ""} onChange={e => setF({ ...f, clientSecret: e.target.value })} />
        </div>
        {ms && (
          <div className="field">
            <label htmlFor="microsoft-tenant">{t("settings.microsoftTenant")}</label>
            <input id="microsoft-tenant" value={f.tenant} spellCheck="false" autoComplete="off" placeholder="organizations" onChange={e => setF({ ...f, tenant: e.target.value })} />
            <div className="help">{t("settings.microsoftTenantHint")}</div>
          </div>
        )}
        <div className="set-row">
          <button className="btn primary" onClick={save}>{t("common.save")}</button>
          {google && <button className="btn" disabled={!f.clientId.trim() || (check && check.busy)} onClick={runCheck}>{check && check.busy ? t("settings.googleChecking") : t("settings.googleCheck")}</button>}
        </div>
      </>)}
      {google && d.fromEnv && <div className="set-row"><button className="btn" disabled={check && check.busy} onClick={runCheck}>{check && check.busy ? t("settings.googleChecking") : t("settings.googleCheck")}</button></div>}
      {google && check && !check.busy && (() => {
        /* one line for the client, one for the way back (said only where the client is known) */
        const cOk = check.client === "ok", wOk = check.redirect === "ok";
        const wayKey = "settings.googleCheckWay." + check.redirect + (["ok", "mismatch"].includes(check.redirect) ? "." + check.flow : "");
        const showWay = !["unknown-client", "unreachable"].includes(check.redirect) && check.client !== "unreachable";
        return (
          <ul className="set-asked" role="status">
            <li className={cOk ? "ok" : check.client === "unclear" ? "" : "bad"} data-check={"client-" + check.client}>{tb("settings.googleCheckClient." + check.client)}</li>
            {showWay && <li className={wOk ? "ok" : check.redirect === "unclear" ? "" : "bad"} data-check={"way-" + check.redirect}>{tb(wayKey, { uri: check.redirectUri, detail: check.detail || "" })}</li>}
          </ul>
        );
      })()}
      {!google && <p className="set-foot-note">{tb(k("Redirect"), { uri: d.redirectUri })}</p>}
      {!google && <p className="set-foot-note">{tb(k("Apis"))}</p>}
      {google && (
        <details className="set-guide set-trouble">
          <summary>{t("settings.googleTrouble")}</summary>
          <dl>
            {Array.from({ length: GOOGLE_TROUBLE }, (_, i) => (
              <React.Fragment key={i}><dt>{t("settings.googleT" + (i + 1) + "Q")}</dt><dd>{tb("settings.googleT" + (i + 1) + "A")}</dd></React.Fragment>
            ))}
          </dl>
        </details>
      )}
      <Msg m={msg} />
    </Card>
  );
}
/* The accounts behind agents' connections that this person can see: their
   own, their workspaces', and for admins the one for everyone. They are added
   from an agent's Connections; here they are seen together and disconnected,
   and one's own say what one's new agents get of them (server.js,
   connectorDefaults): at most what the account grants, more needs a sign-in
   from an agent's Connections. */
const DEFAULT_LEVELS = ["read", "ask", "write"];
function AccountsCard() {
  const [d, setD] = useState(null);
  const [showConn, setShowConn] = useState(false);
  const [msg, setMsg] = useState(null);
  const [saved, flash] = useSaved();
  const load = () => L.AccountsAPI.list().then(setD).catch(e => { setD({ accounts: [] }); setMsg({ kind: "bad", text: errText(e, t("settings.agentAccountsFailed")) }); });
  useEffect(() => { load(); }, []);
  const remove = async a => { try { await L.AccountsAPI.remove(a.id); flash(); load(); } catch (e) { setMsg({ kind: "bad", text: errText(e, t("settings.agentAccountsFailed")) }); } };
  const setDefault = async (a, service, access) => {
    setMsg(null);
    try { await L.AccountsAPI.setDefault({ service, accountId: a.id, access: access || null }); flash(); load(); }
    catch (e) { setMsg({ kind: "bad", text: errText(e, t("settings.agentAccountsFailed")) }); }
  };
  const applyAll = async () => {
    setMsg(null);
    try {
      const r = await L.AccountsAPI.applyDefaults();
      setMsg({ kind: "ok", text: r.agents ? t("settings.defaultsApplied", { n: r.agents }) : t("settings.defaultsNothing") });
      load();
    } catch (e) { setMsg({ kind: "bad", text: errText(e, t("settings.agentAccountsFailed")) }); }
  };
  if (!d) return <Card title={t("settings.agentAccountsTitle")} desc={t("settings.agentAccountsDesc")} scope="account"><div className="set-empty">{t("common.loading")}</div></Card>;
  /* nothing to show where no provider is set up and nobody connected anything */
  if (!d.accounts.length && !d.googleReady && !Object.values(d.ready || {}).some(Boolean)) return null;
  const reachWords = a => Object.entries(a.reach || {}).map(([k, v]) => t("conn.svc." + k) + (v === "write" ? " ✎" : "")).join(", ");
  return (
    <Card title={t("settings.agentAccountsTitle")} desc={t("settings.agentAccountsDesc")} scope="account" saved={saved}>
      {d.accounts.length === 0 && <div className="set-empty">{t("settings.agentAccountsNone")}</div>}
      {d.accounts.length > 0 && (
        <div className="set-list">
          {d.accounts.map(a => (
            <React.Fragment key={a.id}>
              <div className={"set-item" + (a.expired ? " off" : "")}>
                <span className="conn-cat">{a.owner === "person" ? t("settings.accountMine") : a.owner === "workspace" ? (a.workspaceName || t("settings.accountWs")) : t("settings.accountAll")}</span>
                <span className="set-item-name">{a.label}</span>
                <span className="set-item-meta" title={reachWords(a)}>
                  {reachWords(a) || t("settings.accountNoService")} · {a.agents.length ? t("settings.accountUsedBy", { names: a.agents.map(x => x.name).join(", ") }) : t("settings.accountUnused")}
                  {a.expired && <em> · {t("conn.expired")}</em>}
                </span>
                {a.manage && <DeleteButton label={t("settings.connDisconnect")} onConfirm={() => remove(a)} />}
              </div>
              {a.defaults && Object.keys(a.reach || {}).length > 0 && (
                <div className="acct-defaults">
                  <span className="acct-defaults-label">{t("settings.defaultsLabel")}</span>
                  {Object.entries(a.reach).map(([svc, reach]) => (
                    <label key={svc} className="acct-default">
                      <span>{t("conn.svc." + svc)}</span>
                      <select className="adm-select" value={a.defaults[svc] || ""} onChange={e => setDefault(a, svc, e.target.value)}>
                        <option value="">{t("settings.defaultOff")}</option>
                        {DEFAULT_LEVELS.filter(l => l === "read" || reach === "write").map(l => <option key={l} value={l}>{window.IndieConn.accessLabel(svc, l)}</option>)}
                      </select>
                    </label>
                  ))}
                </div>
              )}
            </React.Fragment>
          ))}
        </div>
      )}
      <div className="set-row">
        <button className="btn" onClick={() => setShowConn(true)}>{t("settings.newAgentsConn")}</button>
        {d.accounts.some(a => a.defaults && Object.keys(a.defaults).length) && <button className="btn" onClick={applyAll}>{t("settings.defaultsApply")}</button>}
      </div>
      <Msg m={msg} />
      {showConn && <ConnectionsModal agent={null} title={t("conn.newTitle")} onClose={() => { setShowConn(false); load(); }} />}
    </Card>
  );
}

/* What agents did through the app (server.js, tool_calls): the calls made for
   you; admins can switch to everyone's. */
const ACT_OUTCOME = { ok: "ok", error: "bad", declined: "bad", expired: "bad", refused: "bad", cancelled: "bad" };
function ActivityCard({ isAdmin }) {
  const [all, setAll] = useState(false);
  const [d, setD] = useState(null);
  useEffect(() => { setD(null); L.AccountsAPI.activity(all).then(setD).catch(() => setD({ calls: [] })); }, [all]);
  return (
    <Card title={t("act.title")} desc={t("act.desc")} scope={all ? "everyone" : "account"}>
      {isAdmin && (
        <label className="set-check" style={{ marginTop: 0, marginBottom: 10 }}>
          <input type="checkbox" checked={all} onChange={e => setAll(e.target.checked)} /> {t("act.everyone")}
        </label>
      )}
      {!d ? <div className="set-empty">{t("common.loading")}</div>
        : !d.calls.length ? <div className="set-empty">{t("act.none")}</div>
        : <div className="act-list">{d.calls.map((c, i) => (
            <div className="act-row" key={i}>
              <span className="act-when" title={new Date(c.at).toLocaleString()}>{new Date(c.at).toLocaleString([], { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}</span>
              <span className="act-agent">{c.agent}{c.who ? " · " + c.who : ""}</span>
              <span className="act-tool">{c.server}_{c.tool}</span>
              {c.account && <span className="act-account">{c.account}</span>}
              {c.approval && c.approval !== c.outcome && <span className={"act-chip " + (["allowed", "reviewed", "direct"].includes(c.approval) ? "ok" : "bad")}>{t("act.approval." + c.approval)}</span>}
              <span className={"act-chip " + (ACT_OUTCOME[c.outcome] || "")} title={c.detail || ""}>{t("act.outcome." + c.outcome)}</span>
            </div>
          ))}</div>}
      <p className="set-foot-note">{t("act.note")}</p>
    </Card>
  );
}
/* Whether agents may send mail at all (server.js, mailSendOn). Every send is
   shown to its person first either way; drafts only takes sending away. */
function MailPolicyCard() {
  const [send, setSend] = useState(null);
  const [msg, setMsg] = useState(null);
  const [saved, flash] = useSaved();
  useEffect(() => { L.MailAPI.policy().then(r => setSend(r.send)).catch(e => setMsg({ kind: "bad", text: errText(e, t("settings.mailFailed")) })); }, []);
  const pick = async v => {
    const prev = send; setSend(v); setMsg(null);
    try { const r = await L.MailAPI.setPolicy(v); setSend(r.send); flash(); }
    catch (e) { setSend(prev); setMsg({ kind: "bad", text: errText(e, t("settings.mailFailed")) }); }
  };
  return (
    <Card title={t("settings.mailTitle")} desc={t("settings.mailDesc")} scope="everyone" saved={saved} id="mail-policy">
      {send == null ? (msg ? null : <div className="set-empty">{t("common.loading")}</div>) : (
        <div className="set-radios">
          {[["allow", "settings.mailAllow", "settings.mailAllowHint"], ["drafts", "settings.mailDrafts", "settings.mailDraftsHint"]].map(([k, label, hint]) => (
            <label key={k} className={"set-radio" + (send === k ? " on" : "")}>
              <input type="radio" name="mail-policy" checked={send === k} onChange={() => pick(k)} />
              <span className="set-radio-text"><b>{t(label)}</b> <span className="set-radio-sub">{t(hint)}</span></span>
            </label>
          ))}
        </div>
      )}
      <Msg m={msg} />
    </Card>
  );
}

function IntegrationsSection({ isAdmin }) {
  return (<>
    {isAdmin && <ProviderClientCard provider="google" />}
    {isAdmin && <ProviderClientCard provider="microsoft" />}
    {isAdmin && <MailPolicyCard />}
    <AccountsCard />
    <ActivityCard isAdmin={isAdmin} />
    <ConnectionsCard />
    <McpCard isAdmin={isAdmin} />
    <ConnectorsCard isAdmin={isAdmin} />
    <SkillsCards />
    <PluginsCard />
  </>);
}

/* ---- agents: what each one is told, and what it may read ----
   An agent's system prompt was reachable only through the AGENT_GUIDANCE env
   and a server restart; per-agent wiki access had a server rule (exactly one
   writer per wiki) and no screen. Both live on the agent's row now, so
   everything that shapes one agent is in one place. */
function InstructionsEditor({ value, limit, placeholder, onSave, label }) {
  const [text, setText] = useState(value || "");
  const [base, setBase] = useState(value || "");
  const [msg, setMsg] = useState(null);
  const [busy, setBusy] = useState(false);
  useEffect(() => { setText(value || ""); setBase(value || ""); }, [value]);
  const max = limit || 8000;
  const dirty = text !== base;
  const over = text.length > max;
  const save = async () => {
    setBusy(true); setMsg(null);
    try { await onSave(text); setBase(text); setMsg({ kind: "ok", text: t("settings.instructionsSaved") }); }
    catch (e) { setMsg({ kind: "bad", text: errText(e, t("err.updateFailed")) }); }
    finally { setBusy(false); }
  };
  return (
    <div className="set-instr">
      {label && <div className="set-sub-label">{label}</div>}
      <textarea value={text} rows={7} placeholder={placeholder} aria-label={label || t("settings.instructions")}
                onChange={e => { setText(e.target.value); setMsg(null); }} />
      <div className="set-row">
        <span className={"set-count" + (over ? " over" : "")}>{t("settings.charsCount", { n: L.fmtNum(text.length), max: L.fmtNum(max) })}</span>
        <Msg m={msg || (over ? { kind: "bad", text: t("settings.tooLong", { max: L.fmtNum(max) }) } : null)} />
        {dirty && <button className="btn" onClick={() => { setText(base); setMsg(null); }}>{t("settings.discard")}</button>}
        <button className="btn primary" onClick={save} disabled={!dirty || over || busy}>{t("common.save")}</button>
      </div>
    </div>
  );
}

/* The whole system prompt, top to bottom, as the model receives it: which part
   comes from where, and which part is yours to edit. You could add to it
   without seeing it. Read on demand, because reading it starts pi once in a
   short-lived container, and again whenever reloadKey moves (a save). */
function SystemPromptView({ load, reloadKey, editHere, isAdmin }) {
  const [p, setP] = useState(null);
  const [err, setErr] = useState(null);
  const [copied, setCopied] = useState(false);
  useEffect(() => {
    let live = true;
    setP(null); setErr(null);
    load().then(r => { if (live) setP(r); })
          .catch(e => { if (live) setErr({ kind: "bad", text: errText(e, t("err.loadFailed")) }); });
    return () => { live = false; };
  }, [reloadKey]);
  if (err) return <div className="set-prompt"><Msg m={err} /></div>;
  if (!p) return <div className="set-prompt"><div className="set-reach-pending">{t("settings.promptLoading")}</div></div>;
  const where = layer => {
    if (layer === editHere) return { text: t("settings.promptEditAbove"), mine: true };
    if (layer === "workspace") return isAdmin ? { text: t("settings.promptEditAllAgents"), href: "#all-agents" } : { text: t("settings.promptSetByAdmin") };
    if (layer === "deployment") return { text: t("settings.promptSetInEnv") };
    if (layer === "space") return { text: t("settings.promptSpaceEdit") };
    if (layer === "memory") return { text: t("settings.promptMemoryEdit"), href: "#memory" };
    if (layer === "skills") return { text: t("settings.promptSkillsWhere"), href: "#integrations" };
    if (layer === "all") return { text: "" };
    return { text: t("settings.promptBuiltIn") };
  };
  const whole = p.sections.map(s => s.hidden ? "[" + t("settings.promptLayer.deployment") + "]" : s.text).join("\n\n");
  const copy = () => {
    if (!navigator.clipboard) return;
    navigator.clipboard.writeText(whole).then(() => { setCopied(true); setTimeout(() => setCopied(false), 1600); }).catch(() => {});
  };
  return (
    <div className="set-prompt">
      <div className="set-prompt-head">
        <span className="set-prompt-lead">{t("settings.promptLead")}</span>
        <span className="set-count">{t("settings.promptSize", { chars: L.fmtNum(p.chars), tokens: L.fmtNum(Math.round(p.chars / 4)) })}</span>
        <button className="btn" onClick={copy}>{copied ? t("settings.promptCopied") : t("settings.promptCopy")}</button>
      </div>
      {p.engineError && <div className="set-callout bad">{t("settings.promptNoEngine", { reason: p.engineError })}</div>}
      {p.sections.map((s, i) => {
        const w = where(s.layer);
        return (
          <div key={i} className={"set-prompt-layer" + (w.mine ? " mine" : "")}>
            <div className="set-prompt-label">
              <span className="set-sub-label">{t("settings.promptLayer." + s.layer)}</span>
              {w.text && (w.href ? <a className="set-prompt-where" href={w.href}>{w.text}</a>
                                 : <span className="set-prompt-where">{w.text}</span>)}
            </div>
            {s.hidden ? <div className="set-prompt-hidden">{t("settings.promptDeploymentHidden")}</div>
                      : <pre className="set-pre">{s.text}</pre>}
          </div>
        );
      })}
      {p.tools && p.tools.length > 0 && (
        <details className="set-adv set-prompt-tools">
          <summary>{t("settings.promptTools", { n: p.tools.length })}</summary>
          <ul>{p.tools.map(x => <li key={x.name}><span className="set-mono">{x.name}</span><span>{x.description}</span></li>)}</ul>
        </details>
      )}
      {p.mcp && p.mcp.length > 0 && <div className="set-foot-note">{t("settings.promptMcp", { names: p.mcp.join(", ") })}</div>}
      <div className="set-foot-note">{t("settings.promptPerMessage")}</div>
    </div>
  );
}
/* Not a <details>: its body would mount, and so start the engine, while closed. */
function PromptToggle({ label, children }) {
  const [on, setOn] = useState(false);
  return (
    <div className="set-prompt-wrap">
      <button className="set-prompt-toggle" onClick={() => setOn(v => !v)} aria-expanded={on}>
        <span className="set-prompt-caret" aria-hidden="true">▸</span>{on ? t("settings.promptHide") : label}
      </button>
      {on && children()}
    </div>
  );
}

/* One line saying what an agent is for, shown under its name in the sidebar
   and in its empty state. Saved when the field is left. */
function AgentDescription({ agent, onSave }) {
  const [v, setV] = useState(agent.description || "");
  useEffect(() => { setV(agent.description || ""); }, [agent.id, agent.description]);
  const commit = () => { const n = v.replace(/\s+/g, " ").trim(); if (n !== (agent.description || "")) onSave(n); };
  return (
    <div className="field set-agent-desc">
      <label htmlFor={"desc-" + agent.id}>{t("settings.agentDesc")}</label>
      <input id={"desc-" + agent.id} value={v} maxLength={200} placeholder={t("settings.agentDescPlaceholder")}
             onChange={e => setV(e.target.value)} onBlur={commit}
             onKeyDown={e => { if (e.key === "Enter") e.target.blur(); }} />
    </div>
  );
}

function AgentRow({ agent, wikiOn, limit, onWiki, onInstructions, onDescription, isAdmin }) {
  const [open, setOpen] = useState(false);
  const has = !!(agent.instructions && agent.instructions.trim());
  return (
    <div className={"set-agent" + (open ? " open" : "")}>
      <div className="set-agent-head">
        <button className="set-agent-toggle" onClick={() => setOpen(o => !o)} aria-expanded={open}>
          <span className="set-agent-caret" aria-hidden="true">▸</span>
          <span className="set-agent-name">{agent.name}</span>
          {has && <span className="set-agent-chip">{t("settings.instructionsSet")}</span>}
        </button>
        {wikiOn && (
          <label className="set-agent-wiki">
            <span>{t("settings.wikiAccess")}</span>
            <select className="adm-select" value={agent.wiki || "none"} aria-label={t("settings.wikiAccess") + ": " + agent.name}
                    onChange={e => onWiki(agent, e.target.value)}>
              <option value="none">{t("settings.wiki.none")}</option>
              <option value="read">{t("settings.wiki.read")}</option>
              {/* the company's wiki is written by its Librarian; a workspace's by one of its agents */}
              {!(agent.scope === "user" && !agent.workspaceId) && <option value="write">{t("settings.wiki.write")}</option>}
            </select>
          </label>
        )}
      </div>
      {open && (<>
        <AgentDescription agent={agent} onSave={text => onDescription(agent, text)} />
        <InstructionsEditor value={agent.instructions || ""} limit={limit}
                            label={t("settings.instructionsFor", { name: agent.name })}
                            placeholder={t("settings.instructionsPlaceholder")}
                            onSave={text => onInstructions(agent, text)} />
        <div className="set-agent-prompt">
          <PromptToggle label={t("settings.promptShow")}>
            {() => <SystemPromptView load={() => L.AgentsAPI.systemPrompt(agent.id, L.enabledSkills())}
                                     reloadKey={agent.instructions || ""} editHere="agent" isAdmin={isAdmin} />}
          </PromptToggle>
        </div>
      </>)}
    </div>
  );
}

/* One list of agents that share an owner, so they share a wiki and its single
   writer: choosing a writer demotes the previous one, and the row says so. */
function AgentListCard({ title, desc, scope, agents, limit, empty, onChanged, isAdmin }) {
  const [msg, setMsg] = useState(null);
  const [saved, flash] = useSaved();
  const [local, setLocal] = useState(agents);
  useEffect(() => { setLocal(agents); }, [agents]);
  const wikiOn = L.moduleOn("brain");
  const onWiki = async (a, mode) => {
    const prev = mode === "write" ? local.find(x => x.wiki === "write" && x.id !== a.id) : null;
    setLocal(list => list.map(x => x.id === a.id ? { ...x, wiki: mode } : (prev && x.id === prev.id ? { ...x, wiki: "read" } : x)));
    try {
      await L.AgentsAPI.update(a.id, { wiki: mode });
      setMsg(prev ? { kind: "ok", text: t("settings.wikiHandover", { name: a.name, prev: prev.name }) } : null);
      flash();
    } catch (e) { setMsg({ kind: "bad", text: errText(e, t("err.updateFailed")) }); }
    onChanged();
  };
  const onDescription = async (a, text) => {
    try {
      const r = await L.AgentsAPI.update(a.id, { description: text });
      setLocal(list => list.map(x => x.id === a.id ? { ...x, description: r.description != null ? r.description : text } : x));
      flash(); setMsg(null);
    } catch (e) { setMsg({ kind: "bad", text: errText(e, t("err.updateFailed")) }); }
  };
  const onInstructions = async (a, text) => {
    const r = await L.AgentsAPI.update(a.id, { instructions: text });
    setLocal(list => list.map(x => x.id === a.id ? { ...x, instructions: r.instructions != null ? r.instructions : text } : x));
    flash();
  };
  return (
    <Card title={title} desc={desc} scope={scope} saved={saved}>
      {local.length
        ? <div className="set-agents">{local.map(a => (
            <AgentRow key={a.id} agent={a} wikiOn={wikiOn} limit={limit} onWiki={onWiki} onInstructions={onInstructions} onDescription={onDescription} isAdmin={isAdmin} />
          ))}</div>
        : <div className="set-empty">{empty}</div>}
      <Msg m={msg} />
    </Card>
  );
}

function useAgents() {
  const [agents, setAgents] = useState(null);
  const [error, setError] = useState(null);
  const refresh = () => L.AgentsAPI.list().then(a => setAgents(Array.isArray(a) ? a : (a.agents || [])))
                                        .catch(e => setError({ kind: "bad", text: errText(e, t("err.loadFailed")) }));
  useEffect(() => { refresh(); }, []);
  return [agents, refresh, error];
}

/* ---------- Memory: what a person's own agents know about them ----------
   A folder of notes all of their agents share (server.js, "a person's
   memory"): MEMORY.md is what every turn is shown, each other note a subject
   an agent opens when it needs it. Agents write it; this is where the person
   reads it, corrects it, deletes it and switches it off. Notes are forms
   (they have a Save button), the switch saves on change. */
const memDay = ms => { try { return new Date(ms).toLocaleDateString(L.lang() || undefined, { year: "numeric", month: "short", day: "numeric" }); } catch { return ""; } };
function MemoryNote({ note, onSaved, onDeleted, onClose }) {
  const [text, setText] = useState(null);
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState(null);
  useEffect(() => { L.MemoryAPI.read(note.path).then(r => setText(r.content)).catch(e => { setText(""); setMsg({ kind: "bad", text: errText(e, t("settings.memFailed")) }); }); }, [note.path]);
  const save = async () => { setBusy(true); setMsg(null); try { await L.MemoryAPI.write(note.path, text); onSaved(); } catch (e) { setMsg({ kind: "bad", text: errText(e, t("settings.memFailed")) }); } finally { setBusy(false); } };
  const del = async () => { setMsg(null); try { await L.MemoryAPI.remove(note.path); onDeleted(); } catch (e) { setMsg({ kind: "bad", text: errText(e, t("settings.memFailed")) }); } };
  return (
    <div className="mem-edit">
      {text === null ? <div className="set-empty">{t("common.loading")}</div>
        : <textarea className="mem-text" rows={Math.min(22, Math.max(6, text.split("\n").length + 1))} value={text} spellCheck="false" aria-label={note.path} onChange={e => setText(e.target.value)} />}
      <div className="set-row">
        <button className="btn primary" disabled={busy || text === null} onClick={save}>{t("settings.memNoteSave")}</button>
        <button className="btn" onClick={onClose}>{t("settings.memNoteClose")}</button>
        <span className="test-status" />
        <DeleteButton label={t("settings.memNoteDelete")} onConfirm={del} />
      </div>
      <Msg m={msg} />
    </div>
  );
}
function MemorySection() {
  const [d, setD] = useState(null);
  const [err, setErr] = useState(null);
  const [core, setCore] = useState("");
  const [coreBusy, setCoreBusy] = useState(false);
  const [coreSaved, flashCore] = useSaved();
  const [swSaved, flashSw] = useSaved();
  const [notesSaved, flashNotes] = useSaved();
  const [open, setOpen] = useState(null);
  const [adding, setAdding] = useState(false);
  const [draft, setDraft] = useState({ name: "", text: "" });
  const [msg, setMsg] = useState(null);
  const load = keepCore => L.MemoryAPI.get().then(r => { setD(r); setErr(null); if (!keepCore) setCore(r.core || ""); return r; })
    .catch(e => { setErr({ kind: "bad", text: errText(e, t("settings.memError")) }); setD(x => x || { available: true, enabled: true, core: "", files: [], limits: {} }); });
  useEffect(() => { load(); }, []);
  if (!d) return <Card title={t("settings.memTitle")} scope="account"><div className="set-empty">{t("common.loading")}</div></Card>;
  const fail = e => setMsg({ kind: "bad", text: errText(e, t("settings.memFailed")) });
  const setEnabled = async on => { setMsg(null); try { const r = await L.MemoryAPI.setEnabled(on); setD(x => ({ ...x, enabled: r.enabled })); flashSw(); } catch (e) { fail(e); } };
  const saveCore = async () => { setCoreBusy(true); setMsg(null); try { await L.MemoryAPI.write("MEMORY.md", core); flashCore(); await load(true); } catch (e) { fail(e); } finally { setCoreBusy(false); } };
  const addNote = async () => {
    setMsg(null);
    let name = draft.name.trim().replace(/^\/+/, "");
    if (name && !/\.(md|txt)$/i.test(name)) name += ".md";
    try { await L.MemoryAPI.write(name, draft.text); setDraft({ name: "", text: "" }); setAdding(false); flashNotes(); await load(true); } catch (e) { fail(e); }
  };
  const forget = async () => { setMsg(null); try { await L.MemoryAPI.clear(); setOpen(null); await load(); setMsg({ kind: "ok", text: t("settings.memForgot") }); } catch (e) { fail(e); } };
  const lim = d.limits || {};
  const coreLines = core ? core.replace(/\n+$/, "").split("\n").length : 0;
  const coreOver = (lim.coreLines && coreLines > lim.coreLines) || (lim.coreChars && core.length > lim.coreChars);
  const dirty = core !== (d.core || "");
  return (<>
    <Card title={t("settings.memTitle")} desc={t("settings.memDesc")} scope="account" saved={swSaved}>
      {!d.available ? <p className="set-foot-note">{t("settings.memUnavailable")}</p> : (
        <SwitchRow on={d.enabled} onChange={setEnabled} name={t("settings.memSwitch")} desc={t("settings.memSwitchDesc")} />
      )}
      <p className="set-foot-note">{t("settings.memWhere")}</p>
      <Msg m={err} />
    </Card>
    {d.available && (<>
      <Card title={t("settings.memCoreTitle")} desc={t("settings.memCoreDesc", { n: lim.coreLines || 200 })} scope="account" saved={coreSaved}>
        <textarea id="mem-core" className="mem-text" rows={Math.min(22, Math.max(6, coreLines + 2))} value={core} spellCheck="false"
                  aria-label={t("settings.memCoreTitle")} placeholder={t("settings.memCoreEmpty")} onChange={e => setCore(e.target.value)} />
        {coreOver && <p className="set-msg bad">{t("settings.memCoreOver", { n: lim.coreLines || 200 })}</p>}
        <div className="set-row">
          <button className="btn primary" disabled={coreBusy || !dirty} onClick={saveCore}>{t("settings.memCoreSave")}</button>
          {d.coreUpdated ? <span className="test-status">{t("settings.memUpdated", { date: memDay(d.coreUpdated) })}</span> : null}
        </div>
      </Card>
      <Card title={t("settings.memNotesTitle")} desc={t("settings.memNotesDesc")} scope="account" saved={notesSaved}>
        {d.files.length === 0 && !adding && <div className="set-empty">{t("settings.memNotesNone")}</div>}
        {d.files.length > 0 && (
          <div className="set-list mem-list">
            {d.files.map(f => (
              <React.Fragment key={f.path}>
                <button className={"set-item mem-item" + (open === f.path ? " on" : "")} aria-expanded={open === f.path} onClick={() => setOpen(open === f.path ? null : f.path)}>
                  <span className="set-item-name">{f.path}</span>
                  <span className="set-item-meta">{f.description}</span>
                  <span className="set-item-note">{t("settings.memUpdated", { date: memDay(f.updated) })}</span>
                </button>
                {open === f.path && (
                  <MemoryNote note={f} onClose={() => setOpen(null)}
                              onSaved={() => { flashNotes(); load(true); }}
                              onDeleted={() => { setOpen(null); flashNotes(); load(true); }} />
                )}
              </React.Fragment>
            ))}
          </div>
        )}
        {adding ? (
          <div className="mem-edit">
            <div className="field">
              <label htmlFor="mem-name">{t("settings.memNoteName")}</label>
              <input id="mem-name" value={draft.name} spellCheck="false" autoComplete="off" placeholder={t("settings.memNoteNameHint")} onChange={e => setDraft({ ...draft, name: e.target.value })} />
            </div>
            <div className="field">
              <label htmlFor="mem-new">{t("settings.memNoteText")}</label>
              <textarea id="mem-new" className="mem-text" rows="7" value={draft.text} spellCheck="false" placeholder={t("settings.memNoteFirstLine")} onChange={e => setDraft({ ...draft, text: e.target.value })} />
            </div>
            <div className="set-row">
              <button className="btn primary" disabled={!draft.name.trim() || !draft.text.trim()} onClick={addNote}>{t("settings.memNoteAdd")}</button>
              <button className="btn" onClick={() => setAdding(false)}>{t("common.cancel")}</button>
            </div>
          </div>
        ) : <div className="set-row"><button className="btn" onClick={() => { setAdding(true); setMsg(null); }}>+ {t("settings.memNoteNew")}</button></div>}
        <Msg m={msg} />
      </Card>
      <Card title={t("settings.memForget")} desc={t("settings.memForgetDesc")} scope="account">
        <div className="set-row"><DeleteButton label={t("settings.memForget")} onConfirm={forget} /></div>
      </Card>
    </>)}
  </>);
}

function MyAgentsSection({ isAdmin }) {
  const [agents, refresh, error] = useAgents();
  const [guide, setGuide] = useState(null);
  useEffect(() => { L.AgentsAPI.guidance().then(setGuide).catch(() => {}); }, []);
  if (!agents) return <Card title={t("settings.myAgentsTitle")}><div className="set-empty">{t("common.loading")}</div><Msg m={error} /></Card>;
  const mine = agents.filter(a => a.scope === "user");
  const ws = guide && (guide.workspace || "").trim();
  return (<>
    <AgentListCard title={t("settings.myAgentsTitle")} scope="account" agents={mine} limit={guide && guide.limit} isAdmin={isAdmin}
                   desc={t("settings.myAgentsDesc") + (L.moduleOn("brain") ? " " + t("settings.wikiMine") : "")}
                   empty={t("settings.wikiNoAgents")} onChanged={refresh} />
    {/* A rule you cannot see is a mystery: show what every agent is also told. */}
    {ws && (
      <Card title={t("settings.workspaceInstrTitle")} desc={t("settings.workspaceInstrReadonly")} scope="everyone">
        <pre className="set-pre">{guide.workspace}</pre>
        {isAdmin && <div className="set-foot-note"><a href="#all-agents">{t("settings.editInAllAgents")}</a></div>}
      </Card>
    )}
  </>);
}

function WorkspaceInstructionsCard() {
  const [g, setG] = useState(null);
  const [saved, flash] = useSaved();
  useEffect(() => { L.AgentsAPI.guidance().then(setG).catch(() => setG({ workspace: "", limit: 8000 })); }, []);
  return (
    <Card title={t("settings.workspaceInstrTitle")} desc={t("settings.workspaceInstrDesc")} scope="everyone" saved={saved}>
      {!g ? <div className="set-empty">{t("common.loading")}</div> : (<>
        {g.deployment && g.deployment.trim() && (
          <details className="set-adv set-dep">
            <summary>{t("settings.deploymentInstr")}</summary>
            <pre className="set-pre">{g.deployment}</pre>
          </details>
        )}
        <InstructionsEditor value={g.workspace || ""} limit={g.limit}
                            placeholder={t("settings.workspaceInstrPlaceholder")}
                            onSave={async text => { const r = await L.AgentsAPI.setGuidance(text); setG(x => ({ ...x, workspace: r.workspace })); flash(); }} />
        <div className="set-foot-note">{t("settings.promptOrder")}</div>
        <PromptToggle label={t("settings.promptShowEvery")}>
          {() => <SystemPromptView load={() => L.AgentsAPI.guidancePreview()} reloadKey={g.workspace || ""} editHere="workspace" isAdmin />}
        </PromptToggle>
      </>)}
    </Card>
  );
}

/* Whether members see the engine and model menus on their agents. Off by
   default: the default above is the recommended one, and a long model list
   was one more thing a first-time user could not place. */
/* Agent bundles (server.js, bundles.js): the ready-made agents people can add
   from the start page and New. An admin decides which are offered here; one
   switched off is not offered to anyone, and agents already made from it stay. */
function BundlesCard() {
  const [list, setList] = useState(null);
  const [saved, flash] = useSaved();
  const [msg, setMsg] = useState(null);
  const bl = v => (v == null ? "" : typeof v === "string" ? v : (v[L.lang()] || v.en || ""));
  useEffect(() => { L.BundlesAPI.list().then(d => setList(d.bundles || [])).catch(e => setMsg({ kind: "bad", text: errText(e, t("err.loadFailed")) })); }, []);
  const change = async (b, v) => {
    setList(xs => xs.map(x => x.key === b.key ? { ...x, offered: v } : x));
    try { await L.BundlesAPI.setOffered(b.key, v); flash(); setMsg(null); }
    catch (e) { setList(xs => xs.map(x => x.key === b.key ? { ...x, offered: !v } : x)); setMsg({ kind: "bad", text: t("settings.switchFailed") + " " + errText(e, "error") }); }
  };
  return (
    <Card title={t("settings.bundlesTitle")} desc={t("settings.bundlesDesc")} scope="everyone" saved={saved}>
      {!list && !msg && <div className="set-empty">{t("common.loading")}</div>}
      {list && !list.length && <div className="set-empty">{t("settings.bundlesNone")}</div>}
      {(list || []).map(b => (
        <SwitchRow key={b.key} on={b.offered} onChange={v => change(b, v)}
                   name={b.icon + " " + bl(b.name) + " " + b.version}
                   desc={bl(b.summary) + " " + t("settings.bundlesUses", { n: b.uses || 0 }) + (b.origin === "config" ? " " + t("settings.bundlesFromConfig") : "")} />
      ))}
      <Msg m={msg} />
    </Card>
  );
}

function ModelChoiceCard() {
  const [on, setOn] = useState(L.membersPickModels());
  const [saved, flash] = useSaved();
  const [msg, setMsg] = useState(null);
  useEffect(() => { L.loadConfig().then(() => setOn(L.membersPickModels())); }, []);
  const change = async v => {
    setOn(v);
    try { await L.AgentsAPI.setModelChoice(v); await L.loadConfig(); flash(); setMsg(null); }
    catch (e) { setOn(!v); setMsg({ kind: "bad", text: t("settings.switchFailed") + " " + errText(e, "error") }); }
  };
  return (
    <Card title={t("settings.modelChoiceTitle")} desc={t("settings.modelChoiceDesc")} scope="everyone" saved={saved}>
      <SwitchRow on={on} onChange={change} name={t("settings.modelChoiceName")} desc={t("settings.modelChoiceSub")} />
      <Msg m={msg} />
    </Card>
  );
}

/* The deployment's models in order of priority (server.js, model priority).
   Priority 1 is the default every agent follows; when the model an agent
   runs on says nothing for the wait below, the app tests the others and
   offers the first that answers. Each entry can be tested here first, and
   may say its window: a gateway serves models of every size behind one
   engine, and a conversation that outgrows one is offered the next with a
   larger window. */
function ModelPriorityCard() {
  const [data, setData] = useState(null);         /* { list, waitSec, engines } */
  const [models, setModels] = useState({});       /* base -> [{ id, label }] */
  const [tests, setTests] = useState({});         /* entry key -> "pending" | probe result */
  const [add, setAdd] = useState("");
  const [wait, setWait] = useState("");
  const [msg, setMsg] = useState(null);
  const [saved, flash] = useSaved();
  useEffect(() => {
    L.ModelPriorityAPI.get().then(d => {
      setData(d); setWait(String(d.waitSec));
      for (const e of d.engines || []) if (e.base) L.loadModelsForBase(e.base).then(m => setModels(x => ({ ...x, [e.base]: m || [] }))).catch(() => {});
    }).catch(e => setMsg({ kind: "bad", text: errText(e, t("settings.switchFailed")) }));
  }, []);
  const k = e => e.backend + "\u0001" + e.model;
  const nameOf = e => {
    const base = ((data && data.engines) || []).find(x => x.key === e.backend);
    const m = ((base && models[base.base]) || []).find(x => L.sameModel(x.id, e.model)) || L.findModel(e.model);
    return (m && m.label) || e.model;
  };
  const save = async list => {
    try { const r = await L.ModelPriorityAPI.save({ list: list.map(e => ({ backend: e.backend, model: e.model, contextWindow: e.contextWindow || null, maxTokens: e.maxTokens || null })) }); setData(d => ({ ...d, list: r.list })); flash(); setMsg(null); }
    catch (e) { setMsg({ kind: "bad", text: errText(e, t("settings.switchFailed")) }); }
  };
  const move = (i, d) => { const l = data.list.slice(), j = i + d; if (j < 0 || j >= l.length) return; [l[i], l[j]] = [l[j], l[i]]; save(l); };
  /* empty = the engine's own figure */
  const setWindow = (i, v) => {
    const n = String(v).trim() === "" ? null : Math.round(Number(v));
    if (n === (data.list[i].contextWindow || null)) return;
    save(data.list.map((e, x) => x === i ? { ...e, contextWindow: n } : e));
  };
  const test = async e => {
    setTests(x => ({ ...x, [k(e)]: "pending" }));
    try { const r = await L.ModelPriorityAPI.test(e); setTests(x => ({ ...x, [k(e)]: r })); }
    catch (er) { setTests(x => ({ ...x, [k(e)]: { ok: false, error: errText(er, "error") } })); }
  };
  const saveWait = async () => {
    const n = Number(wait);
    if (!data || n === data.waitSec) return;
    try { const r = await L.ModelPriorityAPI.save({ waitSec: n }); setData(d => ({ ...d, waitSec: r.waitSec })); setWait(String(r.waitSec)); flash(); setMsg(null); L.loadConfig(); }
    catch (e) { setWait(String(data.waitSec)); setMsg({ kind: "bad", text: errText(e, t("settings.switchFailed")) }); }
  };
  if (!data) return <Card title={t("settings.priorityTitle")} desc={t("settings.priorityDesc")} scope="everyone"><div className="set-empty">{t("common.loading")}</div></Card>;
  /* what may still be added: each engine's own model and the ones its provider serves */
  const listed = new Set(data.list.map(k));
  const choices = [];
  for (const en of data.engines || []) {
    const ids = [en.model, ...((models[en.base] || []).map(m => m.id).filter(id => !L.sameModel(id, en.model)))];
    const opts = ids.map(id => ({ backend: en.key, model: id })).filter(e => !listed.has(k(e)));
    if (opts.length) choices.push({ en, opts });
  }
  return (
    <Card title={t("settings.priorityTitle")} desc={t("settings.priorityDesc")} scope="everyone" saved={saved}>
      <div className="set-list">
        {data.list.map((e, i) => {
          const r = tests[k(e)];
          return (
            <div className="set-item prio-item" key={k(e)}>
              <span className="prio-n">{i + 1}</span>
              <span className="set-item-name" title={e.model}>{nameOf(e)}</span>
              <span className="set-item-meta">{e.backendLabel}{i === 0 ? " · " + t("settings.priorityFirst") : ""}</span>
              <input className="prio-win" type="number" min="1024" step="1024" inputMode="numeric" key={k(e) + ":" + (e.contextWindow || "")}
                     defaultValue={e.contextWindow || ""} placeholder={e.window ? L.fmtNum(e.window) : t("settings.priorityWindowPh")}
                     title={t("settings.priorityWindowHint")} aria-label={t("settings.priorityWindow")}
                     onBlur={ev => setWindow(i, ev.target.value)} onKeyDown={ev => { if (ev.key === "Enter") ev.target.blur(); }} />
              {r && <span className={"prio-test " + (r === "pending" ? "" : r.ok ? "ok" : "bad")} title={r !== "pending" && !r.ok ? (r.timeout ? t("model.hintTimeout", { n: r.timeout }) : r.error) : ""}>
                {r === "pending" ? t("settings.priorityTesting") : r.ok ? t("settings.priorityOk", { ms: r.ms }) : t("settings.priorityFail")}</span>}
              <button className="mini" onClick={() => test(e)} disabled={r === "pending"}>{t("settings.priorityTest")}</button>
              <button className="mini" onClick={() => move(i, -1)} disabled={i === 0} title={t("settings.priorityUp")} aria-label={t("settings.priorityUp")}>↑</button>
              <button className="mini" onClick={() => move(i, 1)} disabled={i === data.list.length - 1} title={t("settings.priorityDown")} aria-label={t("settings.priorityDown")}>↓</button>
              {data.list.length > 1 && <DeleteButton onConfirm={() => save(data.list.filter((_, x) => x !== i))} />}
            </div>
          );
        })}
      </div>
      <div className="set-foot-note">{t("settings.priorityWindowNote")}</div>
      {choices.length > 0 && (
        <div className="set-add prio-add">
          <select className="adm-select" value={add} onChange={e => setAdd(e.target.value)} aria-label={t("settings.priorityAdd")}>
            <option value="">{t("settings.priorityAddPick")}</option>
            {choices.map(c => (
              <optgroup key={c.en.key} label={c.en.label}>
                {c.opts.map(e => <option key={k(e)} value={k(e)}>{nameOf(e)}</option>)}
              </optgroup>
            ))}
          </select>
          <button className="btn" disabled={!add} onClick={() => { const [backend, model] = add.split("\u0001"); setAdd(""); save([...data.list, { backend, model }]); }}>{t("settings.priorityAdd")}</button>
        </div>
      )}
      <div className="prio-wait">
        <label htmlFor="prio-wait">{t("settings.priorityWait")}</label>
        <input id="prio-wait" type="number" min="15" max="900" step="5" value={wait} onChange={e => setWait(e.target.value)}
               onBlur={saveWait} onKeyDown={e => { if (e.key === "Enter") e.target.blur(); }} />
        <span>{t("settings.priorityWaitUnit")}</span>
      </div>
      <Msg m={msg} />
    </Card>
  );
}

function AllAgentsSection() {
  const [eg, setEg] = useState({ current: null, options: [] });
  const [egSaved, egFlash] = useSaved();
  const [msg, setMsg] = useState(null);
  const [agents, refresh] = useAgents();
  const [limit, setLimit] = useState(8000);
  /* reach: undefined = not asked, "pending" = asking, then the probe's answer */
  const checkReach = fresh => {
    setEg(x => ({ ...x, reach: "pending" }));
    L.AgentsAPI.egressReach(fresh).then(r => setEg(x => ({ ...x, reach: r.reach }))).catch(() => setEg(x => ({ ...x, reach: undefined })));
  };
  useEffect(() => {
    L.AgentsAPI.egress().then(e => { setEg(e); if (e.current && e.current !== "open") checkReach(false); }).catch(() => {});
    L.AgentsAPI.guidance().then(g => setLimit(g.limit || 8000)).catch(() => {});
  }, []);
  const pickEg = async key => {
    const prev = eg.current; setEg(x => ({ ...x, current: key }));
    try {
      await L.AgentsAPI.setEgress(key); egFlash(); setMsg(null);
      if (key !== "open") checkReach(true); else setEg(x => ({ ...x, reach: undefined }));
    }
    catch (e) { setEg(x => ({ ...x, current: prev })); setMsg({ kind: "bad", text: t("settings.switchFailed") + " " + errText(e, "error") }); }
  };
  const shared = (agents || []).filter(a => a.scope === "global");
  return (<>
    <WorkspaceInstructionsCard />
    <ModelPriorityCard />
    <ModelChoiceCard />
    <BundlesCard />
    <Card title={t("settings.egressTitle")} desc={t("settings.egressDesc")} scope="everyone" saved={egSaved}>
      <div className="set-radios">
        {(eg.options || []).map(o => (
          <label key={o.key} className={"set-radio" + (eg.current === o.key ? " on" : "")}>
            <input type="radio" name="agent-egress" checked={eg.current === o.key} onChange={() => pickEg(o.key)} />
            <span className="set-radio-text">{["open", "search", "off"].includes(o.key) ? t("egress." + o.key) : o.label}</span>
          </label>
        ))}
      </div>
      {/* Whether turns on this network can reach this server at all: on a
          restricted tier the model and every app tool go through it. */}
      {eg.current && eg.current !== "open" && eg.reach === "pending" && (
        <div className="set-reach-pending">{t("settings.egressChecking")}</div>
      )}
      {eg.current && eg.current !== "open" && eg.reach && eg.reach.ok === false && (
        <div className="set-callout bad">{tb("settings.egressReachBad", { url: eg.reach.url })}</div>
      )}
      {eg.current && eg.current !== "open" && eg.reach && eg.reach.ok === true && (
        <div className="set-reach-ok">{t("settings.egressReachOk")}</div>
      )}
      {eg.current && eg.current !== "open" && (
        <div className="set-foot-note">{tb("settings.egressNote", { network: eg.network, subnet: eg.subnet || t("settings.subnetAuto") })}</div>
      )}
    </Card>
    <Msg m={msg} />
    {shared.length > 0 && (
      <AgentListCard title={t("settings.sharedAgentsTitle")} desc={t("settings.sharedAgentsDesc")} scope="everyone"
                     agents={shared} limit={limit} empty="" onChanged={refresh} isAdmin />
    )}
  </>);
}

/* ========================================================
   WORKSPACE (admin)
   ======================================================== */
const ROLES = ["owner", "admin", "member", "viewer"];
function UserEditor({ user, onClose, onSaved }) {
  const isNew = user === "new";
  const [v, setV] = useState(isNew ? { name: "", email: "", role: "member", password: "" } : { name: user.name, email: user.email, role: user.role, status: user.status });
  const [msg, setMsg] = useState(null);
  const [busy, setBusy] = useState(false);
  const set = (k, val) => setV(s => ({ ...s, [k]: val }));
  const save = async e => {
    e.preventDefault(); setBusy(true); setMsg(null);
    try {
      if (isNew) {
        if ((v.password || "").length < 6) throw new Error(t("settings.passwordShort"));
        await L.AdminUsersAPI.create(v);
      } else await L.AdminUsersAPI.update(user.id, v);
      onSaved();
    } catch (err) { setMsg({ kind: "bad", text: errText(err, t("err.updateFailed")) }); setBusy(false); }
  };
  return (
    <div className="modal-scrim" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <form className="modal" onSubmit={save}>
        <div className="modal-head">
          <div><span className="eb">{t("settings.nav.users")}</span><h2>{isNew ? t("admin.addUser") : t("admin.editUser")}</h2></div>
          <button type="button" className="modal-x" onClick={onClose} aria-label={t("common.cancel")}>✕</button>
        </div>
        <div className="modal-body">
          <div className="field"><label htmlFor="u-name">{t("auth.name")}</label>
            <input id="u-name" value={v.name} onChange={e => set("name", e.target.value)} placeholder="Jane Doe" autoFocus /></div>
          <div className="field"><label htmlFor="u-email">{t("admin.email")}</label>
            <input id="u-email" type="email" value={v.email} onChange={e => set("email", e.target.value)} placeholder="jane@example.com" spellCheck="false" /></div>
          <div className="set-2col">
            <div className="field"><label htmlFor="u-role">{t("admin.role")}</label>
              <select id="u-role" value={v.role} onChange={e => set("role", e.target.value)}>
                {ROLES.map(r => <option key={r} value={r}>{t("role." + r)}</option>)}
              </select></div>
            {isNew ? (
              <div className="field"><label htmlFor="u-pw">{t("settings.initialPassword")}</label>
                <input id="u-pw" type="text" value={v.password} onChange={e => set("password", e.target.value)} spellCheck="false" autoComplete="off" /></div>
            ) : (
              <div className="field"><label htmlFor="u-status">{t("admin.status")}</label>
                <select id="u-status" value={v.status} onChange={e => set("status", e.target.value)}>
                  {["active", "pending", "disabled"].map(s => <option key={s} value={s}>{t("status." + s)}</option>)}
                </select></div>
            )}
          </div>
          <div className="help">{t("settings.roleHelp")}</div>
        </div>
        <div className="modal-foot">
          <Msg m={msg} />
          <button type="button" className="btn" onClick={onClose}>{t("common.cancel")}</button>
          <button type="submit" className="btn primary" disabled={busy || !v.name || !v.email}>{t("common.save")}</button>
        </div>
      </form>
    </div>
  );
}

function PasswordReset({ user, onClose, onDone }) {
  const [pw, setPw] = useState("");
  const [msg, setMsg] = useState(null);
  const [busy, setBusy] = useState(false);
  const go = async e => {
    e.preventDefault();
    if (pw.length < 6) return setMsg({ kind: "bad", text: t("settings.passwordShort") });
    setBusy(true);
    try { await L.AdminUsersAPI.update(user.id, { password: pw }); onDone(); }
    catch (err) { setMsg({ kind: "bad", text: errText(err, t("err.updateFailed")) }); setBusy(false); }
  };
  return (
    <div className="modal-scrim" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <form className="modal" onSubmit={go}>
        <div className="modal-head">
          <div><span className="eb">{user.email}</span><h2>{t("settings.resetPasswordFor", { name: user.name })}</h2></div>
          <button type="button" className="modal-x" onClick={onClose} aria-label={t("common.cancel")}>✕</button>
        </div>
        <div className="modal-body">
          <div className="field"><label htmlFor="rp">{t("settings.newPassword")}</label>
            <input id="rp" type="text" value={pw} onChange={e => setPw(e.target.value)} autoFocus spellCheck="false" autoComplete="off" /></div>
          <div className="help">{t("settings.resetPasswordHelp")}</div>
        </div>
        <div className="modal-foot">
          <Msg m={msg} />
          <button type="button" className="btn" onClick={onClose}>{t("common.cancel")}</button>
          <button type="submit" className="btn primary" disabled={busy || !pw}>{t("settings.resetPassword")}</button>
        </div>
      </form>
    </div>
  );
}

function UsersSection({ me, onPendingChange }) {
  const [rows, setRows] = useState(null);
  const [edit, setEdit] = useState(null);
  const [reset, setReset] = useState(null);
  const [msg, setMsg] = useState(null);
  const load = () => L.AdminUsersAPI.list().then(r => { setRows(r); onPendingChange && onPendingChange(r.filter(u => pending(u.status)).length); })
                                          .catch(e => setMsg({ kind: "bad", text: errText(e, t("err.loadFailed")) }));
  useEffect(() => { load(); }, []);
  const pending = s => s === "pending" || s === "invited";
  const approve = async u => { try { await L.AdminUsersAPI.update(u.id, { status: "active" }); setMsg({ kind: "ok", text: t("settings.userApproved", { name: u.name }) }); load(); } catch (e) { setMsg({ kind: "bad", text: errText(e, t("err.updateFailed")) }); } };
  const remove = async u => { try { await L.AdminUsersAPI.delete(u.id); setMsg(null); load(); } catch (e) { setMsg({ kind: "bad", text: errText(e, t("err.removeFailed")) }); } };
  const chip = s => s === "active" ? "green" : pending(s) ? "terra" : "gray";
  const label = (p, k) => { const v = t(p + k); return v === p + k ? k : v; };

  if (!rows) return <Card title={t("admin.users")}><div className="set-empty">{t("admin.loadingUsers")}</div><Msg m={msg} /></Card>;
  const waiting = rows.filter(u => pending(u.status));
  /* Waiting people first: they are the reason to open this page. */
  const sorted = [...waiting, ...rows.filter(u => !pending(u.status))];

  return (<>
    <Card title={t("settings.accountsTitle")} desc={t("settings.usersDesc")} scope="everyone">
      {waiting.length > 0 && <div className="set-callout">{t("settings.pendingApproval", { n: waiting.length })}</div>}
      <div className="set-users">
        {sorted.map(u => (
          <div className={"set-user" + (pending(u.status) ? " waiting" : "")} key={u.id}>
            <span className="set-avatar sm">{initialsOf(u.name)}</span>
            <div className="set-user-id">
              <div className="set-user-name">{u.name}{u.id === me.id && <span className="set-you">{t("settings.you")}</span>}</div>
              <div className="set-user-meta">
                <span className="set-user-email">{u.email}</span>
                <span className="set-user-role">{label("role.", u.role)}</span>
                {u.authSource === "box" && <span className="set-user-role" title={t("settings.userViaBoxHint")}>{t("settings.userViaBox")}</span>}
                {u.authSource === "control" && <span className="set-user-role" title={t("settings.userViaControlHint", { name: u.via || "" })}>{t("settings.userViaControl", { name: u.via || "" })}</span>}
                <span className={"tag-chip " + chip(u.status)}><span className="sq" />{label("status.", u.status)}</span>
              </div>
            </div>
            <div className="row-acts">
              {pending(u.status) && <button className="mini approve" onClick={() => approve(u)}>{t("admin.approve")}</button>}
              <button className="mini" onClick={() => setEdit(u)}>{t("common.edit")}</button>
              {u.id !== me.id && <button className="mini" onClick={() => setReset(u)}>{t("settings.resetPassword")}</button>}
              {u.id !== me.id && <DeleteButton onConfirm={() => remove(u)} />}
            </div>
          </div>
        ))}
      </div>
      <div className="set-row">
        <Msg m={msg} />
        <button className="btn primary" onClick={() => setEdit("new")}>+ {t("admin.addUser")}</button>
      </div>
      <div className="set-foot-note">{t("settings.removeUserNote")}</div>
    </Card>
    {/* the admin's setup (onboarding.jsx): the name, the model, development passwords, mail, people, ready-made agents */}
    <Card title={t("settings.setupTitle")} desc={t("settings.setupDesc")} scope="everyone">
      <button className="btn" onClick={() => L.OnboardingAPI.updateAdmin({ done: false }).then(() => { location.href = "/"; }).catch(() => {})}>{t("settings.setupAgain")}</button>
    </Card>
    {edit && <UserEditor user={edit} onClose={() => setEdit(null)} onSaved={() => { setEdit(null); load(); }} />}
    {reset && <PasswordReset user={reset} onClose={() => setReset(null)}
                             onDone={() => { setMsg({ kind: "ok", text: t("settings.passwordReset", { name: reset.name }) }); setReset(null); }} />}
  </>);
}

function BrandingSection() {
  const [saved0] = useState(() => ({ ...L.BRAND }));
  const [brand, setBrand] = useState(() => ({ ...L.BRAND }));
  const [base, setBase] = useState(() => ({ ...L.BRAND }));
  const [msg, setMsg] = useState(null);
  useEffect(() => { L.loadBranding().then(b => { setBrand({ ...b }); setBase({ ...b }); }); }, []);
  /* Revert an unsaved live preview when you leave the section. */
  useEffect(() => () => { L.applyBranding(L.getJSON("indie.brand", saved0) || saved0); }, []);
  const apply = b => { L.applyBranding(b); retitle("branding"); };
  const update = patch => { const next = { ...brand, ...patch }; setBrand(next); apply(next); };
  const dirty = ["brandName", "tagline", "accent", "logoUrl"].some(k => (brand[k] || "") !== (base[k] || ""));
  const save = async () => {
    try { const s = await L.BrandingAPI.save(brand); apply(s); L.setJSON("indie.brand", s); setBase({ ...s }); setMsg({ kind: "ok", text: t("settings.brandSaved") }); }
    catch (e) { setMsg({ kind: "bad", text: errText(e, t("settings.brandSaveFailed")) }); }
  };
  const discard = () => { setBrand({ ...base }); apply(base); setMsg(null); };
  const accentVal = /^#[0-9a-fA-F]{6}$/.test(brand.accent || "") ? brand.accent : "#c2562d";

  return (
    <>
    <Card title={t("settings.brandingTitle")} desc={t("settings.brandingDesc")} scope="everyone">
      <div className="set-2col">
        <div className="field"><label htmlFor="b-name">{t("settings.productName")}</label>
          <input id="b-name" value={brand.brandName || ""} onChange={e => update({ brandName: e.target.value })} placeholder="indie.chat" spellCheck="false" /></div>
        <div className="field"><label htmlFor="b-tag">{t("settings.tagline")}</label>
          <input id="b-tag" value={brand.tagline || ""} onChange={e => update({ tagline: e.target.value })} placeholder="Private · Indie Models" spellCheck="false" /></div>
      </div>
      <div className="set-2col">
        <div className="field"><label htmlFor="b-acc">{t("settings.accent")}</label>
          <div className="brand-accent-row">
            <input type="color" className="brand-swatch" value={accentVal} onChange={e => update({ accent: e.target.value })} aria-label={t("settings.accent")} />
            <input id="b-acc" value={brand.accent || ""} onChange={e => update({ accent: e.target.value })} placeholder="#c2562d" spellCheck="false" />
          </div></div>
        <div className="field"><label htmlFor="b-logo">{t("settings.logoUrl")}</label>
          <input id="b-logo" value={brand.logoUrl || ""} onChange={e => update({ logoUrl: e.target.value })} placeholder="/icons/logo.png  ·  https://…" spellCheck="false" /></div>
      </div>
      <div className="set-row">
        <Msg m={msg || (dirty ? { kind: "run", text: t("settings.brandPreviewing") } : null)} />
        {dirty && <button className="btn" onClick={discard}>{t("settings.discard")}</button>}
        <button className="btn primary" onClick={save} disabled={!dirty}>{t("settings.saveBranding")}</button>
      </div>
    </Card>
    <OfficeTemplates />
    </>
  );
}

/* The deployment's templates for the documents agents make (server.js,
   office templates): new Word, PowerPoint and Excel files start from them.
   Without one, agents use the brand name and accent above. */
const OFFICE_KINDS = [["docx", "Word"], ["pptx", "PowerPoint"], ["xlsx", "Excel"]];
const fmtBytes = n => n < 1024 * 1024 ? Math.max(1, Math.round(n / 1024)) + " KB" : (n / (1024 * 1024)).toFixed(1) + " MB";
function OfficeTemplates() {
  const [tpl, setTpl] = useState(null);           /* null: loading, not empty */
  const [busy, setBusy] = useState(null);         /* the kind being uploaded */
  const [msg, setMsg] = useState(null);
  const [saved, setSaved] = useState(false);
  const inputs = useRef({});
  const load = () => L.OfficeTemplatesAPI.list().then(r => setTpl(r.templates || {}))
    .catch(e => { setTpl({}); setMsg({ kind: "bad", text: errText(e, t("settings.officeFailed")) }); });
  useEffect(() => { load(); }, []);
  const flash = () => { setSaved(true); setTimeout(() => setSaved(false), 1600); };
  const upload = async (kind, file) => {
    if (!file) return;
    setBusy(kind); setMsg(null);
    try { await L.OfficeTemplatesAPI.upload(kind, file); flash(); load(); }
    catch (e) {
      const text = e && e.code === "template-format" ? t("settings.officeTemplateFormat", { kind })
        : e && e.code === "wrong-type" ? t("settings.officeWrongType", { kind }) : errText(e, t("settings.officeFailed"));
      setMsg({ kind: "bad", text });
    }
    finally { setBusy(null); }
  };
  const remove = async kind => {
    setMsg(null);
    try { await L.OfficeTemplatesAPI.remove(kind); flash(); load(); }
    catch (e) { setMsg({ kind: "bad", text: errText(e, t("settings.officeFailed")) }); }
  };
  return (
    <Card title={t("settings.officeTitle")} desc={t("settings.officeDesc")} scope="everyone" saved={saved}>
      {tpl === null ? <div className="set-empty">{t("common.loading")}</div> : (
        <div className="set-list">
          {OFFICE_KINDS.map(([kind, label]) => {
            const cur = tpl[kind];
            return (
              <div className="set-item" key={kind}>
                <span className="set-item-name">{label}</span>
                <span className="set-item-meta" title={cur ? cur.name : ""}>{cur ? cur.name + " · " + fmtBytes(cur.size) : t("settings.officeNone")}</span>
                {cur && <button className="mini" onClick={() => L.OfficeTemplatesAPI.download(kind, cur.name).catch(e => setMsg({ kind: "bad", text: errText(e, t("settings.officeFailed")) }))}>{t("common.download")}</button>}
                <button className="mini" disabled={busy === kind} onClick={() => inputs.current[kind] && inputs.current[kind].click()}>
                  {busy === kind ? t("settings.officeUploading") : cur ? t("settings.officeReplace") : t("settings.officeUpload")}
                </button>
                <input type="file" hidden accept={"." + kind} ref={el => { inputs.current[kind] = el; }}
                       onChange={e => { upload(kind, e.target.files && e.target.files[0]); e.target.value = ""; }} />
                {cur && <DeleteButton onConfirm={() => remove(kind)} />}
              </div>
            );
          })}
        </div>
      )}
      <Msg m={msg} />
    </Card>
  );
}

/* ========================================================
   THE PAGE
   ======================================================== */
function Settings({ me }) {
  const isAdmin = ["owner", "admin"].includes(me.role);
  const [cfgV, setCfgV] = useState(0);
  const list = sectionList(isAdmin);
  const [sec, setSec] = useState(() => fromHash(list));
  const [pending, setPending] = useState(0);

  /* Modules and providers can have changed since the cache was written. */
  useEffect(() => { L.loadConfig().then(() => setCfgV(v => v + 1)); }, []);
  useEffect(() => {
    const onHash = () => setSec(fromHash(sectionList(isAdmin)));
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, [isAdmin]);
  /* The pending-approval count belongs in the nav even before Users is opened. */
  useEffect(() => {
    if (!isAdmin) return;
    L.AdminUsersAPI.list().then(r => setPending(r.filter(u => u.status === "pending" || u.status === "invited").length)).catch(() => {});
  }, [isAdmin]);
  useEffect(() => { retitle(sec); }, [sec]);
  /* On a phone the nav is a horizontal strip, and the current section can sit
     off its edge; bring it into view. ("nearest" moves nothing that is already
     visible, so the desktop column never jumps.) */
  useEffect(() => {
    const el = document.querySelector(".set-nav-item.on");
    if (el && el.scrollIntoView) el.scrollIntoView({ block: "nearest", inline: "nearest" });
  }, [sec]);
  const go = id => { if (location.hash !== "#" + id) history.replaceState(null, "", "#" + id); setSec(id); window.scrollTo(0, 0);
                     const w = document.querySelector(".set-main"); if (w) w.scrollTop = 0; };

  const navItem = s => (
    <button key={s.id} className={"set-nav-item" + (sec === s.id ? " on" : "")} onClick={() => go(s.id)}
            aria-current={sec === s.id ? "page" : undefined}>
      {ICONS[s.id]}<span>{sectionLabel(s.id)}</span>
      {s.id === "users" && pending > 0 && <span className="set-badge" title={t("settings.pendingApproval", { n: pending })}>{pending}</span>}
    </button>
  );

  return (
    <div className="admin set-page">
      <div className="admin-top">
        <div className="logo" />
        <div className="admin-brand">
          <span className="nm"><BrandName /></span>
          <span className="tag">{t("nav.settings")}</span>
        </div>
        <a className="back" href="/indie.chat.html">← {t("nav.backToChat")}</a>
      </div>

      <div className="set-body">
        <nav className="set-nav" aria-label={t("nav.settings")}>
          <div className="set-nav-group">{t("settings.group.you")}</div>
          {list.filter(s => s.group === "you").map(navItem)}
          {isAdmin && <div className="set-nav-group">{t("settings.group.workspace")}</div>}
          {list.filter(s => s.group === "ws").map(navItem)}
          <div className="set-nav-hint">{t("settings.autosave")}</div>
        </nav>

        <main className="set-main">
          <div className="set-inner" key={sec + ":" + cfgV}>
            <h1 className="set-h1">{sectionLabel(sec)}</h1>
            <p className="set-lead">{t("settings.lead." + sec)}</p>
            {sec === "account"      && <AccountSection me={me} />}
            {sec === "preferences"  && <PreferencesSection />}
            {sec === "models"       && <ModelsSection />}
            {sec === "tools"        && <ChatToolsSection />}
            {sec === "integrations" && <IntegrationsSection isAdmin={isAdmin} />}
            {sec === "memory"       && <MemorySection />}
            {sec === "my-agents"    && <MyAgentsSection isAdmin={isAdmin} />}
            {sec === "users"        && <UsersSection me={me} onPendingChange={setPending} />}
            {sec === "all-agents"   && <AllAgentsSection />}
            {sec === "branding"     && <BrandingSection />}
          </div>
        </main>
      </div>
    </div>
  );
}

/* The wordmark follows the deployment's brand, like the chat page's. Accent the
   separator and everything after it, accepting ':' as well as '.'. */
function BrandName() {
  const n = (L.BRAND && L.BRAND.brandName) || "indie.chat";
  const i = n.search(/[.:]/);
  if (i < 0) return n;
  return <React.Fragment>{n.slice(0, i)}<b>{n.slice(i)}</b></React.Fragment>;
}

/* Re-mount on a language switch, so the page the switcher lives on is itself
   translated the moment you press it — see Root() in indie-app.jsx. */
function SettingsRoot({ me }) {
  const [lang, setLang] = React.useState(L.lang());
  React.useEffect(() => {
    const onLang = e => setLang(e.detail);
    window.addEventListener("indie:lang", onLang);
    return () => window.removeEventListener("indie:lang", onLang);
  }, []);
  return <React.Fragment key={lang}><Settings me={me} /></React.Fragment>;
}

/* Auth gate: bounce to login if not signed in. */
L.Auth.me().then(u => {
  if (!u) { location.href = "/indie.chat.html"; return; }
  ReactDOM.createRoot(document.getElementById("root")).render(<SettingsRoot me={u} />);
}).catch(() => { location.href = "/indie.chat.html"; });
