            <button class="btn xs warn" data-img="${t.id}">Test Image</button>
            <button class="btn xs warn" data-word="${t.id}">Test Word</button>
            <button class="btn xs danger-o" data-del="${t.id}">Del</button>
          </div>
        </td>
      </tr>`).join("");
  }

  function editorModal(existing){
    const isEdit = !!existing;
    const nm = el("input", {class:"inp", value: existing ? existing.name : "", placeholder:"Invoice template — blue"});
    const sh = el("input", {class:"inp", value: existing ? existing.subject_hint : "", placeholder:"Optional subject hint for this template"});
    const html = el("textarea", {class:"inp code", placeholder:
`<html><body style="font-family:Arial,sans-serif">
  <p>Dear %FirstName%,</p>
  <p>Your invoice <b>%InvoiceNumber%</b> for <b>%TotalAmount%</b> is due on %DueDate%.</p>
  <p><a href="%UnsubscribeLink%">Unsubscribe</a></p>
</body></html>`});
    const txt = el("textarea", {class:"inp", rows:4, placeholder:"Optional plain-text alternative body"});
    const pv = el("div", {class:"pv-frame"}, el("div",{class:"mut",style:"padding:14px"},"Click “Render Preview” to see the sanitized template with sample variables substituted."));
    const frame = el("iframe");

    const buildPreview = () => {
      const sample = html.value
        .replace(/%FirstName%/g,"Alex").replace(/%LastName%/g,"Rivera")
        .replace(/%CompanyName%/g,"Acme Corp").replace(/%CompanyPhone%/g,"+1 555 0100")
        .replace(/%InvoiceNumber%/g,"INV-8492").replace(/%TotalAmount%/g,"$1,240.00")
        .replace(/%RandomTotal%/g,"$1,240.00").replace(/%RandomShippingCharge%/g,"$18.50")
        .replace(/%RandomInvoiceNumber%/g,"INV-8492")
        .replace(/%InvoiceDate%/g,"2025-01-15").replace(/%DueDate%/g,"2025-01-30")
        .replace(/%RandomName%/g,"Jordan Lee")
        .replace(/%UnsubscribeLink%/g,"#").replace(/%CustomerEmail%/g,"alex@example.com");
      pv.innerHTML = "";
      frame.srcdoc = sample;
      pv.appendChild(frame);
    };

    const form = el("div", {class:"form"},
      el("label",{}, "Template name"), nm,
      el("label",{}, "Subject hint"), sh,
      el("div", {class:"tpl-ed"},
        el("div", {}, el("label",{}, "HTML body"), html, el("label",{style:"margin-top:8px"}, "Plain text alternative"), txt),
        el("div", {}, el("label",{}, "Live preview"), pv)),
      el("div",{class:"btns"},
        el("button",{class:"btn secondary",type:"button",onclick:()=>buildPreview()},"Render Preview")));

    openModal(isEdit ? "Edit Template" : "New Template", form, {
      xw: true,
      buttons: [{ label: isEdit ? "Save Changes" : "Create Template", kind:"btn", onClick: async (close) => {
        if (!html.value.trim()) { toast("HTML body is required","err"); return; }
        if (/<script/i.test(html.value)) { toast("Script tags are not allowed","err"); return; }
        if (isEdit) await api(`/templates/${existing.id}`, { method:"PUT", body:{
          name:nm.value, body_html:html.value, body_text:txt.value, subject_hint:sh.value }});
        else await POST("/templates", { name:nm.value, body_html:html.value,
          body_text:txt.value, subject_hint:sh.value });
        toast(isEdit ? "Template saved" : "Template created", "ok");
        close(); await load();
      }}]
    });
  }

  $("#btnNew").addEventListener("click", () => editorModal(null));

  $("#btnUpload").addEventListener("click", () => {
    const f = el("input", {type:"file", accept:".html,.htm,.txt", required:"required"});
    const nm = el("input", {class:"inp", placeholder:"Name (defaults to filename)"});
