(function() {
    const themeToggle = document.getElementById('theme-toggle');
    const themeIcon = document.getElementById('theme-icon');


    function storeTheme(theme) {
        localStorage.setItem('picoPreferredColorScheme', theme);
    }

    function getStoredTheme() {
        return localStorage.getItem('picoPreferredColorScheme');
    }

    function getCurrentTheme() {
        return document.documentElement.getAttribute('data-theme') || 
            (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
    }

    function applyTheme(currentTheme) {
        const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
        document.documentElement.setAttribute('data-theme', newTheme);
        if (newTheme === 'dark') {
            themeIcon.textContent = '☀️';
            themeToggle.setAttribute('aria-pressed', 'true');
        } else {
            themeIcon.textContent = '🌙';
            themeToggle.setAttribute('aria-pressed', 'false');
        }
    }

    themeToggle.addEventListener('click', () => {
        const currentTheme = getCurrentTheme();
        
        applyTheme(currentTheme);
        storeTheme(currentTheme);
    });

    function init() {
        let storedTheme = getStoredTheme() || getCurrentTheme();
        
        applyTheme(storedTheme);
        
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
            const storedTheme = getStoredTheme();
            if (storedTheme === 'auto') {
                applyTheme();
            }
        })
    }
    
    if (document.readyState !== 'loading') {
        init();
    } else {
        document.addEventListener('DOMContentLoaded', init);
    }
})();