// dashboard-renderconnections.js — extracted verbatim from dashboard.js (pure move).

// ─────────────────────────────────────────────────────────────────
// Merged 2026-05-31: "Connections" and "Accounts" were two separate pages that
// both dealt with accounts and confused users (one to connect, one to manage).
// They are now ONE surface (renderAccounts) with a connect-new header + the full
// manage UI. This route forwards there so existing deep links, the onboarding
// checklist (route:"connections"), and any saved bookmarks keep working.
async function renderConnections() {
  await renderAccounts();
  try {
    await _renderTelegramAddonCard();
  } catch {
    /* non-fatal */
  }
}

// Telegram add-on status card — prepended to the Connections hub. Telegram is
// OPTIONAL: the extension works standalone. This surfaces whether it's connected
// and lets the user attach it via a /pair code (POST /api/telegram/link).
async function _renderTelegramAddonCard() {
  const content = $("#content");
  if (!content) return;
  let cap;
  try {
    cap = await api("capabilities");
  } catch {
    return;
  }
  if (!cap || cap.error) return;

  const linked = !!cap.telegramLinked;
  const enabled = !!cap.telegramEnabled;
  const badge = !enabled
    ? { text: "Unavailable", color: "#888" }
    : linked
      ? { text: "Connected", color: "#3fb950" }
      : { text: "Optional — not connected", color: "#d29922" };

  const card = el("div", { class: "card", style: "margin-bottom:16px;border:1px solid #2a2a38;" });
  card.appendChild(
    el("div", { style: "display:flex;align-items:center;gap:10px;margin-bottom:6px;" }, [
      el("h2", { style: "margin:0;font-size:15px;flex:1;" }, "✈️ Telegram add-on"),
      el("span", { style: `font-size:11px;font-weight:600;color:${badge.color};` }, badge.text),
    ]),
  );

  let body;
  if (!enabled) {
    body =
      "No Telegram bot is configured on the server. The extension runs fully without it — alerts appear in the 🔔 notification center.";
  } else if (linked) {
    body = cap.hasPremiumAccount
      ? "Connected. You'll get DM alerts, and Telegram-channel automations (group activation, TG outreach/scraping/broadcasts) are available."
      : "Connected for DM alerts. Add a Telegram userbot account to unlock Telegram-channel automations (group activation, outreach, scraping, broadcasts).";
  } else {
    body =
      "Optional. Connect Telegram to ALSO receive DM alerts and unlock Telegram-channel automations. Everything else already works. Send /pair to your Nexus bot, then enter the 6-digit code in the extension popup.";
  }
  card.appendChild(el("div", { class: "muted", style: "font-size:12px;line-height:1.5;" }, body));

  // Inline connect (code entry) when not linked but available.
  if (enabled && !linked) {
    const codeInput = el("input", {
      type: "text",
      maxlength: "6",
      placeholder: "000000",
      style:
        "width:120px;text-align:center;letter-spacing:4px;font-family:monospace;margin-top:10px;margin-right:8px;padding:7px;background:#11111a;border:1px solid #2a2a38;border-radius:6px;color:#e0e0e8;",
    });
    const status = el("span", { class: "muted", style: "font-size:11px;margin-left:8px;" });
    const btn = el(
      "button",
      {
        class: "btn btn-secondary",
        type: "button",
        onclick: async () => {
          const code = (codeInput.value || "").trim();
          if (!/^\d{6}$/.test(code)) {
            status.textContent = "Enter the 6-digit code.";
            status.style.color = "#f85149";
            return;
          }
          btn.disabled = true;
          status.textContent = "Connecting…";
          status.style.color = "";
          try {
            const r = await api("telegram-link", { body: { code } });
            if (r?.ok) {
              status.textContent = "Connected!";
              status.style.color = "#3fb950";
              setTimeout(() => renderConnections(), 700);
            } else {
              status.textContent = r?.message || r?.error || "Failed.";
              status.style.color = "#f85149";
            }
          } catch (err) {
            status.textContent = err.message;
            status.style.color = "#f85149";
          } finally {
            btn.disabled = false;
          }
        },
      },
      "Connect",
    );
    card.appendChild(
      el("div", { style: "margin-top:8px;display:flex;align-items:center;flex-wrap:wrap;" }, [
        codeInput,
        btn,
        status,
      ]),
    );
  }

  content.insertBefore(card, content.firstChild);
}

