---
import LocaleCopy from "./LocaleCopy.astro";
import { localeMeta } from "../data/locales";
---

<div class="locale-switcher" data-locale-switcher>
  <div class="locale-switcher__buttons" role="group" aria-label="Language switcher">
    <button type="button" class="locale-switcher__button" data-lang-button="en">
      {localeMeta.en.switcher}
    </button>
    <button type="button" class="locale-switcher__button" data-lang-button="fr">
      {localeMeta.fr.switcher}
    </button>
    <button type="button" class="locale-switcher__button" data-lang-button="nb">
      {localeMeta.nb.switcher}
    </button>
  </div>

  <LocaleCopy
    className="locale-switcher__note"
    copy={{
      en: localeMeta.en.note,
      fr: localeMeta.fr.note,
      nb: localeMeta.nb.note,
    }}
  />
</div>

<script is:inline>
  (() => {
    const COOKIE_NAME = "dg_ui_lang";
    const valid = ["en", "fr", "nb"];

    const readCookie = (name) => {
      const match = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
      return match ? decodeURIComponent(match[1]) : null;
    };

    const writeCookie = (name, value, days) => {
      const maxAge = days * 24 * 60 * 60;
      document.cookie = `${name}=${encodeURIComponent(value)}; path=/; max-age=${maxAge}; SameSite=Lax`;
    };

    const applyLang = (lang) => {
      const next = valid.includes(lang) ? lang : "en";
      document.documentElement.setAttribute("data-ui-lang", next);
      document.documentElement.lang = next;
      document.querySelectorAll("[data-lang-button]").forEach((button) => {
        button.classList.toggle("is-active", button.getAttribute("data-lang-button") === next);
        button.setAttribute(
          "aria-pressed",
          button.getAttribute("data-lang-button") === next ? "true" : "false",
        );
      });
      writeCookie(COOKIE_NAME, next, 180);
      window.dispatchEvent(new CustomEvent("dg:lang-change", { detail: { lang: next } }));
    };

    const initial = readCookie(COOKIE_NAME) || document.documentElement.getAttribute("data-ui-lang") || "en";
    applyLang(initial);

    document.querySelectorAll("[data-lang-button]").forEach((button) => {
      button.addEventListener("click", () => {
        const lang = button.getAttribute("data-lang-button");
        if (lang) applyLang(lang);
      });
    });
  })();
</script>
