  $("#btnConnect").addEventListener("click", async () => {
    const btn = $("#btnConnect"); btn.disabled = true; btn.textContent = "Starting…";
    try {
      const d = await POST("/gmail/accounts/connect");
      const url = d.authorization_url || d.url || d.auth_url;
      if (!url) throw new Error("No authorization URL returned");
      // Navigate the current tab to Google's consent screen (popup blockers
      // kill window.open() after an await, so we use a direct navigation).
      sessionStorage.setItem("oauth_start_url", url);
      location.href = url;
    } catch (e) {
      toast("Connect failed: " + e.message, "err");
      btn.disabled = false; btn.textContent = "Connect Gmail Account";
    }
  });

  // ---- Import OAuth client config ----
  $("#btnImportCfg").addEventListener("click", () => {
    $("#cfgCard").style.display = $("#cfgCard").style.display === "none" ? "" : "none";
  });
    });
  });

  // ---- Row actions ----
  $("#accBody").addEventListener("click", async (e) => {
    const b = e.target.closest("button"); if (!b) return;
    const id = b.dataset.test || b.dataset.edit || b.dataset.reauth || b.dataset.disc;
    if (b.dataset.test) {
      b.disabled = true; b.textContent = "Testing…";
      try {
        const d = await POST(`/gmail/accounts/${id}/test`);
        if (d.ok) toast("Connection verified: " + (d.detail || "Gmail profile OK"), "ok");
        else toast("Test failed: " + (d.detail || d.error || "unknown"), "err");
        await load();
      } finally { b.disabled = false; b.textContent = "Test"; }
    }
    if (b.dataset.reauth) {
      try {
        const d = await POST(`/gmail/accounts/${id}/reauthorize`);
        if (d.authorization_url) {
          // Direct navigation (no popup-blocker risk)
          location.href = d.authorization_url;
        }
      } catch (err) { toast("Reauthorize failed: " + err.message, "err"); }
    }
    if (b.dataset.edit) {
      const a = state.accounts.find(x => x.id == id);
      const dm = el("select", {class:"inp"}, ...[["api","Gmail API (recommended)"],["smtp","SMTP XOAUTH2"]].map(([v,l]) =>
        el("option", {value:v, selected:(a.sending_method||"api")===v}, l)));
      const dl = el("input", {class:"inp", type:"number", value:a.daily_limit, min:1, max:2000});
      const cl = el("input", {class:"inp", type:"number", value:a.campaign_limit, min:1, max:2000});
