/* ===========================================================
   The Connections dialog (server.js, connectors per agent), shared by
   the app (an agent's Connections) and Settings. Loaded before both
   pages' own scripts. Wrapped, because every text/babel script runs as a
   classic script in ONE global scope: a second top-level `const
   useState` would stop the page. Exposed as window.IndieConn.
   =========================================================== */
(() => {
const { useState, useEffect, useRef } = React;

const FilesIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M4 7a2 2 0 0 1 2-2h4l2 2h6a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z" />
  </svg>
);

/* a service whose name is not a product's is shown in the reader's language */
const SERVICE_NAME_KEY = { imap_mail: "conn.name.imap_mail" };
const serviceName = (key, name) => (SERVICE_NAME_KEY[key] ? t(SERVICE_NAME_KEY[key]) : name);

/* ---- connections of an agent (server.js, connectors per agent) ----
   What an agent may use beyond its own folder, added one by one: a catalog
   (the services that run in the app, Google's and Microsoft's, and the
   connections an admin set up) with search and groups and the details on a
   click, then which account it acts as and how far it may go. Taken from the
   agent studio's "add a connection". */
const MailIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <rect x="3" y="5" width="18" height="14" rx="2" /><path d="M3.5 6.5l8.5 6.5 8.5-6.5" />
  </svg>
);
const CalendarIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <rect x="3.5" y="5" width="17" height="15" rx="2" /><path d="M3.5 9.5h17M8 3v4M16 3v4" />
  </svg>
);
const ChatBubbleIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M4 5.5h16v10H10l-4.5 3.5V15.5H4z" /><path d="M8 9.5h8M8 12.5h5" />
  </svg>
);
const PlugIcon = () => (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
    <path d="M9 7V3M15 7V3M6 7h12v4a6 6 0 0 1-12 0z" /><path d="M12 17v4" />
  </svg>
);
const CONN_GROUPS = ["mail", "files", "calendar", "messenger", "crm", "search", "other"];
const CONN_ACCESS = ["read", "ask", "write"];
const ConnGlyph = ({ group }) => (
  <span className={"conn-glyph g-" + (CONN_GROUPS.includes(group) ? group : "other")}>
    {group === "mail" ? <MailIcon /> : group === "files" ? <FilesIcon /> : group === "calendar" ? <CalendarIcon /> : group === "messenger" ? <ChatBubbleIcon /> : <PlugIcon />}
  </span>
);
/* whose account: "yours", "the workspace's", "everyone's" */
const ownerWord = (acc, wsName) => acc.owner === "person" ? t("conn.ownerMine") : acc.owner === "workspace" ? t("conn.ownerWs", { name: acc.workspaceName || wsName || "" }) : t("conn.ownerAll");
/* What the server refused, in the reader's language where it names a reason
   (`code`), else in its own words. */
const CONN_ERR = { "provider-address": "conn.addressRefused", "paste-format": "conn.pasteErrFormat", "paste-other": "conn.pasteErrOther",
                   "paste-expired": "conn.pasteErrExpired", "paste-denied": "conn.pasteErrDenied", "paste-refused": "conn.pasteErrRefused" };
const connErr = (e, fb) => {
  const d = (e && e.data) || {};
  if (CONN_ERR[d.code]) return t(CONN_ERR[d.code], { name: d.provider === "microsoft" ? "Microsoft" : "Google", address: d.address || "" });
  return (e && e.message) || fb;
};
/* Mailboxes with a known catch (imap.js, mailProviderOf): the steps are shown
   as soon as the address says whose it is, and again when the sign-in is
   refused. `link`: where the app password is made. */
const MAIL_DOMAINS = { "gmail.com": "gmail", "googlemail.com": "gmail", "gmx.de": "gmx", "gmx.net": "gmx", "gmx.at": "gmx", "gmx.ch": "gmx", "web.de": "webde",
  "icloud.com": "icloud", "me.com": "icloud", "mac.com": "icloud", "yahoo.com": "yahoo", "yahoo.de": "yahoo", "aol.com": "aol", "aol.de": "aol",
  "outlook.com": "microsoft", "outlook.de": "microsoft", "hotmail.com": "microsoft", "hotmail.de": "microsoft", "live.com": "microsoft", "live.de": "microsoft", "msn.com": "microsoft",
  "t-online.de": "tonline", "magenta.de": "tonline" };
const MAIL_HELP = {
  gmail: { steps: 3, link: "https://myaccount.google.com/apppasswords", note: true },
  gmx: { steps: 2 }, webde: { steps: 2 },
  icloud: { steps: 2, link: "https://account.apple.com" },
  yahoo: { steps: 2, link: "https://login.yahoo.com/account/security" }, aol: { steps: 2, link: "https://login.aol.com/account/security" },
  microsoft: { steps: 1, outlook: true }, tonline: { steps: 2 },
};
/* How far a connection may go, in words: a mailbox's levels are named by what
   they mean for mail (reading, drafts), everything else's by changes. Takes a
   service key or a group. */
const MAIL_SERVICES = ["google_gmail", "ms_outlook", "imap_mail"];
const accessLabel = (service, level) => t((service === "mail" || MAIL_SERVICES.includes(service) ? "conn.mailAccess." : "conn.access.") + level);
const mailHelpKey = email => MAIL_DOMAINS[String(email || "").trim().toLowerCase().split("@")[1] || ""] || null;
/* does the account already hold what this access needs (else the provider asks again) */
const reaches = (acc, service, access) => { const r = (acc && acc.reach && acc.reach[service]) || ""; return r === "write" || (access === "read" && r === "read"); };

