// ── Theme Toggle ──
// Dark mode is the default. No data-theme attribute means dark mode.
// Light mode is [data-theme="light"].

(function () {
  const STORAGE_KEY = "arcline-theme";
  const LIGHT = "light";
  const DARK = "dark";

  function applyTheme(theme) {
    if (theme === LIGHT) {
      document.documentElement.setAttribute("data-theme", LIGHT);
    } else {
      document.documentElement.removeAttribute("data-theme");
    }
  }

  // Read saved preference, default to dark
  function getSavedTheme() {
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored === LIGHT || stored === DARK) return stored;
    } catch (_) {
      // localStorage unavailable — ignore
    }
    return DARK;
  }

  function saveTheme(theme) {
    try {
      localStorage.setItem(STORAGE_KEY, theme);
    } catch (_) {
      // localStorage unavailable — ignore
    }
  }

  // Apply the saved theme immediately (before page render)
  const current = getSavedTheme();
  applyTheme(current);

  // Wire up toggle button(s) once the DOM is ready
  function initToggle() {
    const buttons = document.querySelectorAll("[data-theme-toggle]");
    buttons.forEach(function (btn) {
      btn.addEventListener("click", function () {
        const next = document.documentElement.hasAttribute("data-theme")
          ? DARK
          : LIGHT;
        applyTheme(next);
        saveTheme(next);
      });
    });
  }

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

