// dark-mode.js - Theme toggle with localStorage persistence
(function () {
    'use strict';

    const STORAGE_KEY = 'jongvoter-theme';

    function getStoredTheme() {
        try { return localStorage.getItem(STORAGE_KEY); }
        catch (e) { return null; }
    }

    function setStoredTheme(theme) {
        try { localStorage.setItem(STORAGE_KEY, theme); }
        catch (e) { }
    }

    function applyTheme(theme) {
        document.documentElement.setAttribute('data-bs-theme', theme);

        // Update all dark mode toggle button icons
        const iconClass = theme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
        document.querySelectorAll('#darkModeToggle, #darkModeToggleTop').forEach(function (btn) {
            const icon = btn.querySelector('i');
            if (icon) icon.className = iconClass;
        });

        // Re-render chart with updated colors
        if (typeof VoteChart !== 'undefined' && VoteChart.render) {
            VoteChart.render();
        }
    }

    function toggleTheme() {
        const current = document.documentElement.getAttribute('data-bs-theme') || 'light';
        const next = current === 'dark' ? 'light' : 'dark';
        setStoredTheme(next);
        applyTheme(next);
    }

    // Set up toggle button after DOM loads
    document.addEventListener('DOMContentLoaded', function () {
        const btn = document.getElementById('darkModeToggle');
        if (btn) {
            btn.addEventListener('click', toggleTheme);
        }
        applyTheme(getStoredTheme() || 'light');
    });

    window.darkMode = {
        toggle: toggleTheme,
        set: function (theme) { setStoredTheme(theme); applyTheme(theme); },
        get: function () { return document.documentElement.getAttribute('data-bs-theme') || 'light'; }
    };
})();