/* What an agent did through the app (server.js, tool_calls): loaded when opened. */
const ACT_OUTCOME = { ok: "ok", error: "bad", declined: "bad", expired: "bad", refused: "bad", cancelled: "bad" };
function ToolCallRow({ c, withAgent }) {
  const when = new Date(c.at);
  return (
    <div className="act-row">
      <span className="act-when" title={when.toLocaleString()}>{L.relTime ? L.relTime(c.at) : when.toLocaleTimeString()}</span>
      {withAgent && <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>
  );
}
function ConnActivity({ agentId }) {
  const [calls, setCalls] = useState(null);
  const load = () => L.AgentConnectorsAPI.activity(agentId, 30).then(r => setCalls(r.calls || [])).catch(() => setCalls([]));
  return (
    <details className="conn-activity" onToggle={e => { if (e.target.open && calls === null) load(); }}>
      <summary>{t("act.agentTitle")}</summary>
      {calls === null ? <p className="conn-note">{t("common.loading")}</p>
        : calls.length === 0 ? <p className="conn-note">{t("act.none")}</p>
        : <div className="act-list">{calls.map((c, i) => <ToolCallRow key={i} c={c} />)}</div>}
      <p className="conn-note">{t("act.note")}</p>
    </details>
  );
}
/* `agent`: that agent's connections. Without one: what the person's NEW
   agents start with (server.js, connectorDefaults; the start page and
   Settings), the same dialog over the marked services. */
function ConnectionsModal({ agent, title, initial, onClose }) {
  const forNewAgents = !agent;
  const agentId = agent ? agent.id : null;
  const [data, setData] = useState(null);
  const [view, setView] = useState("list");          /* "list" | "catalog" | an entry */
  const [q, setQ] = useState("");
  const [msg, setMsg] = useState(null);
  const [waiting, setWaiting] = useState(false);     /* a sign-in window is open */
  const [acct, setAcct] = useState("");
  const [access, setAccess] = useState("read");
  /* give the account to this person's new agents too (server.js, connectorDefaults) */
  const [forNew, setForNew] = useState(true);
  /* for new agents: what giving the marked ones to existing agents did */
  const [applied, setApplied] = useState(null);
  /* a mailbox over IMAP: what the person types instead of a sign-in window */
  const blankMail = { email: "", password: "", host: "", port: "", security: "ssl", username: "", smtpHost: "", smtpPort: "", smtpSecurity: "ssl", more: false };
  /* A mailbox: may this agent also send with it (each mail after the person's
     OK in the email card), or drafts only. For Outlook it also decides
     whether Microsoft is asked for sending (Mail.Send): off for
     organisations that do not let people consent to it. */
  const [allowSend, setAllowSend] = useState(true);
  const [mail, setMail] = useState(blankMail);
  const [mailBusy, setMailBusy] = useState(false);
  /* the steps for a mailbox provider: asked for (Gmail without Google sign-in), or what the server said refused */
  const [mailHelp, setMailHelp] = useState(null);
  /* A sign-in that ends with copying an address back (server.js, 'paste'):
     { state, redirect, url, text, busy }. Google sent the person to an
     address on their own machine; what their address bar shows goes here. */
  const [paste, setPaste] = useState(null);
  /* how the last sign-in of that kind ended: { outcome, email, service } */
  const [done, setDone] = useState(null);
  const pendingConn = useRef(null);                  /* a connection to add once its sign-in is back */
  const load = () => (agent ? L.AgentConnectorsAPI.get(agentId) : L.AccountsAPI.newAgents()).then(d => { setData(d); return d; }).catch(e => { setMsg(connErr(e, t("conn.failed"))); setData(d => d || { grants: [], catalog: [], accounts: [], owners: [], connections: [] }); });
  useEffect(() => { load(); }, [agentId]);
  /* opened from a card under a reply: straight to that service, at the access it asked for */
  const opened = useRef(false);
  useEffect(() => {
    if (!data || opened.current || !initial || !initial.service) return;
    opened.current = true;
    const c = (data.catalog || []).find(x => x.key === initial.service);
    if (c) { openEntry({ type: "native", key: c.key, name: c.name, group: c.group, about: t("conn.about." + c.key), svc: c }); setAccess(CONN_ACCESS.includes(initial.access) ? initial.access : "read"); }
  }, [data]);
  useEffect(() => {
    const onMsg = async e => {
      if (e.origin !== location.origin || !e.data || e.data.type !== "indie-oauth") return;
      setWaiting(false);
      if (e.data.ok && pendingConn.current) {
        const id = pendingConn.current; pendingConn.current = null;
        try { setData(await L.AgentConnectorsAPI.add(agentId, { connectionId: id })); } catch (err) { setMsg(connErr(err, t("conn.failed"))); }
      } else await load();
      if (e.data.ok) setView("list");
    };
    window.addEventListener("message", onMsg);
    return () => window.removeEventListener("message", onMsg);
  }, [agentId]);
  /* the sign-in window opens at once, while the click still counts as the
     person's: one opened after the request returns is what pop-up blockers stop */
  const signIn = async (fn, provider) => {
    setMsg(null); setDone(null);
    /* copying an address back needs an address bar: a tab, not a window without one */
    const tab = !!(data && data.flows && data.flows[provider]);
    const w = tab ? window.open("", "_blank") : window.open("", "indie-oauth", "width=560,height=720");
    try {
      const r = await fn();
      if (r.paste) {
        /* the provider's pages get no handle on this one */
        if (w && !w.closed) { try { w.opener = null; } catch {} w.location.href = r.url; }
        setPaste({ state: r.paste.state, redirect: r.paste.redirect, url: r.url, text: "", busy: false, blocked: !w || w.closed });
        return;
      }
      if (w && !w.closed) w.location.href = r.url; else location.href = r.url;
      setWaiting(true);
    } catch (e) { if (w) w.close(); setMsg(connErr(e, t("conn.failed"))); }
  };
  /* the pasted address (or what was typed) to the server; a wrong paste can be tried again */
  const finishPaste = async text => {
    const pasted = String(text != null ? text : paste.text).trim();
    if (!pasted || !paste || paste.busy) return;
    setMsg(null); setPaste(p => p && ({ ...p, text: pasted, busy: true }));
    try {
      const r = await L.AccountsAPI.finishConnect({ state: paste.state, pasted });
      if (r.view) setData(r.view); else await load();
      setPaste(null); setView("list");
      setDone({ outcome: r.outcome, email: r.email || "", service: r.service });
    } catch (e) {
      const code = e && e.data && e.data.code;
      setMsg(connErr(e, t("conn.failed")));
      if (code === "paste-format" || code === "paste-other") setPaste(p => p && ({ ...p, text: "", busy: false }));
      else setPaste(null);
    }
  };
  const act = async fn => { setMsg(null); try { setData(await fn()); } catch (e) { setMsg(connErr(e, t("conn.failed"))); } };

  /* Rendered into <body>: opened from a top bar (the start page's), it would
     be laid out inside it, because the bar's backdrop-filter makes it the
     containing block of everything fixed in it. */
  const portal = el => ReactDOM.createPortal(el, document.body);
  if (!data) return portal(
    <div className="modal-scrim" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal conn-modal"><div className="modal-body"><div className="set-empty">{t("common.loading")}</div></div></div>
    </div>
  );
  const manage = data.manage;
  /* is this provider's sign-in set up on the server (an older server says so for Google only) */
  const ready = pr => data.ready && pr in data.ready ? !!data.ready[pr] : pr === "google" && !!data.googleReady;
  const prName = pr => (pr === "microsoft" ? "Microsoft" : "Google");
  const svcOf = key => data.catalog.find(c => c.key === key);
  /* a mailbox's levels are named by what they mean for mail: reading, drafts */
  const accessWord = (svc, level) => accessLabel(svc && svc.group === "mail" ? "mail" : "", level);
  const accessHint = (svc, level) => t((svc && svc.group === "mail" ? "conn.mailAccessHint." : "conn.accessHint.") + level);
  const wsOwner = data.owners.find(o => o.owner === "workspace");
  /* the catalog: the services that run here, then the admin's connections */
  const entries = [
    ...data.catalog.map(c => ({ type: "native", key: c.key, name: serviceName(c.key, c.name), group: c.group, about: t("conn.about." + c.key), svc: c,
                                added: data.grants.some(g => g.service === c.key) })),
    ...data.connections.map(c => ({ type: "connection", key: "c:" + c.id, id: c.id, name: c.name, group: c.group, about: c.description || "", conn: c,
                                     added: data.mode === "all" ? c.connected : data.grants.some(g => g.connection && g.connection.id === c.id) })),
  ];
  const needle = q.trim().toLowerCase();
  const shown = entries.filter(e => !needle || (e.name + " " + e.about + " " + t("conn.group." + e.group)).toLowerCase().includes(needle));
  const open = e => openEntry(e);
  function openEntry(e, preset) {
    setMsg(null); setDone(null); setView(e); setMail(blankMail); setForNew(true); setAllowSend(true); setMailHelp(preset && preset.help ? preset.help : null);
    if (e.type === "native") {
      const fit = data.accounts.find(a => a.provider === e.svc.provider);
      setAcct(preset && preset.acct ? preset.acct : fit ? fit.id : data.owners.find(o => o.owner === "person") ? "new:person" : wsOwner && wsOwner.manage ? "new:workspace" : data.owners.find(o => o.owner === "everyone" && o.manage) ? "new:everyone" : "");
      setAccess(preset && preset.access ? preset.access : "read");
    }
  }
  /* an account of this person's own (or a new one): only those can go to their new agents */
  const ownAcct = id => id === "new:person" || !!data.accounts.find(x => x.id === id && x.owner === "person" && x.mine);
  /* true or false for one's own account; nothing for anyone else's */
  const markNew = id => (ownAcct(id) ? forNew : undefined);
  const isDefault = g => !!g.account && (data.defaults || []).some(d => d.service === g.service && d.accountId === g.account.id);
  /* a mailbox: connected (or connected again with a new password), tried
     first by the server, and added to the agent in the same step */
  const mailFormFor = acctId => acctId.startsWith("new:") || !!(data.accounts.find(x => x.id === acctId) || {}).expired;
  const connectMail = async () => {
    setMsg(null); setMailBusy(true);
    const again = !acct.startsWith("new:");
    try {
      const r = await L.AccountsAPI.connectImap({
        ...(again ? { accountId: acct } : { owner: acct.slice(4), workspaceId: data.workspaceId || undefined, email: mail.email.trim() }),
        password: mail.password, host: mail.host.trim() || undefined, port: mail.port.trim() || undefined, security: mail.security,
        smtpHost: mail.smtpHost.trim() || undefined, smtpPort: mail.smtpPort.trim() || undefined, smtpSecurity: mail.smtpSecurity,
        username: mail.username.trim() || undefined, agentId: agentId || undefined, access, forNew: forNewAgents ? true : markNew(acct),
        ...(access !== "read" && !allowSend ? { send: false } : {}) });
      if (r.view) setData(r.view); else await load();
      setMail(blankMail); setView("list");
    } catch (err) {
      setMsg(connErr(err, t("conn.failed")));
      /* the server it tried, to correct by hand */
      const d = (err && err.data) || {};
      /* whose server refused, where that has a known reason: show the steps */
      if (d.mailProvider && MAIL_HELP[d.mailProvider]) setMailHelp(d.mailProvider);
      if (d.server) setMail(m => ({ ...m, more: true, host: m.host || d.server.host, port: m.port || String(d.server.port), security: d.server.security,
                                    ...(d.server.smtpHost ? { smtpHost: m.smtpHost || d.server.smtpHost, smtpPort: m.smtpPort || String(d.server.smtpPort), smtpSecurity: d.server.smtpSecurity } : {}) }));
      else if (d.needServer || d.field === "host" || d.field === "port") setMail(m => ({ ...m, more: true }));
    } finally { setMailBusy(false); }
  };
  const addNative = e => {
    if (!acct) return;
    const fn = forNewAgents ? true : markNew(acct), aid = agentId || undefined;
    /* a mailbox that may change things: with sending, or drafts only */
    const send = e.svc.group === "mail" && access !== "read" ? { send: allowSend } : {};
    const pr = e.svc.provider;
    if (acct.startsWith("new:"))
      return signIn(() => L.AccountsAPI.connect({ service: e.key, access, owner: acct.slice(4), workspaceId: data.workspaceId || undefined, agentId: aid, forNew: fn, ...send }), pr);
    const a = data.accounts.find(x => x.id === acct);
    if (!reaches(a, e.key, access) || (e.key === "ms_outlook" && allowSend && access !== "read" && data.mailSend !== "drafts" && !(a && a.canSend)))
      return signIn(() => L.AccountsAPI.connect({ service: e.key, access, accountId: acct, agentId: aid, forNew: fn, ...send }), pr);
    act(async () => {
      const d = forNewAgents ? await L.AccountsAPI.setDefault({ service: e.key, accountId: acct, access, ...send })
                             : await L.AgentConnectorsAPI.add(agentId, { service: e.key, accountId: acct, access, forNew: fn, ...send });
      setView("list"); return d;
    });
  };
  /* a mailbox on the agent: sending on or off (drafts only) */
  const setGrantSend = (g, on) => {
    if (forNewAgents) return act(() => L.AccountsAPI.setDefault({ service: g.service, accountId: g.account.id, access: g.access, send: on }));
    act(async () => {
      const d = await L.AgentConnectorsAPI.setSend(agentId, g.id, on);
      if (!isDefault(g)) return d;
      await L.AccountsAPI.setDefault({ service: g.service, accountId: g.account.id, access: g.access, send: on });
      return L.AgentConnectorsAPI.get(agentId);
    });
  };
  const setGrantAccess = (g, level) => {
    if (g.account && !reaches(g.account, g.service, level))
      return signIn(() => L.AccountsAPI.connect({ service: g.service, access: level, accountId: g.account.id, agentId: agentId || undefined, forNew: forNewAgents || isDefault(g) }), g.account.provider);
    if (forNewAgents) return act(() => L.AccountsAPI.setDefault({ service: g.service, accountId: g.account.id, access: level }));
    /* a grant marked for new agents takes its default along */
    act(async () => {
      const d = await L.AgentConnectorsAPI.setAccess(agentId, g.id, level);
      if (!isDefault(g)) return d;
      await L.AccountsAPI.setDefault({ service: g.service, accountId: g.account.id, access: level });
      return L.AgentConnectorsAPI.get(agentId);
    });
  };
  const removeGrant = g => act(() => forNewAgents ? L.AccountsAPI.setDefault({ service: g.service, accountId: g.account.id, access: null })
                                                  : L.AgentConnectorsAPI.remove(agentId, g.id));
  /* the marked ones to the agents the person already has */
  const applyToExisting = async () => {
    setMsg(null);
    try { const r = await L.AccountsAPI.applyDefaults(); setApplied(r.agents ? t("settings.defaultsApplied", { n: r.agents }) : t("settings.defaultsNothing")); }
    catch (e) { setMsg(connErr(e, t("conn.failed"))); }
  };
  const toggleNew = (g, on) => act(async () => {
    await L.AccountsAPI.setDefault({ service: g.service, accountId: g.account.id, access: on ? g.access : null, ...(on && g.send === false ? { send: false } : {}) });
    return L.AgentConnectorsAPI.get(agentId);
  });

  const head = (
    <div className="modal-head">
      <div><span className="eb">{t("conn.eyebrow")}</span><h2>{title}</h2></div>
      <button className="modal-x" onClick={onClose}>✕</button>
    </div>
  );
  const back = <button className="conn-back" onClick={() => { setView(view === "catalog" ? "list" : "catalog"); setMsg(null); }}>← {view === "catalog" ? (forNewAgents ? t("conn.newTitle") : t("conn.backList")) : t("conn.backCatalog")}</button>;

  let body;
  if (paste) {
    /* The copy-back way. The provider's page is open in a tab; when the
       person has agreed there, the browser lands on an address on their own
       machine where nothing answers, and that address comes back here. */
    body = (<>
      <button className="conn-back" onClick={() => { setPaste(null); setMsg(null); }}>← {t("conn.pasteBack")}</button>
      <div className="conn-detail-head"><ConnGlyph group={view && view.group} /><div><h3>{t("conn.pasteTitle")}</h3><p>{t("conn.pasteIntro")}</p></div></div>
      <ol className="conn-steps">
        <li>
          <div>{tb(paste.blocked ? "conn.pasteStep1Blocked" : "conn.pasteStep1")}</div>
          <div className="conn-choice-sub">{tb("conn.googleHint")}</div>
          <a className="mini" href={paste.url} target="_blank" rel="noopener noreferrer">{paste.blocked ? t("conn.pasteOpen") : t("conn.pasteOpenAgain")}</a>
        </li>
        <li>
          <div>{tb("conn.pasteStep2")}</div>
          <div className="conn-paste-bar" aria-hidden="true"><span className="conn-paste-dot" />{paste.redirect.replace(/^http:\/\//, "")}?state=…&amp;code=…</div>
        </li>
        <li>
          <label htmlFor="conn-paste">{tb("conn.pasteStep3")}</label>
          <input id="conn-paste" className="conn-paste-input" autoFocus spellCheck="false" autoComplete="off" value={paste.text} disabled={paste.busy}
                 placeholder={paste.redirect + "?state=…&code=…"}
                 onChange={ev => { const v = ev.target.value; setPaste(p => p && ({ ...p, text: v })); }}
                 onPaste={ev => { const tx = (ev.clipboardData || window.clipboardData).getData("text"); if (/[?&](code|error)=/.test(tx)) { ev.preventDefault(); finishPaste(tx); } }}
                 onKeyDown={ev => { if (ev.key === "Enter") finishPaste(); }} />
        </li>
      </ol>
    </>);
  } else if (view === "list") {
    const legacy = data.connections.filter(c => c.connected);
    body = (<>
      <p className="conn-intro">{forNewAgents ? t("conn.introNew") : data.personal ? t("conn.introPersonal") : t("conn.introShared")}</p>
      {done && (() => {
        const name = (svcOf(done.service) || {}).name || "";
        const good = done.outcome === "added" || done.outcome === "marked" || done.outcome === "connected";
        return <div className={"set-msg " + (good ? "ok" : "bad")} role="status">{t("conn.done." + (good ? "ok" : done.outcome), { email: done.email, name })}</div>;
      })()}
      {data.grants.length === 0 && !(data.mode === "all" && legacy.length) && <div className="set-empty">{forNewAgents ? t("conn.noneNew") : t("conn.none")}</div>}
      {data.grants.length > 0 && (
        <div className="conn-list">
          {data.grants.map(g => {
            const svc = g.connection ? null : svcOf(g.service);
            const name = g.connection ? g.connection.name : svc ? serviceName(svc.key, svc.name) : g.service;
            return (
              <div className="conn-row" key={g.id}>
                <ConnGlyph group={g.connection ? g.connection.group : svc && svc.group} />
                <div className="conn-row-main">
                  <div className="conn-row-name">{name}</div>
                  <div className="conn-row-sub">
                    {g.account ? <>{g.account.label} · {ownerWord(g.account)}</> : t("conn.yourConnection")}
                    {g.account && g.account.expired && <em> · {t("conn.expired")}</em>}
                    {g.account && !g.fits && <em> · {t("conn.notHere")}</em>}
                  </div>
                  {g.account && manage && !forNewAgents && ownAcct(g.account.id) && (
                    <label className="conn-fornew-mini" title={t("conn.forNewHint")}>
                      <input type="checkbox" checked={isDefault(g)} onChange={ev => toggleNew(g, ev.target.checked)} /> {t("conn.forNewShort")}
                    </label>
                  )}
                  {/* a mailbox that may write: with sending (each mail after the person's OK), or drafts only */}
                  {g.account && svc && svc.group === "mail" && g.access !== "read" && data.mailSend !== "drafts" && g.account.canSend !== false && (manage
                    ? <label className="conn-fornew-mini conn-send-mini" title={t("conn.allowSendHint")}>
                        <input type="checkbox" checked={g.send !== false} onChange={ev => setGrantSend(g, ev.target.checked)} /> {t("conn.sendShort")}
                      </label>
                    : g.send === false && <span className="conn-fornew-mini">{t("conn.draftsOnly")}</span>)}
                </div>
                {g.account && g.account.expired && manage && (
                  <button className="mini primary" onClick={() => g.account.provider === "imap"
                    ? openEntry(entries.find(x => x.key === g.service) || { type: "native", key: g.service, name, group: svc && svc.group, about: "", svc }, { acct: g.account.id, access: g.access })
                    : signIn(() => L.AccountsAPI.connect({ service: g.service, access: g.access, accountId: g.account.id, agentId: agentId || undefined, ...(forNewAgents ? { forNew: true } : {}) }), g.account.provider)}>{t("conn.again")}</button>
                )}
                {/* Outlook signed in before sending existed: one more sign-in allows it (Mail.Send) */}
                {g.account && !g.account.expired && manage && g.account.manage && g.service === "ms_outlook" && g.access !== "read" && data.mailSend !== "drafts" && g.account.canSend === false && (
                  <button className="mini" title={t("conn.allowSendHint")}
                          onClick={() => signIn(() => L.AccountsAPI.connect({ service: g.service, access: g.access, accountId: g.account.id, agentId: agentId || undefined, send: true, ...(forNewAgents ? { forNew: true } : {}) }), g.account.provider)}>{t("conn.allowSendBtn")}</button>
                )}
                {g.account && (manage
                  ? <select className="adm-select conn-access" value={g.access} aria-label={t("conn.accessLabel")} onChange={e => setGrantAccess(g, e.target.value)}>
                      {CONN_ACCESS.map(l => <option key={l} value={l}>{accessWord(svc, l)}</option>)}
                    </select>
                  : <span className="conn-row-access">{accessWord(svc, g.access)}</span>)}
                {manage && <button className="mini danger" onClick={() => removeGrant(g)}>{t("conn.remove")}</button>}
              </div>
            );
          })}
        </div>
      )}
      {data.mode === "all" && data.personal && legacy.length > 0 && (
        <div className="conn-legacy">
          <div className="conn-legacy-head">{t("conn.allTitle")}</div>
          <p className="conn-note">{t("conn.allDesc")} <b>{legacy.map(c => c.name).join(", ")}</b></p>
          {manage && <button className="mini" onClick={() => act(() => L.AgentConnectorsAPI.setMode(agentId, "chosen"))}>{t("conn.chooseInstead")}</button>}
        </div>
      )}
      {!manage && <p className="conn-note">{t("conn.adminOnly")}</p>}
      {forNewAgents ? (<>
        {data.grants.length > 0 && (
          <div className="conn-apply">
            <button className="mini" onClick={applyToExisting}>{t("settings.defaultsApply")}</button>
            {applied && <span className="conn-note">{applied}</span>}
          </div>
        )}
        <p className="conn-note">{t("conn.nextNew")}</p>
      </>) : (<>
        <p className="conn-note">{t("conn.nextTurn")}</p>
        <ConnActivity agentId={agentId} />
      </>)}
    </>);
  } else if (view === "catalog") {
    body = (<>
      {back}
      <input className="conn-search" autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder={t("conn.search")} aria-label={t("conn.search")} />
      {shown.length === 0 && <div className="set-empty">{t("conn.noMatch")}</div>}
      {CONN_GROUPS.filter(gr => shown.some(e => e.group === gr)).map(gr => (
        <div key={gr} className="conn-group">
          <div className="conn-group-head">{t("conn.group." + gr)}</div>
          {shown.filter(e => e.group === gr).map(e => (
            <button key={e.key} className="conn-entry" onClick={() => open(e)}>
              <ConnGlyph group={e.group} />
              <span className="conn-entry-text"><span className="conn-entry-name">{e.name}</span><span className="conn-entry-about">{e.about}</span></span>
              {e.added && <span className="conn-chip on">{t("conn.added")}</span>}
              {!e.added && e.type === "native" && !ready(e.svc.provider) && <span className="conn-chip">{t("conn.notSetUp")}</span>}
            </button>
          ))}
        </div>
      ))}
      {!data.personal && <p className="conn-note">{t("conn.sharedNoPersonal")}</p>}
    </>);
  } else if (view.type === "native") {
    const e = view, provider = e.svc.provider, isMail = provider === "imap";
    const fits = data.accounts.filter(a => a.provider === provider);
    const mailForm = isMail && mailFormFor(acct);
    const newAcct = acct.startsWith("new:");
    const setM = (k, v) => setMail(m => ({ ...m, [k]: v }));
    const newOpts = data.owners.filter(o => o.owner !== "workspace" || o.manage).filter(o => o.owner !== "everyone" || o.manage);
    body = (<>
      {back}
      <div className="conn-detail-head"><ConnGlyph group={e.group} /><div><h3>{e.name}</h3><p>{e.about}</p></div></div>
      <div className="conn-tools">
        {e.svc.tools.map(tl => <span key={tl.name} className={"conn-tool" + (tl.write ? " w" : "")} title={tl.confirm ? t("conn.toolConfirm") : tl.write ? t("conn.toolWrite") : t("conn.toolRead")}>{tl.name}{tl.confirm ? " !" : ""}</span>)}
      </div>
      {!ready(provider) ? (<>
        <p className="conn-note warn">{data.admin ? tb("conn.providerMissingAdmin", { name: prName(provider) }) : t("conn.providerMissing", { name: prName(provider) })}</p>
        {/* Gmail needs no sign-in app at all: as a mailbox, with an app password (mail only) */}
        {e.key === "google_gmail" && manage && entries.some(x => x.key === "imap_mail") && (
          <div className="conn-alt">
            <b>{t("conn.gmailAltTitle")}</b>
            <p>{t("conn.gmailAltText")}</p>
            <button className="btn" onClick={() => openEntry(entries.find(x => x.key === "imap_mail"), { help: "gmail" })}>{t("conn.gmailAltBtn")}</button>
          </div>
        )}
      </>) : !manage ? <p className="conn-note">{t("conn.adminOnly")}</p> : (<>
        <div className="field">
          <label>{t("conn.account")}</label>
          <div className="conn-choices">
            {fits.map(a => (
              <label key={a.id} className={"conn-choice" + (acct === a.id ? " on" : "")}>
                <input type="radio" name="conn-acct" checked={acct === a.id} onChange={() => setAcct(a.id)} />
                <span><b>{a.label}</b> <span className="conn-choice-sub">{ownerWord(a)}{a.expired ? " · " + t("conn.expired") : ""}</span></span>
              </label>
            ))}
            {newOpts.map(o => (
              <label key={o.owner} className={"conn-choice" + (acct === "new:" + o.owner ? " on" : "")}>
                <input type="radio" name="conn-acct" checked={acct === "new:" + o.owner} onChange={() => setAcct("new:" + o.owner)} />
                <span>{isMail ? t("conn.newMail." + o.owner, { name: o.name || "" }) : t("conn.new." + o.owner, { name: o.name || "", provider: prName(provider) })}</span>
              </label>
            ))}
            {fits.length === 0 && newOpts.length === 0 && <div className="conn-note">{wsOwner ? t("conn.wsAskAdmin", { name: wsOwner.name }) : t("conn.noAccountHere")}</div>}
          </div>
          {wsOwner && !wsOwner.manage && fits.length > 0 && <div className="help">{t("conn.wsAskAdmin", { name: wsOwner.name })}</div>}
        </div>
        {mailForm && (
          <div className="conn-mail">
            {!newAcct && <p className="conn-note">{t("conn.mailAgain")}</p>}
            {newAcct && (
              <div className="field">
                <label htmlFor="mail-email">{t("conn.mailEmail")}</label>
                <input id="mail-email" type="email" autoComplete="off" spellCheck="false" value={mail.email} onChange={ev => setM("email", ev.target.value)} placeholder={mailHelp === "gmail" ? "name@gmail.com" : "name@example.com"} />
              </div>
            )}
            <div className="field">
              <label htmlFor="mail-pass">{t("conn.mailPassword")}</label>
              <input id="mail-pass" type="password" autoComplete="new-password" value={mail.password} onChange={ev => setM("password", ev.target.value)} />
              <div className="help">{t("conn.mailPasswordHint")}</div>
            </div>
            {(() => {
              /* whose mailbox it is, where that has a catch: the steps, and where the app password is made */
              const key = mailHelpKey(mail.email) || mailHelp, h = key && MAIL_HELP[key];
              if (!h) return null;
              const outlook = h.outlook && entries.find(x => x.key === "ms_outlook");
              return (
                <div className="conn-mailhelp" data-provider={key}>
                  <b>{t("conn.mailHelp." + key + ".title")}</b>
                  <ol>{Array.from({ length: h.steps }, (_, i) => <li key={i}>{tb("conn.mailHelp." + key + "." + (i + 1))}</li>)}</ol>
                  {h.link && <p><a href={h.link} target="_blank" rel="noopener noreferrer">{h.link.replace(/^https:\/\//, "")}</a></p>}
                  {h.note && <p className="conn-choice-sub">{t("conn.mailHelp." + key + ".note")}</p>}
                  {outlook && <p><button className="mini" onClick={() => openEntry(outlook)}>{t("conn.mailHelp.microsoft.btn")}</button></p>}
                </div>
              );
            })()}
            <details className="conn-mail-more" open={mail.more} onToggle={ev => { const o = ev.currentTarget.open; setMail(m => (m.more === o ? m : { ...m, more: o })); }}>
              <summary>{t("conn.mailMore")}</summary>
              <div className="field">
                <label htmlFor="mail-host">{t("conn.mailHost")}</label>
                <input id="mail-host" autoComplete="off" spellCheck="false" value={mail.host} onChange={ev => setM("host", ev.target.value)} placeholder={t("conn.mailAuto")} />
              </div>
              <div className="conn-mail-row">
                <div className="field">
                  <label htmlFor="mail-sec">{t("conn.mailSecurity")}</label>
                  <select id="mail-sec" className="adm-select" value={mail.security} onChange={ev => setM("security", ev.target.value)}>
                    <option value="ssl">{t("conn.mailSsl")}</option>
                    <option value="starttls">{t("conn.mailStarttls")}</option>
                  </select>
                </div>
                <div className="field">
                  <label htmlFor="mail-port">{t("conn.mailPort")}</label>
                  <input id="mail-port" inputMode="numeric" value={mail.port} onChange={ev => setM("port", ev.target.value)} placeholder={mail.security === "starttls" ? "143" : "993"} />
                </div>
              </div>
              <div className="field">
                <label htmlFor="mail-user">{t("conn.mailUser")}</label>
                <input id="mail-user" autoComplete="off" spellCheck="false" value={mail.username} onChange={ev => setM("username", ev.target.value)} />
              </div>
              <div className="field">
                <label htmlFor="mail-smtp">{t("conn.mailSmtpHost")}</label>
                <input id="mail-smtp" autoComplete="off" spellCheck="false" value={mail.smtpHost} onChange={ev => setM("smtpHost", ev.target.value)} placeholder={t("conn.mailAuto")} />
                <div className="help">{t("conn.mailSmtpHint")}</div>
              </div>
              <div className="conn-mail-row">
                <div className="field">
                  <label htmlFor="mail-smtp-sec">{t("conn.mailSecurity")}</label>
                  <select id="mail-smtp-sec" className="adm-select" value={mail.smtpSecurity} onChange={ev => setM("smtpSecurity", ev.target.value)}>
                    <option value="ssl">{t("conn.mailSsl")}</option>
                    <option value="starttls">{t("conn.mailStarttls")}</option>
                  </select>
                </div>
                <div className="field">
                  <label htmlFor="mail-smtp-port">{t("conn.mailPort")}</label>
                  <input id="mail-smtp-port" inputMode="numeric" value={mail.smtpPort} onChange={ev => setM("smtpPort", ev.target.value)} placeholder={mail.smtpSecurity === "starttls" ? "587" : "465"} />
                </div>
              </div>
            </details>
          </div>
        )}
        <div className="field">
          <label>{t("conn.accessLabel")}</label>
          <div className="conn-choices">
            {CONN_ACCESS.map(l => (
              <label key={l} className={"conn-choice" + (access === l ? " on" : "")}>
                <input type="radio" name="conn-access" checked={access === l} onChange={() => setAccess(l)} />
                <span><b>{accessWord(e.svc, l)}</b> <span className="conn-choice-sub">{accessHint(e.svc, l)}</span></span>
              </label>
            ))}
          </div>
        </div>
        {/* a mailbox that may write: with sending, each mail after the person's OK, or drafts only */}
        {e.svc.group === "mail" && access !== "read" && data.mailSend !== "drafts" && (
          <label className="conn-fornew conn-send">
            <input type="checkbox" checked={allowSend} onChange={ev => setAllowSend(ev.target.checked)} />
            <span><b>{t("conn.allowSend")}</b> <span className="conn-choice-sub">{t("conn.allowSendHint")}{e.key === "ms_outlook" ? " " + t("conn.allowSendMs") : ""}</span></span>
          </label>
        )}
        {!forNewAgents && ownAcct(acct) && (
          <label className="conn-fornew">
            <input type="checkbox" checked={forNew} onChange={ev => setForNew(ev.target.checked)} />
            <span><b>{t("conn.forNew")}</b> <span className="conn-choice-sub">{t("conn.forNewHint")}</span></span>
          </label>
        )}
        <p className="conn-note">{e.key === "ms_teams" ? t("conn.teamsAsks")
          : e.svc.group === "mail" ? (data.mailSend === "drafts" ? t("conn.mailDraftsOnly") : access === "read" ? t("conn.mailReadOnly") : allowSend ? t("conn.mailCard") : t("conn.mailNoSend"))
          : t("conn.neverSends")}</p>
        {/* what Google shows on the way: its warning about an app it has not verified, and checkboxes */}
        {provider === "google" && (acct.startsWith("new:") || !reaches(data.accounts.find(x => x.id === acct), e.key, access)) && <p className="conn-note">{tb("conn.googleHint")}</p>}
      </>)}
    </>);
  } else {
    const c = view.conn;
    body = (<>
      {back}
      <div className="conn-detail-head"><ConnGlyph group={view.group} /><div><h3>{c.name}</h3><p>{view.about}</p></div></div>
      <p className="conn-note">{c.connected ? t("conn.connConnected") + (c.account ? " (" + c.account + ")" : "") : t("conn.connNotYet")}</p>
      {data.mode === "all" && <p className="conn-note">{t("conn.connAll")}</p>}
    </>);
  }

  const foot = paste ? (
    <div className="modal-foot">
      <span className="test-status run">{paste.busy ? t("conn.pasteChecking") : ""}</span>
      <button className="btn" onClick={() => { setPaste(null); setMsg(null); }}>{t("common.cancel")}</button>
      <button className="btn primary" disabled={!paste.text.trim() || paste.busy} onClick={() => finishPaste()}>{t("conn.pasteFinish")}</button>
    </div>
  ) : view === "list" ? (
    <div className="modal-foot">
      <span className="test-status run">{waiting ? t("conn.waiting") : ""}</span>
      {manage && <button className="btn primary" onClick={() => { setQ(""); setView("catalog"); }}>+ {t("conn.add")}</button>}
    </div>
  ) : view !== "catalog" && manage ? (
    <div className="modal-foot">
      <span className="test-status run">{waiting ? t("conn.waiting") : ""}</span>
      {view.type === "native" && view.svc.provider === "imap" && mailFormFor(acct) && (
        <button className="btn primary" disabled={mailBusy || !mail.password || (acct.startsWith("new:") && !mail.email.trim())} onClick={connectMail}>
          {mailBusy ? t("conn.mailChecking") : acct.startsWith("new:") ? t("conn.mailConnect") : t("conn.again")}
        </button>
      )}
      {view.type === "native" && ready(view.svc.provider) && !(view.svc.provider === "imap" && mailFormFor(acct)) && (
        <button className="btn primary" disabled={!acct || waiting} onClick={() => addNative(view)}>
          {acct.startsWith("new:") || !reaches(data.accounts.find(x => x.id === acct), view.key, access) ? t("conn.signInAdd") : forNewAgents ? t("conn.addNew") : t("conn.addTo")}
        </button>
      )}
      {view.type === "connection" && !view.conn.connected && (
        <button className="btn primary" disabled={waiting} onClick={() => { if (data.mode === "chosen") pendingConn.current = view.conn.id; signIn(() => L.ConnectionsAPI.connect(view.conn.id)); }}>{t("conn.signIn")}</button>
      )}
      {view.type === "connection" && view.conn.connected && data.mode === "chosen" && !view.added && (
        <button className="btn primary" onClick={() => act(async () => { const d = await L.AgentConnectorsAPI.add(agentId, { connectionId: view.conn.id }); setView("list"); return d; })}>{t("conn.addTo")}</button>
      )}
    </div>
  ) : null;

  return portal(
    <div className="modal-scrim" onMouseDown={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal conn-modal" role="dialog" aria-label={t("conn.eyebrow")}>
        {head}
        <div className="modal-body">
          {body}
          {msg && <div className="set-msg bad" role="alert">{msg}</div>}
        </div>
        {foot}
      </div>
    </div>
  );
}

window.IndieConn = { FilesIcon, PlugIcon, ConnGlyph, serviceName, reaches, accessLabel, ConnectionsModal };
})();
