/*!
 * dark-mode-switch.ts
 * Source: https://dbohdan.com/assets/dark-mode-switch.ts
 *
 * Control dark mode.
 * Requires compiled dark-mode.ts loaded in the browser before initialization.
 *
 * Copyright (c) 2025 D. Bohdan.
 * License: MIT.
 * https://dbohdan.com/mit-license/2025
 */

"use strict";

type Theme = "system" | "reverse" | "light" | "dark" | "flicker";

declare const darkMode: {
    loadTheme(): Theme;
    setTheme(theme: Theme): void;
};

const darkModeSwitch = {
    ACTIVE_CLASS: "dark-mode-switch-active",
    ID_PREFIX: "dark-mode-",
    STORAGE_KEY: "dark-mode-switch",

    getSwitch(theme: Theme): HTMLElement | null {
        return document.getElementById(this.ID_PREFIX + theme);
    },

    set(theme: Theme, switchOnly: boolean): void {
        const prevTheme = darkMode.loadTheme();

        if (!switchOnly) {
            darkMode.setTheme(theme);
        }

        const prevSwitch = this.getSwitch(prevTheme);
        const newSwitch = this.getSwitch(theme);

        if (prevSwitch) {
            prevSwitch.classList.remove(this.ACTIVE_CLASS);
        }

        if (newSwitch) {
            newSwitch.classList.add(this.ACTIVE_CLASS);
        }
    },

    init(): void {
        const theme = darkMode.loadTheme();

        this.set(theme, true);
    },
};
