            <td class="err-cell" title="${esc(r.detail || "")}">${esc(r.detail || "—")}</td>
            <td class="mono-s">${r.message_id ? esc(r.message_id.slice(0, 16)) + "…" : "—"}</td>
          </tr>`).join("")}</tbody></table></div>`
          : `<div class="empty-state"><div class="e-ico">⟐</div><p>No email events yet. Events appear as campaign messages are queued, submitted and accepted.</p></div>`;
        $("#pager").innerHTML = pagerHTML(d.total, d.page, "events");
        bindPager("events");
      } else if (tab === "audit") {
        const p = new URLSearchParams({ action: st._act || "", page: st.audit, page_size: PS });
        const d = await GET("/logs/audit?" + p);
        const rows = d.audit || [];
        box.innerHTML = rows.length ? `<div class="tbl-wrap"><table class="tbl">
          <thead><tr><th>#</th><th>Time</th><th>Action</th><th>Entity</th><th>Detail</th><th>IP</th></tr></thead>
          <tbody>${rows.map(r => `<tr>
            <td class="mono-s">${r.id}</td>
            <td class="nowrap small">${fmtDT(r.created_at)}</td>
            <td><span class="badge b-violet">${esc(r.action)}</span></td>
            <td class="small">${esc(r.entity || "—")}${r.entity_id ? ` #${r.entity_id}` : ""}</td>
            <td class="err-cell mono-s" title="${esc(JSON.stringify(r.detail || {}))}">${esc(JSON.stringify(r.detail || {}).slice(0, 140))}</td>
            <td class="mono-s">${esc(r.ip_address || "—")}</td>
          </tr>`).join("")}</tbody></table></div>`
          : `<div class="empty-state"><div class="e-ico">☰</div><p>No audit entries yet. Administrative actions are recorded here.</p></div>`;
        $("#pager").innerHTML = pagerHTML(d.total, d.page, "audit");
        bindPager("audit");
      } else {
        const d = await GET(`/logs/dlq?page=${st.dlq}&page_size=PS`);
        if (d.error) {
          box.innerHTML = `<div class="notice warn"><span class="n-ico">⚠</span><div>${esc(d.error)}</div></div>`;
        } else {
          const items = d.dlq || [];
          box.innerHTML = items.length ? items.map((it, i) => {
            const idx = (d.page - 1) * PS + i + 1;
            const email = it.recipient_email || it.email || it.args?.recipient_email || "?";
            const reason = it.reason || it.error || (it.exc_message || "");
            return `<div class="dlq-item">
              <div class="flex-between">
                <div><strong>#${idx}</strong> · ${esc(email)} ${it.campaign_id ? `· campaign #${it.campaign_id}` : ""}</div>
                <span class="badge b-red">dead-lettered</span>
              </div>
              ${reason ? `<div class="small mt-1"><strong>Reason:</strong> ${esc(String(reason).slice(0, 300))}</div>` : ""}
              <pre>${esc(JSON.stringify(it, null, 2).slice(0, 3000))}</pre>
            </div>`;
          }).join("") : `<div class="empty-state"><div class="e-ico">✓</div><p>Dead-letter queue is empty. No jobs have exhausted their retries.</p></div>`;
          $("#pager").innerHTML = pagerHTML(d.total, d.page, "dlq");
          bindPager("dlq");
        }
      }
    } catch (e) {
      box.innerHTML = `<div class="notice err"><span class="n-ico">✕</span><div>${esc(e.message)}</div></div>`;
    }
  }

  async function showHistory(crId) {
    let d;
    try { d = await GET(`/logs/recipient/${crId}/history`); }
    catch (e) { toast(e.message, "err"); return; }
    const r = d.recipient || {};
    const node = el("div", {},
      el("dl", { class: "kv" },
        el("dt", {}, "Email"), el("dd", {}, r.email || "—"),
        el("dt", {}, "Seq"), el("dd", {}, String(r.seq ?? "—")),
        el("dt", {}, "Final status"), el("dd", { html: badge(r.status) }),
        el("dt", {}, "Invoice number"), el("dd", {}, r.invoice_number || "—"),
        el("dt", {}, "Amount"), el("dd", {}, r.amount != null ? fmtMoney(r.amount) : "—"),
        el("dt", {}, "Message ID"), el("dd", {}, r.message_id || "—"),
        el("dt", {}, "Last error"), el("dd", {}, r.last_error || "—")),
      el("div", { class: "hist-sec" },
        el("h4", {}, `Send attempts (${(d.attempts || []).length})`),
        (d.attempts || []).length ? el("div", { class: "tbl-wrap" }, el("table", { class: "tbl", html:
          `<thead><tr><th>Time</th><th>#</th><th>Outcome</th><th>Error class</th><th>Error</th><th>Provider response</th></tr></thead>
           <tbody>${(d.attempts || []).map(a => `<tr>
             <td class="nowrap small">${fmtDT(a.created_at)}</td><td class="center">${a.attempt_number}</td>
             <td>${badge(a.outcome)}</td><td class="mono-s">${esc(a.error_class || "—")}</td>
             <td class="err-cell" title="${esc(a.error_message || "")}">${esc((a.error_message || "—").slice(0, 120))}</td>
             <td class="err-cell" title="${esc(a.provider_response || "")}">${esc((a.provider_response || "—").slice(0, 120))}</td>
           </tr>`).join("")}</tbody>` })) : el("p", { class: "muted small" }, "No attempts recorded.")),
      el("div", { class: "hist-sec" },
        el("h4", {}, `Events (${(d.events || []).length})`),
        (d.events || []).length ? el("div", { class: "tbl-wrap" }, el("table", { class: "tbl", html:
          `<thead><tr><th>Time</th><th>Event</th><th>Detail</th></tr></thead>
           <tbody>${(d.events || []).map(e => `<tr>
             <td class="nowrap small">${fmtDT(e.created_at)}</td><td>${badge(e.event_type)}</td>
             <td class="err-cell" title="${esc(e.detail || "")}">${esc(e.detail || "—")}</td>
           </tr>`).join("")}</tbody>` })) : el("p", { class: "muted small" }, "No events recorded.")));
    openModal(`Recipient history — ${r.email || "#" + crId}`, node, { wide: true });
  }

  $$("#tabs .tab").forEach(t => t.onclick = () => {
    $$("#tabs .tab").forEach(x => x.classList.remove("active"));
    t.classList.add("active");
    tab = t.dataset.tab;
    renderFilters();
    load();
  });

  $("#btnExport").onclick = () => {
    const p = new URLSearchParams();
    if (tab === "attempts" || tab === "events") { if (st._camp) p.set("campaign_id", st._camp); }
    if (tab === "attempts" && st._out) p.set("outcome", st._out);
    const qs = p.toString();
    window.location = "/logs/export" + (qs ? "?" + qs : "");
    toast("CSV export downloading…", "ok");
  };

  await loadCampaigns();
  renderFilters();
  load();
};
