class ThemeManager {
    constructor(storageKey = 'theme-preference') {
        this.storageKey = storageKey;
        this.init();
    }

    init() {
        const saved = localStorage.getItem(this.storageKey);
        const systemPrefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
        const theme = saved || (systemPrefersDark ? 'dark' : 'light');
        this.setTheme(theme);
        this.setupListener();
    }

    setTheme(theme) {
        document.documentElement.setAttribute('data-theme', theme);
        localStorage.setItem(this.storageKey, theme);
        this.updateToggleIcon(theme);
    }

    toggle() {
        const current = document.documentElement.getAttribute('data-theme') || 'light';
        const next = current === 'light' ? 'dark' : 'light';
        this.setTheme(next);
    }

    updateToggleIcon(theme) {
        const toggle = document.querySelector('[data-theme-toggle] i');
        if (!toggle) return;
        toggle.className = theme === 'dark' ? 'bi bi-sun' : 'bi bi-moon';
    }

    setupListener() {
        const toggle = document.querySelector('[data-theme-toggle]');
        if (!toggle) return;
        toggle.addEventListener('click', () => this.toggle());
    }
}

// Auto-init when DOM is ready
window.addEventListener('DOMContentLoaded', () => {
    window.themeManager = new ThemeManager();
});
