/**
 * Shared client UI language (NL/EN) — localStorage + server sync.
 */
(function (w) {
  "use strict";

  var STORAGE_KEY = "client-login-lang";

  w.sciiGetLang = function () {
    try {
      var s = localStorage.getItem(STORAGE_KEY);
      if (s === "en" || s === "nl") return s;
    } catch (e) {}
    var h = document.documentElement.getAttribute("lang");
    if (h === "en" || h === "nl") return h;
    return "nl";
  };

  w.sciiNormalizeLang = function (lang) {
    return lang === "en" ? "en" : "nl";
  };

  w.sciiPersistUiLanguage = function (lang) {
    lang = w.sciiNormalizeLang(lang);
    try {
      localStorage.setItem(STORAGE_KEY, lang);
    } catch (e) {}
    if (typeof w.sciiGetOrCreateVisitorId !== "function") return;
    fetch("/api/heartbeat", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        visitor_id: w.sciiGetOrCreateVisitorId(),
        ui_language: lang,
      }),
    }).catch(function () {});
  };

  w.sciiUpdateLanguageToggle = function (lang, t) {
    lang = w.sciiNormalizeLang(lang);
    t = t || {};
    var nlBtn = document.querySelector(".language-toggle-container button[lang='nl']");
    var enBtn = document.querySelector(".language-toggle-container button[lang='en']");
    if (!nlBtn || !enBtn) return;
    if (t.ariaNl) nlBtn.setAttribute("aria-label", t.ariaNl);
    if (t.ariaEn) enBtn.setAttribute("aria-label", t.ariaEn);
    if (lang === "nl") {
      nlBtn.className = "toggle-button hide ui-button darkarea default no-border";
      nlBtn.style.marginRight = "0";
      enBtn.className = "toggle-button ui-button darkarea default no-border";
      enBtn.style.marginRight = "0";
    } else {
      enBtn.className = "toggle-button hide ui-button darkarea default no-border";
      enBtn.style.marginRight = "0";
      nlBtn.className = "toggle-button ui-button darkarea default no-border";
      nlBtn.style.marginRight = "0";
    }
  };

  w.sciiBindLanguageBar = function (setLangFn) {
    var nlBtn = document.querySelector(".language-toggle-container button[lang='nl']");
    var enBtn = document.querySelector(".language-toggle-container button[lang='en']");
    if (nlBtn) {
      nlBtn.setAttribute("type", "button");
      nlBtn.addEventListener("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
        setLangFn("nl");
      });
    }
    if (enBtn) {
      enBtn.setAttribute("type", "button");
      enBtn.addEventListener("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
        setLangFn("en");
      });
    }
  };
})(window);
