/**
 * Themis theme toggle — manages DaisyUI theme switching.
 *
 * Reads data-theme-mode, data-light-theme, and data-dark-theme from <html>.
 * Cycles through: light → dark → auto.
 * Persists selection to localStorage.
 */
(function () {
    "use strict";

    var html = document.documentElement;
    var btn = document.getElementById("themis-theme-toggle");
    var iconSun = document.getElementById("themis-icon-sun");
    var iconMoon = document.getElementById("themis-icon-moon");
    var iconAuto = document.getElementById("themis-icon-auto");

    var lightTheme = html.getAttribute("data-light-theme") || "corporate";
    var darkTheme = html.getAttribute("data-dark-theme") || "business";

    // Get stored mode or fall back to server-rendered mode
    var mode = localStorage.getItem("themis-theme-mode") ||
               html.getAttribute("data-theme-mode") ||
               "auto";

    function systemPrefersDark() {
        return window.matchMedia("(prefers-color-scheme: dark)").matches;
    }

    function applyTheme(m) {
        mode = m;
        localStorage.setItem("themis-theme-mode", m);

        // Hide all icons
        if (iconSun) iconSun.classList.add("hidden");
        if (iconMoon) iconMoon.classList.add("hidden");
        if (iconAuto) iconAuto.classList.add("hidden");

        if (m === "dark") {
            html.setAttribute("data-theme", darkTheme);
            if (iconSun) iconSun.classList.remove("hidden");   // show sun = click to go light
        } else if (m === "light") {
            html.setAttribute("data-theme", lightTheme);
            if (iconMoon) iconMoon.classList.remove("hidden");  // show moon = click to go dark
        } else {
            // auto
            html.setAttribute("data-theme", systemPrefersDark() ? darkTheme : lightTheme);
            if (iconAuto) iconAuto.classList.remove("hidden");
        }
    }

    // Apply initial theme
    applyTheme(mode);

    // Listen for system preference changes (for auto mode)
    window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", function () {
        if (mode === "auto") {
            applyTheme("auto");
        }
    });

    // Toggle button: light → dark → auto → light
    if (btn) {
        btn.addEventListener("click", function () {
            if (mode === "light") {
                applyTheme("dark");
            } else if (mode === "dark") {
                applyTheme("auto");
            } else {
                applyTheme("light");
            }
        });
    }
})();
