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

<aside class="cookie-banner" data-cookie-banner hidden>
  <div class="cookie-banner__panel">
    <div class="cookie-banner__copy">
      <p class="cookie-banner__eyebrow">
        <LocaleCopy copy={cookieBannerCopy.eyebrow} />
      </p>
      <h2>
        <LocaleCopy copy={cookieBannerCopy.title} />
      </h2>
      <p class="cookie-banner__body">
        <LocaleCopy copy={cookieBannerCopy.body} />
      </p>
    </div>

    <div class="cookie-banner__actions">
      <button type="button" class="button button--dark button--small" data-cookie-accept="all">
        <LocaleCopy copy={cookieBannerCopy.acceptAll} />
      </button>
      <button type="button" class="button button--soft button--small" data-cookie-accept="essential">
        <LocaleCopy copy={cookieBannerCopy.essentialOnly} />
      </button>
      <button type="button" class="button button--ghost button--small" data-cookie-customize>
        <LocaleCopy copy={cookieBannerCopy.customize} />
      </button>
    </div>

    <div class="cookie-banner__details" data-cookie-details hidden>
      <label class="cookie-toggle">
        <input type="checkbox" checked disabled />
        <span>
          <strong><LocaleCopy copy={cookieBannerCopy.categories.essential} /></strong>
          <em>
            <LocaleCopy
              copy={{
                en: "Always on",
                fr: "Toujours actif",
                nb: "Alltid pa",
              }}
            />
          </em>
        </span>
      </label>

      <label class="cookie-toggle">
        <input type="checkbox" data-cookie-option="analytics" />
        <span>
          <strong><LocaleCopy copy={cookieBannerCopy.categories.analytics} /></strong>
          <em>
            <LocaleCopy
              copy={{
                en: "Off by default",
                fr: "Desactive par defaut",
                nb: "Av som standard",
              }}
            />
          </em>
        </span>
      </label>

      <label class="cookie-toggle">
        <input type="checkbox" data-cookie-option="embeds" />
        <span>
          <strong><LocaleCopy copy={cookieBannerCopy.categories.embeds} /></strong>
          <em>
            <LocaleCopy
              copy={{
                en: "Off by default",
                fr: "Desactive par defaut",
                nb: "Av som standard",
              }}
            />
          </em>
        </span>
      </label>

      <button type="button" class="button button--dark button--small" data-cookie-save>
        <LocaleCopy copy={cookieBannerCopy.save} />
      </button>
    </div>
  </div>
</aside>

<script is:inline>
  (() => {
    const COOKIE_NAME = "dg_cookie_preferences";
    const banner = document.querySelector("[data-cookie-banner]");
    if (!banner) return;

    const details = banner.querySelector("[data-cookie-details]");
    const analytics = banner.querySelector('[data-cookie-option="analytics"]');
    const embeds = banner.querySelector('[data-cookie-option="embeds"]');

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

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

    const applyPreference = (value) => {
      const pref = value || "essential";
      const analyticsOn = pref === "all" || pref.includes("analytics");
      const embedsOn = pref === "all" || pref.includes("embeds");
      document.documentElement.setAttribute("data-cookie-analytics", analyticsOn ? "true" : "false");
      document.documentElement.setAttribute("data-cookie-embeds", embedsOn ? "true" : "false");
      if (analytics) analytics.checked = analyticsOn;
      if (embeds) embeds.checked = embedsOn;
    };

    const closeBanner = () => {
      banner.hidden = true;
    };

    const savePreference = (value) => {
      writeCookie(value);
      applyPreference(value);
      closeBanner();
      window.dispatchEvent(new CustomEvent("dg:cookie-consent", { detail: { preference: value } }));
    };

    const existing = readCookie(COOKIE_NAME);
    if (existing) {
      applyPreference(existing);
      closeBanner();
      window.dispatchEvent(new CustomEvent("dg:cookie-consent", { detail: { preference: existing } }));
      return;
    }

    banner.hidden = false;
    applyPreference("essential");

    banner.querySelector('[data-cookie-accept="all"]')?.addEventListener("click", () => {
      savePreference("all");
    });

    banner.querySelector('[data-cookie-accept="essential"]')?.addEventListener("click", () => {
      savePreference("essential");
    });

    banner.querySelector("[data-cookie-customize]")?.addEventListener("click", () => {
      if (!details) return;
      details.hidden = !details.hidden;
    });

    banner.querySelector("[data-cookie-save]")?.addEventListener("click", () => {
      const parts = ["essential"];
      if (analytics?.checked) parts.push("analytics");
      if (embeds?.checked) parts.push("embeds");
      savePreference(parts.join(","));
    });
  })();
</script>
