import { Storage as YStorage } from "@matdata/yasgui-utils";
export class ThemeManager {
    constructor(rootElement) {
        this.storage = new YStorage("yasgui");
        this.rootElement = rootElement;
        this.currentTheme = this.getStoredTheme() || this.getSystemTheme();
        this.applyTheme(this.currentTheme);
    }
    getTheme() {
        return this.currentTheme;
    }
    setTheme(theme) {
        this.currentTheme = theme;
        this.applyTheme(theme);
        this.storage.set(ThemeManager.STORAGE_KEY, theme, 60 * 60 * 24 * 365, () => {
            console.warn("Failed to store theme preference due to quota exceeded");
        });
    }
    toggleTheme() {
        const newTheme = this.currentTheme === "light" ? "dark" : "light";
        this.setTheme(newTheme);
        return newTheme;
    }
    applyTheme(theme) {
        this.rootElement.setAttribute("data-theme", theme);
        document.documentElement.setAttribute("data-theme", theme);
        this.updateCodeMirrorTheme(theme);
    }
    updateCodeMirrorTheme(theme) {
        const cmTheme = theme === "dark" ? "material-palenight" : "default";
        const cmElements = this.rootElement.querySelectorAll(".CodeMirror");
        cmElements.forEach((element) => {
            const cm = element.CodeMirror;
            if (cm && cm.setOption) {
                cm.setOption("theme", cmTheme);
            }
        });
    }
    getStoredTheme() {
        const stored = this.storage.get(ThemeManager.STORAGE_KEY);
        if (stored === "light" || stored === "dark") {
            return stored;
        }
        return null;
    }
    getSystemTheme() {
        if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) {
            return "dark";
        }
        return "light";
    }
    listenToSystemTheme() {
        if (window.matchMedia) {
            const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
            mediaQuery.addEventListener("change", (e) => {
                if (!this.storage.get(ThemeManager.STORAGE_KEY)) {
                    const newTheme = e.matches ? "dark" : "light";
                    this.currentTheme = newTheme;
                    this.applyTheme(newTheme);
                }
            });
        }
    }
    refresh() {
        this.applyTheme(this.currentTheme);
    }
}
ThemeManager.STORAGE_KEY = "yasgui_theme";
//# sourceMappingURL=ThemeManager.js.map