// First-run checklist (endowed progress: step 1 is already done because you're
// in the dashboard). Prepended to Home until complete or dismissed. Goal-gradient
// effect — a visible, partly-done checklist measurably lifts activation.
async function _renderOnboardingChecklist() {
  let dismissed = false;
  try {
    dismissed = localStorage.getItem("_nxOnboardingDone") === "1";
  } catch {}
  if (dismissed) return;

  const [acctRes, objRes, autoRes] = await Promise.all([
    api("accounts-all").catch(() => null),
    api("objectives-list").catch(() => null),
    api("automations-list").catch(() => null),
  ]);
  // accounts-all is platform-keyed ({ twitter, linkedin, telegram, smtp, ... }),
  // not a flat array — flatten the known platform lists to count connections.
  const accts = acctRes
    ? [].concat(
        acctRes.twitter || [],
        acctRes.linkedin || [],
        acctRes.telegram || [],
        acctRes.smtp || [],
      )
    : [];
  const objectives = (objRes && objRes.objectives) || [];
  const goalPicked = objectives.some(
    (o) => o.progress && (o.progress.done_count > 0 || o.progress.started),
  );
  const customs = ((autoRes && autoRes.workflows) || []).filter((w) => w.kind === "custom");
  const anyActive = customs.some((w) => w.status === "active");

  const steps = [
    { done: true, label: "Connect the Nexus bot", hint: "Done — you're here.", route: null },
    {
      done: accts.length > 0,
      label: "Connect a social account",
      hint: "X, LinkedIn, Telegram or Email.",
      route: "connections",
    },
    {
      done: goalPicked,
      label: "Pick a goal",
      hint: "We'll map it to the right automations.",
      route: "objectives",
    },
    {
      done: anyActive,
      label: "Activate an automation",
      hint: "Set up isn't running until you Activate.",
      route: "objectives",
    },
  ];
  const doneCount = steps.filter((s) => s.done).length;
  if (doneCount === steps.length) {
    try {
      localStorage.setItem("_nxOnboardingDone", "1");
    } catch {}
    return;
  }

  const content = $("#content");
  if (!content) return;
  const card = el("div", {
    class: "card",
    style: "margin-bottom:16px;border:1px solid #2a3550;background:#11131c;",
  });
  card.appendChild(
    el("div", { style: "display:flex;align-items:center;gap:10px;margin-bottom:10px;" }, [
      el(
        "h2",
        { style: "margin:0;font-size:15px;flex:1;" },
        `🚀 Get started — ${doneCount}/${steps.length}`,
      ),
      el(
        "button",
        {
          class: "btn btn-tiny btn-secondary",
          onclick: () => {
            try {
              localStorage.setItem("_nxOnboardingDone", "1");
            } catch {}
            card.remove();
          },
        },
        "Dismiss",
      ),
    ]),
  );
  card.appendChild(
    el(
      "div",
      {
        style:
          "height:6px;border-radius:3px;background:#1c1c26;overflow:hidden;margin-bottom:12px;",
      },
      [
        el("div", {
          style: `height:100%;width:${Math.round((doneCount / steps.length) * 100)}%;background:#6C63FF;`,
        }),
      ],
    ),
  );
  for (const s of steps) {
    card.appendChild(
      el("div", { style: "display:flex;align-items:center;gap:10px;padding:7px 0;" }, [
        el(
          "span",
          { style: `font-size:15px;color:${s.done ? "#4ade80" : "#555"};min-width:18px;` },
          s.done ? "✓" : "○",
        ),
        el("div", { style: "flex:1;" }, [
          el(
            "div",
            {
              style: `font-size:13px;${s.done ? "color:#888;text-decoration:line-through;" : "font-weight:500;"}`,
            },
            s.label,
          ),
          s.done
            ? null
            : el("div", { class: "muted", style: "font-size:11px;margin-top:1px;" }, s.hint),
        ]),
        !s.done && s.route
          ? el(
              "button",
              { class: "btn btn-primary btn-tiny", onclick: () => navigate(s.route) },
              "Do it",
            )
          : null,
      ]),
    );
  }
  content.insertBefore(card, content.firstChild);
}

