window.pageBoot = async (me) => {
  let tab = "attempts";
  let campaigns = [];
  let st = { attempts: 1, events: 1, audit: 1, dlq: 1 };
  const PS = 50;
  const OUTCOMES = ["", "submitted", "accepted", "temp_failed", "perm_failed", "skipped"];
  const OUT_BADGE = { submitted: "b-blue", accepted: "b-green", temp_failed: "b-amber",
                      perm_failed: "b-red", skipped: "b-gray", sent: "b-green",
                      suppressed: "b-violet", bounced: "b-red" };

  const sel = (id, opts, val) => `<select id="${id}">` + opts.map(o =>
    `<option value="${esc(o.v)}" ${o.v === (val ?? "") ? "selected" : ""}>${esc(o.t)}</option>`).join("") + "</select>";

  async function loadCampaigns() {
    try { const d = await GET("/campaigns/list?page_size=100"); campaigns = d.campaigns || []; }
    catch { campaigns = []; }
  }

  function renderFilters() {
    const f = $("#filters");
    const campOpts = [{ v: "", t: "All campaigns" }].concat(
      campaigns.map(c => ({ v: String(c.id), t: `#${c.id} — ${c.name}`.slice(0, 60) })));
    if (tab === "attempts") {
      f.innerHTML =
        sel("fCamp", campOpts, st._camp || "") +
        sel("fOutcome", OUTCOMES.map(o => ({ v: o, t: o ? o.replace("_", " ") : "All outcomes" })), st._out || "") +
        `<input id="fSearch" placeholder="Search email or message id…" value="${esc(st._q || "")}">` +
        `<button class="btn sm" id="fGo">Apply</button>`;
      $("#fGo").onclick = applyFilters;
      $("#fSearch").onkeydown = e => { if (e.key === "Enter") applyFilters(); };
    } else if (tab === "events") {
      f.innerHTML =
        sel("fCamp", campOpts, st._camp || "") +
        sel("fEvType", ["", "queued", "submitted", "accepted", "failed", "retry_scheduled",
                        "suppressed", "unsubscribed", "bounced", "dlq"].map(o =>
          ({ v: o, t: o ? o.replace("_", " ") : "All event types" })), st._ev || "") +
        `<button class="btn sm" id="fGo">Apply</button>`;
      $("#fGo").onclick = applyFilters;
    } else if (tab === "audit") {
      f.innerHTML =
        sel("fAction", ["", "auth.login", "auth.register", "campaign.create", "campaign.start",
                        "campaign.pause", "campaign.resume", "campaign.cancel",
                        "recipients.import", "recipients.manual_add", "subjects.import",
                        "templates.upload", "attachments.upload", "phones.import",
                        "suppression.add", "gmail.connect", "gmail.disconnect", "gmail.import_config",
                        "settings.save_batch", "settings.reset"].map(o =>
          ({ v: o, t: o ? o.replace(/\./g, " › ") : "All actions" })), st._act || "") +
        `<button class="btn sm" id="fGo">Apply</button>`;
      $("#fGo").onclick = applyFilters;
    } else {
      f.innerHTML = `<span class="muted small">Jobs that exhausted all retries and were moved to the dead-letter queue (dlq:send).</span>`;
    }
  }

  function applyFilters() {
    if (tab === "attempts") {
      st._camp = $("#fCamp").value; st._out = $("#fOutcome").value; st._q = $("#fSearch").value.trim();
    } else if (tab === "events") {
      st._camp = $("#fCamp").value; st._ev = $("#fEvType").value;
    } else if (tab === "audit") {
      st._act = $("#fAction").value;
    }
    st[tab] = 1;
    load();
  }

  function pagerHTML(total, page, key) {
    const pages = Math.max(1, Math.ceil(total / PS));
    if (pages <= 1) return "";
    return `<button class="btn sm secondary" ${page <= 1 ? "disabled" : ""} data-pg="${page - 1}">‹ Prev</button>
      <span class="small muted">Page ${page} of ${pages} · ${total} records</span>
      <button class="btn sm secondary" ${page >= pages ? "disabled" : ""} data-pg="${page + 1}">Next ›</button>`;
  }

  function bindPager(key) {
    $$("#pager [data-pg]").forEach(b => b.onclick = () => { st[key] = parseInt(b.dataset.pg, 10); load(); });
  }

  function badge(v) { return `<span class="badge ${OUT_BADGE[v] || "b-gray"}">${esc(v || "—")}</span>`; }

  async function load() {
    const box = $("#listing");
    box.innerHTML = `<div class="skeleton" style="width:60%"></div><div class="skeleton"></div><div class="skeleton" style="width:80%"></div>`;
    try {
      if (tab === "attempts") {
        const p = new URLSearchParams({ campaign_id: st._camp || 0, outcome: st._out || "",
                                       search: st._q || "", page: st.attempts, page_size: PS });
        const d = await GET("/logs/list?" + p);
        const rows = d.logs || [];
        box.innerHTML = rows.length ? `<div class="tbl-wrap"><table class="tbl">
          <thead><tr><th>#</th><th>Time</th><th>Email</th><th>Outcome</th><th>Attempt</th><th>Error class</th><th>Error / provider response</th><th>Message ID</th><th></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>${esc(r.email || "")}</td>
            <td>${badge(r.outcome)}</td>
            <td class="center">${r.attempt_number}</td>
            <td>${r.error_class ? `<span class="mono-s">${esc(r.error_class)}</span>` : "—"}</td>
            <td class="err-cell" title="${esc(r.error_message || r.provider_response || "")}">${esc((r.error_message || r.provider_response || "").slice(0, 120) || "—")}</td>
            <td class="mono-s" title="${esc(r.message_id || "")}">${r.message_id ? esc(r.message_id.slice(0, 18)) + "…" : "—"}</td>
            <td><button class="btn xs secondary" data-hist="${r.campaign_recipient_id}">History</button></td>
          </tr>`).join("")}</tbody></table></div>`
          : `<div class="empty-state"><div class="e-ico">≡</div><p>No send attempts match these filters yet.</p></div>`;
        $("#pager").innerHTML = pagerHTML(d.total, d.page, "attempts");
        bindPager("attempts");
        $$("#listing [data-hist]").forEach(b => b.onclick = () => showHistory(parseInt(b.dataset.hist, 10)));
      } else if (tab === "events") {
        const p = new URLSearchParams({ campaign_id: st._camp || 0, event_type: st._ev || "",
                                       page: st.events, page_size: PS });
        const d = await GET("/logs/events?" + p);
        const rows = d.events || [];
        box.innerHTML = rows.length ? `<div class="tbl-wrap"><table class="tbl">
          <thead><tr><th>#</th><th>Time</th><th>Campaign</th><th>Email</th><th>Event</th><th>Detail</th><th>Message ID</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 class="mono-s">#${r.campaign_id}</td>
            <td>${esc(r.email || "")}</td>
            <td>${badge(r.event_type)}</td>
            <td class="err-cell" title="${esc(r.detail || "")}">${esc(r.detail || "—")}</td>
