'use strict';
{
    /**
     * 设置网页主题
     * 验证主题模式有效性，将主题应用到页面，并保存到本地存储
     * @param {string} mode - 目标主题模式（light/dark/auto）
     */
    function setTheme(mode) {
        if (mode !== "light" && mode !== "dark" && mode !== "auto") {
            // 判断系统是否偏好深色模式（通过媒体查询）
            console.error(`Got invalid theme mode: ${mode}. Resetting to auto.`);
            mode = "auto";
        }
        document.documentElement.dataset.theme = mode;
        localStorage.setItem("theme", mode);
    }

    function cycleTheme() {
        const currentTheme = localStorage.getItem("theme") || "auto";
        const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;

        if (prefersDark) {
            // Auto (dark) -> Light -> Dark
             // 系统偏好浅色：切换顺序为「Auto（实际显示浅色）→ Dark → Light → Auto」
            if (currentTheme === "auto") {
                setTheme("light");
            } else if (currentTheme === "light") {
                setTheme("dark");
            } else {
                setTheme("auto");
            }
        } else {
            // Auto (light) -> Dark -> Light
            if (currentTheme === "auto") {
                setTheme("dark");
            } else if (currentTheme === "dark") {
                setTheme("light");
            } else {
                setTheme("auto");
            }
        }
    }
    /**
     * 初始化网页主题
     * 页面加载时，优先使用localStorage中保存的主题，无则默认“auto”
     */
    function initTheme() {
        // set theme defined in localStorage if there is one, or fallback to auto mode
        const currentTheme = localStorage.getItem("theme");
        currentTheme ? setTheme(currentTheme) : setTheme("auto");
    }
    // 页面加载完成后，给所有主题切换按钮绑定点击事件
    window.addEventListener('load', function(_) {
        const buttons = document.getElementsByClassName("theme-toggle");
        Array.from(buttons).forEach((btn) => {
            btn.addEventListener("click", cycleTheme);
        });
    });

    initTheme();
}
