(() => {
  const getStoredLanguage = () => {
    const m = document.cookie.match(/language=(\w+)/);
    return m ? m[1] : null;
  };
  const setStoredLanguage = (language: string) => (document.cookie = `language=${language}; max-age=34560000; path=/`);

  const getPreferredLanguage = () => {
    const storedLanguage = getStoredLanguage();
    if (storedLanguage) {
      return storedLanguage;
    }
    const result = window.navigator.language.split("-")[0];
    return ["en", "ru"].includes(result) ? result : "en";
  };

  const setLanguage = (language: string) => {};

  setLanguage(getPreferredLanguage());

  const showActiveLanguage = (language: string, focus = false) => {
    const languageSwitcher = document.querySelector<HTMLElement>("#bd-language");

    if (!languageSwitcher) {
      return;
    }

    const languageSwitcherText = document.querySelector("#bd-language-text");
    const activeLanguageIcon = document.querySelector(".language-icon-active");
    const btnToActive = document.querySelector<HTMLElement>(`[data-bs-language-value="${language}"]`);
    const activeLanguageIconClass = (btnToActive?.querySelector(".fi")?.className.match(/fi-[\w-]+/) || [])[0] || "";

    document.querySelectorAll("[data-bs-language-value]").forEach((element) => {
      element.classList.remove("active");
      element.setAttribute("aria-pressed", "false");
    });

    btnToActive?.classList.add("active");
    btnToActive?.setAttribute("aria-pressed", "true");
    const classesToRemove = Array.from(activeLanguageIcon?.classList || []).filter((className) =>
      className.startsWith("fi-"),
    );
    activeLanguageIcon?.classList.remove(...classesToRemove);
    activeLanguageIcon?.classList.add(activeLanguageIconClass);
    const languageSwitcherLabel = `${languageSwitcherText?.textContent} (${btnToActive?.dataset.bsLanguageValue})`;
    languageSwitcher.setAttribute("aria-label", languageSwitcherLabel);

    if (focus) {
      languageSwitcher?.focus();
    }
  };

  window.addEventListener("DOMContentLoaded", () => {
    showActiveLanguage(getPreferredLanguage());

    document.querySelectorAll("[data-bs-language-value]").forEach((toggle) => {
      toggle.addEventListener("click", () => {
        const language = toggle.getAttribute("data-bs-language-value") || "";
        setStoredLanguage(language);
        setLanguage(language);
        showActiveLanguage(language, true);
        window.location.reload();
      });
    });
  });
})();
