import { getLang, initI18n, onLangChange, t, tDyn } from "./i18n";
import { initSidebar } from "./sidebar";
import { markChangelogSeen } from "./changelog-seen";

interface Entry {
  date: string;
  title_de: string;
  title_en: string;
  body_de: string;
  body_en: string;
  tag: "feature" | "content" | "fix";
}

let entries: Entry[] = [];

async function load(): Promise<void> {
  const resp = await fetch("/api/changelog");
  if (!resp.ok) return;
  entries = await resp.json();
  render();
}

function formatDate(iso: string): string {
  // iso = YYYY-MM-DD. Render locale-aware without Intl allocations per row:
  // "20. April 2026" (DE) or "20 April 2026" (EN). Cheap and deterministic.
  const [y, m, d] = iso.split("-");
  if (!y || !m || !d) return iso;
  const monthsDE = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"];
  const monthsEN = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  const monthIdx = parseInt(m, 10) - 1;
  const day = parseInt(d, 10);
  if (getLang() === "en") {
    return `${day} ${monthsEN[monthIdx] ?? m} ${y}`;
  }
  return `${day}. ${monthsDE[monthIdx] ?? m} ${y}`;
}

function escapeHTML(s: string): string {
  return s
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

function render(): void {
  const list = document.getElementById("changelog-list") as HTMLOListElement | null;
  const empty = document.getElementById("changelog-empty") as HTMLElement | null;
  if (!list || !empty) return;

  if (entries.length === 0) {
    list.innerHTML = "";
    empty.style.display = "block";
    return;
  }
  empty.style.display = "none";

  const lang = getLang();
  list.innerHTML = entries.map((e) => {
    const title = lang === "en" ? e.title_en : e.title_de;
    const body = lang === "en" ? e.body_en : e.body_de;
    const tagLabel = tDyn(`changelog.tag.${e.tag}`);
    return (
      `<li class="changelog-entry">` +
      `<div class="changelog-meta">` +
      `<time class="changelog-date" datetime="${escapeHTML(e.date)}">${escapeHTML(formatDate(e.date))}</time>` +
      `<span class="changelog-tag changelog-tag-${escapeHTML(e.tag)}">${escapeHTML(tagLabel)}</span>` +
      `</div>` +
      `<h2 class="changelog-title">${escapeHTML(title)}</h2>` +
      `<p class="changelog-body">${escapeHTML(body)}</p>` +
      `</li>`
    );
  }).join("");
}

document.addEventListener("DOMContentLoaded", () => {
  initI18n();
  initSidebar();
  // Stamp the visit immediately so the sidebar badge clears even if the
  // user navigates away before /api/changelog returns.
  markChangelogSeen();
  // Also clear any locally-rendered badge in the current DOM so it
  // disappears without waiting for a reload.
  document.querySelectorAll<HTMLElement>(".sidebar-badge").forEach((el) => {
    el.remove();
  });
  onLangChange(render);
  load();
});
