(function () {
  const SUPPORTED = ["en", "da", "fr"];
  const DEFAULT_LANG = "en";
  const STORAGE_KEY = "wuys-lang";

  let currentLang = DEFAULT_LANG;
  let translations = {};

  function detectLang() {
    // 1. URL param ?lang=da overrides everything
    try {
      const params = new URLSearchParams(location.search);
      const urlLang = params.get("lang");
      if (urlLang && SUPPORTED.includes(urlLang)) return urlLang;
    } catch (e) {}
    // 2. Saved preference
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored && SUPPORTED.includes(stored)) return stored;
    } catch (e) {}
    // 3. Browser default
    const browserLang = (navigator.language || "en").slice(0, 2).toLowerCase();
    if (SUPPORTED.includes(browserLang)) return browserLang;
    return DEFAULT_LANG;
  }

  async function loadLang(lang) {
    // Every language — including English — loads from window.__langData[lang],
    // which is populated by <script src="lang/{lang}.js"> tags in the head.
    // Fall back to fetch for dev convenience if the inline data is missing.
    if (window.__langData && window.__langData[lang]) {
      translations = window.__langData[lang];
      return;
    }
    try {
      const response = await fetch("lang/" + lang + ".json?t=" + Date.now(), { cache: "no-store" });
      if (!response.ok) throw new Error("HTTP " + response.status);
      translations = await response.json();
    } catch (err) {
      console.warn("Could not load language file: " + lang, err);
      translations = {};
    }
  }

  function t(key, fallback) {
    if (Object.prototype.hasOwnProperty.call(translations, key)) {
      return translations[key];
    }
    return fallback !== undefined ? fallback : key;
  }

  function applyTranslations() {
    // Elements with data-i18n: replace innerHTML
    document.querySelectorAll("[data-i18n]").forEach((el) => {
      const key = el.getAttribute("data-i18n");
      if (Object.prototype.hasOwnProperty.call(translations, key)) {
        el.innerHTML = translations[key];
      }
    });
    // Elements with data-i18n-attr="attr:key" — translate an attribute
    document.querySelectorAll("[data-i18n-attr]").forEach((el) => {
      const config = el.getAttribute("data-i18n-attr");
      const [attr, key] = config.split(":");
      if (Object.prototype.hasOwnProperty.call(translations, key)) {
        el.setAttribute(attr, translations[key]);
      }
    });
    document.documentElement.lang = currentLang;
  }

  async function setLang(lang) {
    if (!SUPPORTED.includes(lang)) return;
    currentLang = lang;
    try { localStorage.setItem(STORAGE_KEY, lang); } catch (e) {}
    await loadLang(lang);
    applyTranslations();
    // Update switcher UI
    document.querySelectorAll(".lang-btn").forEach((btn) => {
      btn.classList.toggle("active", btn.dataset.lang === lang);
    });
    // Notify any listeners (e.g., music.js can re-render to use translations)
    window.dispatchEvent(new CustomEvent("langchange", { detail: { lang } }));
  }

  function getLang() { return currentLang; }

  // Expose for other scripts (music.js etc.)
  window.i18n = { t, setLang, getLang };

  // Wire up after DOM ready
  function init() {
    const lang = detectLang();
    setLang(lang);
    document.querySelectorAll(".lang-btn").forEach((btn) => {
      btn.addEventListener("click", () => setLang(btn.dataset.lang));
    });
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", init);
  } else {
    init();
  }
})();
