window.workTrackerTheme = (() => {
    const storageKey = "worktracker.themeMode";
    const mediaQuery = window.matchMedia
        ? window.matchMedia("(prefers-color-scheme: dark)")
        : null;

    function normalize(mode) {
        const normalized = (mode || "system").toString().toLowerCase();
        return normalized === "light" || normalized === "dark" || normalized === "system"
            ? normalized
            : "system";
    }

    function resolve(mode) {
        if (mode === "system") {
            return mediaQuery && mediaQuery.matches ? "dark" : "light";
        }

        return mode;
    }

    function apply(mode) {
        const normalized = normalize(mode);
        const effectiveMode = resolve(normalized);

        document.documentElement.setAttribute("data-bs-theme", effectiveMode);
        document.documentElement.setAttribute("data-theme-mode", normalized);
        document.documentElement.style.colorScheme = effectiveMode;
        localStorage.setItem(storageKey, normalized);
    }

    function handleSystemThemeChange() {
        const currentMode = normalize(localStorage.getItem(storageKey) || document.documentElement.getAttribute("data-theme-mode"));
        if (currentMode === "system") {
            apply(currentMode);
        }
    }

    if (mediaQuery) {
        if (typeof mediaQuery.addEventListener === "function") {
            mediaQuery.addEventListener("change", handleSystemThemeChange);
        }
        else if (typeof mediaQuery.addListener === "function") {
            mediaQuery.addListener(handleSystemThemeChange);
        }
    }

    return {
        init() {
            apply(localStorage.getItem(storageKey) || document.documentElement.getAttribute("data-theme-mode"));
        },
        setTheme(mode) {
            apply(mode);
        }
    };
})();

window.workTrackerTheme.init();