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

// /admin/email-templates list page. Fetches per-(key, lang) summaries and
// renders them as cards grouped by key. Each card shows the human title plus
// two language buttons that link into the editor.

interface Summary {
  key: string;
  lang: string;
  is_default: boolean;
  updated_at?: string | null;
}

interface CardCopy {
  title_key: string;
  desc_key: string;
  fallback_title: string;
  fallback_desc: string;
}

const CARDS: Record<string, CardCopy> = {
  invitation: {
    title_key: "admin.email_templates.card.invitation.title",
    desc_key: "admin.email_templates.card.invitation.desc",
    fallback_title: "Einladung",
    fallback_desc:
      "E-Mail an neue Kolleg:innen, ausgelöst über die Sidebar.",
  },
  deadline_digest: {
    title_key: "admin.email_templates.card.deadline_digest.title",
    desc_key: "admin.email_templates.card.deadline_digest.desc",
    fallback_title: "Fristen-Sammelmail",
    fallback_desc:
      "Tägliche Morgen- und Abend-Mail mit überfälligen, heute fälligen und kommenden Fristen.",
  },
  base: {
    title_key: "admin.email_templates.card.base.title",
    desc_key: "admin.email_templates.card.base.desc",
    fallback_title: "Layout-Wrapper",
    fallback_desc:
      "Geteilter HTML-Rahmen mit Header und Footer, der alle E-Mails umschliesst.",
  },
};

const KEY_ORDER = ["invitation", "deadline_digest", "base"];

function fmtDate(iso?: string | null): string {
  if (!iso) return "";
  const d = new Date(iso);
  if (Number.isNaN(d.getTime())) return iso;
  return d.toLocaleDateString();
}

function statusLabel(s: Summary): string {
  if (s.is_default) {
    return t("admin.email_templates.status.default") || "Standard";
  }
  const date = fmtDate(s.updated_at);
  const tpl = t("admin.email_templates.status.last_modified") || "Zuletzt geändert: {date}";
  return tpl.replace("{date}", date);
}

function showFeedback(msg: string, isError: boolean) {
  const el = document.getElementById("admin-et-feedback");
  if (!el) return;
  el.textContent = msg;
  el.className = "form-msg " + (isError ? "form-msg-error" : "form-msg-success");
  el.style.display = "block";
}

function render(summaries: Summary[]) {
  const container = document.getElementById("admin-et-list");
  if (!container) return;

  // Group by key in canonical order.
  const byKey: Record<string, Summary[]> = {};
  for (const s of summaries) {
    (byKey[s.key] ||= []).push(s);
  }

  container.innerHTML = "";
  for (const key of KEY_ORDER) {
    const meta = CARDS[key];
    const rows = byKey[key] || [];
    const card = document.createElement("div");
    card.className = "card admin-et-card";
    const title = tDyn(meta.title_key) || meta.fallback_title;
    const desc = tDyn(meta.desc_key) || meta.fallback_desc;

    const header = document.createElement("div");
    header.className = "admin-et-card-header";
    const h2 = document.createElement("h2");
    h2.textContent = title;
    const code = document.createElement("code");
    code.className = "admin-et-card-key";
    code.textContent = key;
    header.appendChild(h2);
    header.appendChild(code);
    card.appendChild(header);

    const p = document.createElement("p");
    p.textContent = desc;
    card.appendChild(p);

    const langs = document.createElement("div");
    langs.className = "admin-et-card-langs";
    for (const lang of ["de", "en"]) {
      const s = rows.find((r) => r.lang === lang);
      const a = document.createElement("a");
      a.className = "admin-et-card-lang-btn";
      a.href = `/admin/email-templates/${key}?lang=${lang}`;
      const flag = document.createElement("span");
      flag.className = "admin-et-card-lang-flag";
      flag.textContent = lang.toUpperCase();
      const status = document.createElement("span");
      status.className = "admin-et-card-lang-status";
      status.textContent = s ? statusLabel(s) : t("admin.email_templates.status.default") || "Standard";
      a.appendChild(flag);
      a.appendChild(status);
      langs.appendChild(a);
    }
    card.appendChild(langs);

    container.appendChild(card);
  }
}

async function loadAndRender() {
  const resp = await fetch("/api/admin/email-templates");
  if (resp.status === 403) {
    showFeedback(t("admin.team.error.forbidden") || "Nur Admins.", true);
    return;
  }
  if (!resp.ok) {
    showFeedback(t("admin.email_templates.load_error") || "Fehler beim Laden.", true);
    return;
  }
  const summaries = (await resp.json()) as Summary[];
  render(summaries);
}

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