const SUPPORTED_LANGS = ["fr", "en", "it"];
const DEFAULT_LANG = "fr";

function normalizeImportedJson(payload) {
  if (payload && typeof payload === "object" && "default" in payload) {
    return payload.default;
  }
  return payload;
}

function applyDict(lang, dict) {
  document.documentElement.lang = lang;

  document.querySelectorAll("[data-i18n]").forEach((el) => {
    const key = el.getAttribute("data-i18n");
    if (dict && typeof dict[key] === "string") {
      el.textContent = dict[key];
    }
  });

  document.querySelectorAll(".lang-btn").forEach((btn) => {
    btn.classList.toggle("active", btn.dataset.lang === lang);
  });
}

function detectInitialLang() {
  const saved = localStorage.getItem("lang");
  if (saved && SUPPORTED_LANGS.includes(saved)) return saved;

  const nav = (navigator.language || "").slice(0, 2).toLowerCase();
  if (SUPPORTED_LANGS.includes(nav)) return nav;

  return DEFAULT_LANG;
}

async function fetchDict(lang) {
  const res = await fetch("/language", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ lang })
  });

  if (!res.ok) throw new Error(`HTTP ${res.status}`);

  const payload = await res.json();
  return normalizeImportedJson(payload);
}

async function setLang(lang) {
  const safeLang = SUPPORTED_LANGS.includes(lang) ? lang : DEFAULT_LANG;

  try {
    const dict = await fetchDict(safeLang);
    applyDict(safeLang, dict);
    localStorage.setItem("lang", safeLang);
  } catch {
    if (safeLang !== "fr") {
      try {
        const dict = await fetchDict("fr");
        applyDict("fr", dict);
        localStorage.setItem("lang", "fr");
        return;
      } catch {}
    }
    document.documentElement.lang = safeLang;
  }
}

async function setMsg() {
  let data = await fetch("/message").then((resp) => {return resp.json()});
  document.getElementById("message").innerText = data["message"] ?? "No message today...";
}

function setupLangButtons() {
  document.querySelectorAll(".lang-btn").forEach((btn) => {
    btn.addEventListener("click", () => setLang(btn.dataset.lang));
  });
}

(async function init() {
  const yearEl = document.getElementById("year");
  if (yearEl) yearEl.textContent = String(new Date().getFullYear());

  setupLangButtons();

  const initialLang = detectInitialLang();
  await setLang(initialLang);
  await setMsg();
})();
