// Theme management: applies light/dark class to <html> based on preference.

let mediaQuery = null;
let mediaHandler = null;

function applyTheme(theme) {
    // Clean up previous system listener
    if (mediaQuery && mediaHandler) {
        mediaQuery.removeEventListener("change", mediaHandler);
        mediaHandler = null;
    }

    if (theme === "dark") {
        document.documentElement.classList.add("dark");
    } else if (theme === "light") {
        document.documentElement.classList.remove("dark");
    } else {
        // system
        mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
        const update = () => {
            if (mediaQuery.matches) {
                document.documentElement.classList.add("dark");
            } else {
                document.documentElement.classList.remove("dark");
            }
        };
        mediaHandler = update;
        mediaQuery.addEventListener("change", update);
        update();
    }
}

module.exports = { applyTheme };
