// admin-broadcasts.ts — read-only viewer for paliad.email_broadcasts.
//
// global_admin sees every row; senders see only their own. Authority is
// enforced server-side; this client just renders whatever /api/admin/broadcasts
// returns. Click a row → load detail (subject, body, recipient list).

import { initI18n, onLangChange, t } from "./i18n";
import { initSidebar } from "./sidebar";

interface BroadcastRow {
  id: string;
  subject: string;
  sender_id: string;
  sender_name: string;
  sender_email: string;
  recipient_count: number;
  sent_at: string;
  template_key?: string;
}

interface BroadcastDetailRecipient {
  id: string;
  email: string;
  display_name: string;
}

interface BroadcastDetail extends BroadcastRow {
  body: string;
  recipient_filter: Record<string, unknown>;
  send_report: { total: number; sent: number; failed: number };
  recipients: BroadcastDetailRecipient[];
}

let rows: BroadcastRow[] = [];

function esc(s: string): string {
  const d = document.createElement("div");
  d.textContent = s;
  return d.innerHTML;
}

function fmtDate(iso: string): string {
  const d = new Date(iso);
  if (isNaN(d.getTime())) return iso;
  return d.toLocaleString();
}

async function load(): Promise<void> {
  const tbody = document.getElementById("broadcasts-tbody")!;
  const empty = document.getElementById("broadcasts-empty")!;
  try {
    const res = await fetch("/api/admin/broadcasts");
    if (!res.ok) {
      if (res.status === 403) {
        tbody.innerHTML = `<tr><td colspan="4">${esc(t("common.forbidden") || "Zugriff verweigert.")}</td></tr>`;
        return;
      }
      tbody.innerHTML = `<tr><td colspan="4">${esc(t("common.load_error") || "Fehler beim Laden.")}</td></tr>`;
      return;
    }
    rows = (await res.json()) as BroadcastRow[];
  } catch {
    tbody.innerHTML = `<tr><td colspan="4">${esc(t("common.load_error") || "Fehler beim Laden.")}</td></tr>`;
    return;
  }
  if (!rows.length) {
    tbody.innerHTML = "";
    empty.style.display = "block";
    return;
  }
  empty.style.display = "none";
  tbody.innerHTML = rows
    .map(
      (r) => `
    <tr data-broadcast-id="${esc(r.id)}">
      <td>${esc(fmtDate(r.sent_at))}</td>
      <td>${esc(r.subject)}</td>
      <td>${esc(r.sender_name || r.sender_email || "—")}</td>
      <td>${r.recipient_count}</td>
    </tr>
  `,
    )
    .join("");
  tbody.querySelectorAll<HTMLTableRowElement>("tr[data-broadcast-id]").forEach((tr) => {
    tr.addEventListener("click", () => loadDetail(tr.dataset.broadcastId!));
    tr.style.cursor = "pointer";
  });
}

async function loadDetail(id: string): Promise<void> {
  const detail = document.getElementById("broadcast-detail")!;
  detail.classList.remove("hidden");
  detail.innerHTML = `<p>${esc(t("common.loading") || "Lade…")}</p>`;
  try {
    const res = await fetch(`/api/admin/broadcasts/${encodeURIComponent(id)}`);
    if (!res.ok) {
      detail.innerHTML = `<p>${esc(t("common.load_error") || "Fehler beim Laden.")}</p>`;
      return;
    }
    const d = (await res.json()) as BroadcastDetail;
    const recList = (d.recipients || [])
      .map(
        (r) =>
          `<li>${esc(r.display_name || "—")} <span class="broadcast-recip-email">&lt;${esc(r.email)}&gt;</span></li>`,
      )
      .join("");
    const report = d.send_report || { total: d.recipient_count, sent: d.recipient_count, failed: 0 };
    detail.innerHTML = `
      <article class="card broadcast-detail-card">
        <header>
          <h2>${esc(d.subject)}</h2>
          <p class="muted">
            ${esc(t("admin.broadcasts.detail.sent_by") || "Gesendet von")} <strong>${esc(d.sender_name || d.sender_email)}</strong>
            • ${esc(fmtDate(d.sent_at))}
            • ${report.sent}/${report.total} ${esc(t("admin.broadcasts.detail.delivered") || "versandt")}
            ${report.failed > 0 ? ` • ${report.failed} ${esc(t("admin.broadcasts.detail.failed") || "fehlgeschlagen")}` : ""}
          </p>
        </header>
        <div class="broadcast-detail-body">${esc(d.body)}</div>
        <section class="broadcast-detail-recipients">
          <h3>${esc(t("admin.broadcasts.detail.recipients") || "Empfänger")} (${d.recipients?.length ?? 0})</h3>
          <ul>${recList}</ul>
        </section>
      </article>
    `;
    detail.scrollIntoView({ behavior: "smooth", block: "nearest" });
  } catch {
    detail.innerHTML = `<p>${esc(t("common.load_error") || "Fehler beim Laden.")}</p>`;
  }
}

document.addEventListener("DOMContentLoaded", () => {
  initI18n();
  initSidebar();
  onLangChange(() => load());
  load();
});