async function renderObjectivesHub() {
  const wrapper = el("div", { class: "objectives-hub", style: "padding:16px;" });
  setContentNode(wrapper);
  wrapper.appendChild(
    el("div", { class: "page-header", style: "margin-bottom:10px;" }, [
      el("h1", { style: "margin:0;font-size:18px;" }, "🎯 Goals"),
      el(
        "p",
        { class: "muted", style: "margin:4px 0 0;font-size:12px;" },
        "Pick what you're trying to achieve — we'll lay out the exact workflows, set them up in one click, and show you how to monitor.",
      ),
    ]),
  );
  _accountRiskBanner()
    .then((b) => {
      if (b) wrapper.insertBefore(b, wrapper.children[1] || null);
    })
    .catch(() => {});
  const grid = el("div", {
    style:
      "display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:12px;margin-top:12px;",
  });
  wrapper.appendChild(grid);
  grid.appendChild(el("div", { class: "muted", style: "font-size:12px;" }, "Loading goals…"));

  // Never let this page go blank: a rejected api() (e.g. stale service worker
  // that doesn't know the "objectives-list" action) used to throw and kill the
  // render after the header — showing the exact empty page you saw. Catch it,
  // and treat an empty list as a diagnosable state, not silence.
  let res = null;
  try {
    res = await api("objectives-list");
  } catch (err) {
    grid.innerHTML = "";
    grid.appendChild(
      el("div", { class: "empty-state", style: "padding:24px;" }, [
        el("div", { class: "empty-state-icon" }, "⚠️"),
        el("div", { class: "empty-state-title" }, "Couldn't reach the bot"),
        el(
          "div",
          { class: "empty-state-hint" },
          `${err.message}. If you just updated the extension, reload it at chrome://extensions (the background service worker may be stale), then make sure the Nexus bot is running.`,
        ),
      ]),
    );
    return;
  }
  grid.innerHTML = "";
  if (!res || res.error) {
    grid.appendChild(
      el("div", { class: "empty-state", style: "padding:24px;" }, [
        el("div", { class: "empty-state-icon" }, "⚠️"),
        el("div", { class: "empty-state-title" }, "Couldn't load goals"),
        el("div", { class: "empty-state-hint" }, res?.error || "unknown error"),
      ]),
    );
    return;
  }
  if (!(res.objectives || []).length) {
    grid.appendChild(
      el("div", { class: "empty-state", style: "padding:24px;" }, [
        el("div", { class: "empty-state-icon" }, "🎯"),
        el("div", { class: "empty-state-title" }, "No goals loaded"),
        el(
          "div",
          { class: "empty-state-hint" },
          "The bot returned an empty list. If you added the Goals feature recently, restart the Nexus bot so it loads src/workflow/objectives/.",
        ),
      ]),
    );
    return;
  }
  for (const o of res.objectives || []) {
    const prog = o.progress || {};
    grid.appendChild(
      el(
        "div",
        {
          class: "card",
          style:
            "border:1px solid #2a2a38;border-radius:10px;padding:14px;cursor:pointer;background:#13131a;",
          onclick: () => navigate("objectives/" + o.id),
        },
        [
          el("div", { style: "font-size:22px;" }, o.icon || "🎯"),
          el("div", { style: "font-weight:600;margin-top:6px;font-size:14px;" }, o.name),
          el(
            "div",
            { class: "muted", style: "font-size:12px;margin-top:4px;line-height:1.4;" },
            o.goal || "",
          ),
          el(
            "div",
            { style: "margin-top:10px;font-size:11px;color:#8a8a9a;" },
            prog.done_count > 0
              ? `✓ ${prog.done_count}/${prog.total_steps} steps set up`
              : `${o.step_count} steps`,
          ),
        ],
      ),
    );
  }
}

