/* =========================================================
   NOVA X — darkmode.js
   Modo claro / oscuro con persistencia
   ========================================================= */

const NovaDarkMode = (() => {
  const STORAGE_KEY = "novax_theme";

  function aplicarTema(tema) {
    document.documentElement.setAttribute("data-theme", tema);
    document.querySelectorAll(".dark-toggle").forEach((toggle) => {
      toggle.setAttribute("aria-checked", tema === "dark" ? "true" : "false");
    });
    document.querySelectorAll("[data-theme-icon]").forEach((icon) => {
      icon.textContent = tema === "dark" ? "☀️" : "🌙";
    });
  }

  function obtenerTemaGuardado() {
    const guardado = localStorage.getItem(STORAGE_KEY);
    if (guardado) return guardado;
    return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
  }

  function alternarTema() {
    const actual = document.documentElement.getAttribute("data-theme") === "dark" ? "dark" : "light";
    const nuevo = actual === "dark" ? "light" : "dark";
    localStorage.setItem(STORAGE_KEY, nuevo);
    aplicarTema(nuevo);
  }

  function init() {
    aplicarTema(obtenerTemaGuardado());
    document.querySelectorAll("[data-toggle-theme]").forEach((btn) => {
      btn.addEventListener("click", alternarTema);
    });
  }

  return { init, aplicarTema, alternarTema };
})();
