(function() {
    const themeToggle = document.getElementById('theme-toggle');
    const themeIcon = document.getElementById('theme-icon');
    
    function getStoredTheme() {
        return localStorage.getItem('picoPreferredColorScheme') || 'auto';
    }
    
    function storeTheme(theme) {
        localStorage.setItem('picoPreferredColorScheme', theme);
    }
    
    function getSystemTheme() {
        return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    }
    
    function applyTheme() {
        const storedTheme = getStoredTheme();
        let actualTheme;
        
        if (storedTheme === 'auto') {
            actualTheme = getSystemTheme();
        } else {
            actualTheme = storedTheme;
        }
        
        document.documentElement.setAttribute('data-theme', actualTheme);
        
        if (actualTheme === 'dark') {
            themeIcon.textContent = '☀️';
            themeToggle.setAttribute('aria-pressed', 'true');
        } else {
            themeIcon.textContent = '🌙';
            themeToggle.setAttribute('aria-pressed', 'false');
        }
    }
    
    function toggleTheme() {
        const currentStored = getStoredTheme();
        let nextTheme;
        
        if (currentStored === 'auto') {
            nextTheme = 'light';
        } else if (currentStored === 'light') {
            nextTheme = 'dark';
        } else {
            nextTheme = 'auto';
        }
        
        storeTheme(nextTheme);
        applyTheme();
    }
    
    function init() {
        if (themeToggle) {
            applyTheme();
            
            themeToggle.addEventListener('click', toggleTheme);
            
            window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
                if (getStoredTheme() === 'auto') {
                    applyTheme();
                }
            });
        }
    }
    
    if (document.readyState !== 'loading') {
        init();
    } else {
        document.addEventListener('DOMContentLoaded', init);
    }
})();