async function renderObjectiveDetail(params = {}) {
  const id = params.id;
  const root = el("div", { class: "objective-detail", style: "padding:16px;max-width:840px;" });
  setContentNode(root);
  root.appendChild(
    el(
      "button",
      { class: "btn btn-secondary btn-tiny", onclick: () => navigate("objectives") },
      "« All goals",
    ),
  );
  const mount = el("div", { style: "margin-top:12px;" }, [
    el("div", { class: "muted" }, "Loading…"),
  ]);
  root.appendChild(mount);

  // A preset_clone step's real state, derived from the workflows it cloned:
  //   "none" (not set up) | "draft" (set up, not running) | "active" (running).
  function stepCloneState(step) {
    const customs = (step.type === "preset_clone" && step.existing_customs) || [];
    if (!customs.length)
      return { state: "none", active: 0, total: 0, activeId: null, draftId: null };
    const active = customs.filter((c) => c.status === "active");
    return {
      state: active.length ? "active" : "draft",
      active: active.length,
      total: customs.length,
      activeId: active[0]?.custom_id || null,
      draftId:
        customs.find((c) => c.status === "draft")?.custom_id || customs[0]?.custom_id || null,
    };
  }

  function renderStepRow(o, step, reload) {
    const clone = stepCloneState(step);
    const row = el("div", {
      style:
        "display:flex;align-items:flex-start;gap:10px;padding:10px;border:1px solid #22222c;border-radius:8px;margin-bottom:6px;background:#101015;",
    });
    // Status icon reflects REAL run state, not just "was a draft created".
    let statusIcon, statusColor;
    if (step.type === "preset_clone") {
      if (clone.state === "active") {
        statusIcon = "🟢";
        statusColor = "#4ade80";
      } else if (clone.state === "draft") {
        statusIcon = "⏸";
        statusColor = "#c9a96a";
      } else {
        statusIcon = "⚙️";
        statusColor = "#888";
      }
    } else {
      statusIcon = step.done ? "✓" : step.type === "manual" ? "✋" : "🔗";
      statusColor = step.done ? "#4ade80" : "#888";
    }
    row.appendChild(
      el("div", { style: `font-size:16px;color:${statusColor};min-width:18px;` }, statusIcon),
    );
    const body = el("div", { style: "flex:1;" });
    const titleRow = el(
      "div",
      { style: "display:flex;align-items:center;gap:8px;flex-wrap:wrap;" },
      [el("div", { style: "font-size:13px;font-weight:500;" }, step.label)],
    );
    // Real status pill for preset_clone steps.
    if (step.type === "preset_clone" && clone.state !== "none") {
      const pillStyle =
        clone.state === "active"
          ? "background:#143d2a;color:#4ade80;"
          : "background:#3a3320;color:#c9a96a;";
      titleRow.appendChild(
        el(
          "span",
          { style: `font-size:10px;padding:1px 7px;border-radius:8px;${pillStyle}` },
          clone.state === "active"
            ? `running${clone.total > 1 ? ` ·${clone.active}/${clone.total}` : ""}`
            : "draft · not running",
        ),
      );
    }
    body.appendChild(titleRow);
    if (step.why)
      body.appendChild(
        el(
          "div",
          { class: "muted", style: "font-size:11px;margin-top:2px;line-height:1.4;" },
          step.why,
        ),
      );
    if (step.type === "preset_clone" && step.config_hint)
      body.appendChild(
        el(
          "div",
          { style: "font-size:11px;margin-top:4px;color:#c9a96a;" },
          "Config: " + step.config_hint,
        ),
      );
    if (step.type === "preset_clone" && step.preset_id) {
      body.appendChild(
        el(
          "a",
          {
            href: "#automations/view/" + step.preset_id,
            style: "font-size:11px;color:#6aa9ff;margin-top:4px;display:inline-block;",
          },
          "View action map →",
        ),
      );
    }
    row.appendChild(body);

    const actions = el("div", {
      style: "display:flex;flex-direction:column;gap:4px;min-width:96px;",
    });
    if (step.type === "preset_clone") {
      if (clone.state === "none") {
        // Not set up yet → Set up (clone to draft).
        actions.appendChild(
          el(
            "button",
            {
              class: "btn btn-primary btn-tiny",
              onclick: async (e) => {
                await withProgress(e.target, async () => {
                  const r = await api("objectives-apply-step", { id: o.id, stepId: step.id });
                  if (r?.error) toast(r.error, "err");
                  else toast("Set up as a draft — click Activate to start it running", "ok");
                });
                reload();
              },
            },
            "Set up",
          ),
        );
      } else {
        // Set up already → the key fix: surface Activate + Run now inline so a
        // draft can't silently sit idle (visibility of system status).
        if (clone.state === "draft" && clone.draftId) {
          actions.appendChild(
            el(
              "button",
              {
                class: "btn btn-primary btn-tiny",
                onclick: async (e) => {
                  await withProgress(e.target, async () => {
                    const r = await api("automation-update-custom", {
                      customId: clone.draftId,
                      body: { status: "active" },
                    });
                    if (r?.error) toast(r.error, "err");
                    else toast("Activated — it now runs on schedule", "ok");
                  });
                  reload();
                },
              },
              "▶ Activate",
            ),
          );
        }
        if (clone.state === "active" && clone.activeId) {
          actions.appendChild(
            el(
              "button",
              {
                class: "btn btn-secondary btn-tiny",
                onclick: async (e) => {
                  await withProgress(e.target, async () => {
                    const r = await api("automation-update-custom", {
                      customId: clone.activeId,
                      body: { status: "paused" },
                    });
                    if (r?.error) toast(r.error, "err");
                    else toast("Paused", "ok");
                  });
                  reload();
                },
              },
              "⏸ Pause",
            ),
          );
        }
        const runId = clone.activeId || clone.draftId;
        if (runId) {
          actions.appendChild(
            el(
              "button",
              {
                class: "btn btn-secondary btn-tiny",
                onclick: async (e) => {
                  const __pv = await runWithPreview("custom_workflow", runId, {});
                  if (!__pv?.confirmed) return;
                  await withProgress(e.target, async () => {
                    const r = await api("automation-run-now", { customId: runId });
                    if (r?.error || r?.wired === false)
                      toast(r?.error || "Engine wiring in progress", "err");
                    else
                      toast("Test run started — check the workflow for results", "ok", 5000, () =>
                        navigate("workflows"),
                      );
                  });
                },
              },
              "Run now",
            ),
          );
        }
      }
    } else if (step.deep_link) {
      actions.appendChild(
        el(
          "button",
          { class: "btn btn-secondary btn-tiny", onclick: () => navigate(step.deep_link) },
          "Open",
        ),
      );
    } else if (step.type === "manual") {
      actions.appendChild(
        el(
          "button",
          {
            class: `btn btn-tiny ${step.done ? "btn-primary" : "btn-secondary"}`,
            onclick: async () => {
              await api("objectives-patch", {
                id: o.id,
                body: { step: { id: step.id, done: !step.done } },
              });
              reload();
            },
          },
          step.done ? "✓ Done" : "Mark done",
        ),
      );
    }
    row.appendChild(actions);
    return row;
  }

  // Count preset_clone steps by real state for the activation summary.
  function activationSummary(o) {
    let setUp = 0,
      active = 0,
      total = 0;
    for (const phase of o.phases || []) {
      for (const step of phase.steps || []) {
        if (step.type !== "preset_clone") continue;
        total++;
        const c = stepCloneState(step);
        if (c.state !== "none") setUp++;
        if (c.state === "active") active++;
      }
    }
    return { setUp, active, total };
  }

  async function load() {
    const res = await api("objectives-get", { id });
    mount.innerHTML = "";
    if (!res || res.error) {
      mount.appendChild(el("div", { class: "muted" }, `Couldn't load: ${res?.error || "error"}`));
      return;
    }
    const o = res.objective;

    mount.appendChild(
      el("div", {}, [
        el("h1", { style: "margin:0;font-size:20px;" }, `${o.icon || "🎯"} ${o.name}`),
        el("p", { class: "muted", style: "margin:4px 0 0;font-size:13px;" }, o.goal || ""),
      ]),
    );

    // Inputs form (personalizes the config hints applied on setup)
    if ((o.inputs || []).length) {
      const inputsState = { ...(res.progress?.inputs || {}) };
      const form = el("div", {
        style:
          "margin-top:14px;padding:12px;border:1px solid #2a2a38;border-radius:8px;background:#13131a;",
      });
      form.appendChild(
        el(
          "div",
          { style: "font-weight:600;font-size:13px;margin-bottom:8px;" },
          "Tell us a bit (personalizes the setup)",
        ),
      );
      for (const inp of o.inputs) {
        const cur = inputsState[inp.key];
        form.appendChild(
          el(
            "label",
            { style: "font-size:11px;color:#9a9aa8;display:block;margin-bottom:2px;" },
            inp.label,
          ),
        );
        form.appendChild(
          el("input", {
            type: "text",
            value: Array.isArray(cur) ? cur.join(", ") : cur || "",
            placeholder: inp.placeholder || "",
            style:
              "width:100%;margin-bottom:8px;padding:6px 8px;background:#0d0d12;border:1px solid #2a2a38;border-radius:6px;color:#eee;font-size:12px;box-sizing:border-box;",
            oninput: (e) => {
              inputsState[inp.key] =
                inp.type === "list"
                  ? e.target.value
                      .split(",")
                      .map((s) => s.trim())
                      .filter(Boolean)
                  : e.target.value;
            },
          }),
        );
      }
      form.appendChild(
        el(
          "button",
          {
            class: "btn btn-secondary btn-tiny",
            onclick: async (e) => {
              await withProgress(e.target, async () => {
                await api("objectives-patch", { id, body: { inputs: inputsState } });
              });
              toast("Saved", "ok");
            },
          },
          "Save details",
        ),
      );
      mount.appendChild(form);
    }

    // Activation summary — the core "draft trap" fix: always tell the user how
    // many of the automations they set up are ACTUALLY running, with one click
    // to activate the rest. (Nielsen #1 — visibility of system status.)
    const sum = activationSummary(o);
    if (sum.total > 0) {
      const idle = sum.setUp - sum.active;
      const banner = el("div", {
        style: `margin-top:14px;padding:10px 12px;border-radius:8px;display:flex;align-items:center;gap:10px;flex-wrap:wrap;border:1px solid ${idle > 0 ? "#3a3320" : "#143d2a"};background:${idle > 0 ? "#1c1812" : "#0f1a13"};`,
      });
      banner.appendChild(
        el("div", { style: "flex:1;font-size:12px;" }, [
          el(
            "span",
            { style: "font-weight:600;" },
            `${sum.active}/${sum.total} automations running`,
          ),
          el(
            "span",
            { class: "muted", style: "margin-left:8px;" },
            sum.setUp === 0
              ? "Nothing set up yet — Set up the steps below."
              : idle > 0
                ? `${idle} set up but not running.`
                : "All set up and running. 🎉",
          ),
        ]),
      );
      if (idle > 0) {
        // Activate every draft this objective created, in one click.
        banner.appendChild(
          el(
            "button",
            {
              class: "btn btn-primary btn-tiny",
              onclick: async (e) => {
                await withProgress(e.target, async () => {
                  const drafts = [];
                  for (const phase of o.phases || [])
                    for (const step of phase.steps || []) {
                      if (step.type !== "preset_clone") continue;
                      const c = stepCloneState(step);
                      if (c.state === "draft" && c.draftId) drafts.push(c.draftId);
                    }
                  let ok = 0;
                  for (const cid of drafts) {
                    const r = await api("automation-update-custom", {
                      customId: cid,
                      body: { status: "active" },
                    });
                    if (!r?.error) ok++;
                  }
                  toast(`Activated ${ok} automation(s)`, ok ? "ok" : "err");
                });
                load();
              },
            },
            `▶ Activate ${idle}`,
          ),
        );
      }
      mount.appendChild(banner);
    }

    // Bulk setup
    mount.appendChild(
      el("div", { style: "margin-top:14px;" }, [
        el(
          "button",
          {
            class: "btn btn-primary btn-tiny",
            onclick: async (e) => {
              await withProgress(e.target, async () => {
                const r = await api("objectives-apply-all", { id });
                if (r?.error) toast(r.error, "err");
                else
                  toast(
                    `Set up ${r.created?.length || 0} workflow(s) as drafts — now Activate them above`,
                    "ok",
                  );
              });
              load();
            },
          },
          "⚙️ Set up all workflows",
        ),
      ]),
    );

    // Phases + steps
    for (const phase of o.phases || []) {
      mount.appendChild(el("h3", { style: "margin:18px 0 6px;font-size:14px;" }, phase.title));
      for (const step of phase.steps || []) mount.appendChild(renderStepRow(o, step, load));
    }

    // Monitor
    if ((o.monitor || []).length) {
      const mon = el("div", {
        style:
          "margin-top:20px;padding:12px;border:1px solid #2a2a38;border-radius:8px;background:#13131a;",
      });
      mon.appendChild(
        el(
          "div",
          { style: "font-weight:600;font-size:13px;margin-bottom:8px;" },
          "📊 How to monitor",
        ),
      );
      for (const m of o.monitor) {
        if (m.deepLink)
          mon.appendChild(
            el(
              "a",
              {
                href: "#" + m.deepLink,
                style: "display:block;font-size:12px;color:#6aa9ff;margin-bottom:4px;",
              },
              `→ ${m.label}`,
            ),
          );
        else
          mon.appendChild(
            el(
              "div",
              { style: "font-size:12px;color:#bbb;margin-bottom:4px;" },
              `${m.label}${m.command ? ` — ${m.command}` : ""}`,
            ),
          );
      }
      mount.appendChild(mon);
    }
  }

  await load();
}
