const themeToggle = document.getElementById('theme-toggle');
const moonIcon = document.getElementById('moon-icon');
const sunIcon = document.getElementById('sun-icon');

// Function to update the toggle button icon and aria-label
function updateToggleIcon(button) {
    if (!button || !moonIcon || !sunIcon) return; // Guard clause

    if (document.body.classList.contains('dark-mode')) {
        // Dark mode: show sun icon, hide moon icon
        moonIcon.classList.add('hidden');
        sunIcon.classList.remove('hidden');
        button.setAttribute('aria-label', 'Switch to light mode');
    } else {
        // Light mode: show moon icon, hide sun icon
        moonIcon.classList.remove('hidden');
        sunIcon.classList.add('hidden');
        button.setAttribute('aria-label', 'Switch to dark mode');
    }
}

// Apply the cached theme on initial load
const currentTheme = localStorage.getItem('theme');
if (currentTheme) {
    document.body.classList.add(currentTheme);
}

// Set initial button icon and aria-label 
if (themeToggle) {
    updateToggleIcon(themeToggle); 
} else {
    console.warn('Theme toggle button #theme-toggle not found during initial load.');
}

// Add event listener
if (themeToggle) {
    themeToggle.addEventListener('click', () => {
        const body = document.body; // Get body inside listener
        // Toggle the .dark-mode class on the body
        body.classList.toggle('dark-mode');

        // Update theme preference in localStorage
        let theme = 'light-mode'; 
        if (body.classList.contains('dark-mode')) {
            theme = 'dark-mode';
        }
        localStorage.setItem('theme', theme);

        // Update the button icon and aria-label after toggling
        updateToggleIcon(themeToggle); 
    });
} else {
    // Warning already logged during initial load check
} 