window.pageBoot = async (me) => {
  const [acc, tpl] = await Promise.all([GET("/test-send/accounts"), GET("/test-send/templates")]);
  const accSel = $("#account"), tplSel = $("#template");
  (acc.accounts || []).forEach(a => accSel.append(el("option", {value:a.id}, `${a.email} (${(a.sending_method||"api").toUpperCase()})`)));
  (tpl.templates || []).forEach(t => tplSel.append(el("option", {value:t.id}, t.name)));
  if (!(acc.accounts||[]).length)
    $("#result").innerHTML = `<div class="notice warn">No authorized Gmail accounts available. Connect and authorize an account first (Gmail Accounts page).</div>`;
  if (!(tpl.templates||[]).length)
    tplSel.append(el("option", {value:""}, "— none —"));

  $("#srcMode").addEventListener("change", () => {
    const tplMode = $("#srcMode").value === "template";
    $("#tplWrap").style.display = tplMode ? "" : "none";
    $("#rawWrap").style.display = tplMode ? "none" : "";
  });

  $("#form").addEventListener("submit", async (e) => {
    e.preventDefault();
    const btn = $("#sendBtn"); btn.disabled = true; btn.textContent = "Sending via Gmail…";
    $("#result").innerHTML = `<div class="notice">Sending — this performs a real send through the Gmail API/SMTP of the selected account…</div>`;
    const payload = {
      account_id: +$("#account").value,
      to_email: $("#to").value.trim(),
      subject: $("#subject").value.trim(),
      include_pdf: $("#incPdf").checked,
      use_random_variables: $("#useVars").checked,
    };
    if ($("#srcMode").value === "template") {
      if (!$("#template").value) { toast("Select a template or switch to raw HTML","err"); btn.disabled=false; btn.textContent="Send Test Email"; return; }
      payload.template_id = +$("#template").value;
    } else {
      payload.body_html = $("#bodyHtml").value;
    }
    try {
      const d = await POST("/test-send/send", payload);
      const ok = d.ok;
      const kv = [
        ["Result", ok ? "ACCEPTED by Gmail" : (d.stage || "FAILED")],
        ["Detail", d.detail || ""],
        ["Message ID", d.message_id || "—"],
        ["Thread ID", d.thread_id || "—"],
        ["Method", d.method ? d.method.toUpperCase() : "—"],
        ["Provider response", d.provider_response || "—"],
        ["Elapsed", d.elapsed_ms != null ? d.elapsed_ms + " ms" : "—"],
      ];
      const rows = kv.map(([k,v]) => v ? `<div><b>${esc(k)}</b></div><div class="mono" style="font-size:.82rem">${esc(v)}</div>` : "").join("");
      $("#result").innerHTML = `
        <div class="result-box ${ok ? "ok" : "bad"}">
          <div style="font-weight:700;font-size:1.05rem;color:${ok ? "#065f46" : "#991b1b"}">
            ${ok ? "✓ Gmail accepted the message" : "✕ Gmail did not accept the message"}</div>
          <div class="kv">${rows}</div>
          ${ok ? "" : `<div class="mut" style="font-size:.8rem;margin-top:8px">The system never reports fake success — this is the provider's real response.</div>`}
        </div>`;
      toast(ok ? "Test email accepted by Gmail" : "Test send failed (see details)", ok ? "ok" : "err", 6000);
    } catch (err) {
      $("#result").innerHTML = `<div class="result-box bad"><div style="font-weight:700">✕ Send attempt failed</div>
        <div class="kv"><div><b>Error</b></div><div>${esc(err.message)}</div></div></div>`;
      toast("Test send error: " + err.message, "err", 7000);
    } finally {
      btn.disabled = false; btn.textContent = "Send Test Email";
    }
  });
};
===HTML buttons===
31:        <select class="inp" id="account" required></select>
33:        <input class="inp" type="email" id="to" required placeholder="you@example.com">
35:        <input class="inp" id="subject" required placeholder="Test: Invoice %InvoiceNumber% for %FirstName%">
37:        <select class="inp" id="srcMode">
40:        </select>
43:          <select class="inp" id="template"></select>
49:        <label class="chk"><input type="checkbox" id="useVars" checked> Substitute random variables (invoice number, amount, shipping, dates)</label>
50:        <label class="chk"><input type="checkbox" id="incPdf"> Include PDF attachment (rendered from the resolved HTML)</label>
52:          <button class="btn" type="submit" id="sendBtn">Send Test Email</button>
