// Apply theme immediately on script load (before DOM is ready) to prevent flash (function() { const savedTheme = localStorage.getItem('theme'); const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; // Wait for body to be available if (document.body) { applyInitialTheme(); } else { document.addEventListener('DOMContentLoaded', applyInitialTheme); } function applyInitialTheme() { // Remove any existing theme classes first document.body.classList.remove('dark-mode', 'light-mode'); if (savedTheme === 'dark' || (!savedTheme && systemPrefersDark)) { document.body.classList.add('dark-mode'); } else { document.body.classList.add('light-mode'); } } })(); document.addEventListener('DOMContentLoaded', function() { const themeSwitcher = document.getElementById('themeSwitcher'); if (!themeSwitcher) { console.warn('Theme switcher button not found'); return; } const themeIcon = themeSwitcher.querySelector('.iconify'); const themeText = themeSwitcher.querySelector('.theme-text'); // Function to apply theme function applyTheme(theme) { // Remove both classes first document.body.classList.remove('dark-mode', 'light-mode'); if (theme === 'dark') { document.body.classList.add('dark-mode'); if (themeIcon) themeIcon.setAttribute('data-icon', 'mdi-weather-night'); if (themeText) themeText.textContent = 'Dark Mode'; localStorage.setItem('theme', 'dark'); } else { document.body.classList.add('light-mode'); if (themeIcon) themeIcon.setAttribute('data-icon', 'mdi-weather-sunny'); if (themeText) themeText.textContent = 'Light Mode'; localStorage.setItem('theme', 'light'); } } // Set initial theme UI based on current state const savedTheme = localStorage.getItem('theme'); const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches; const currentTheme = savedTheme || (systemPrefersDark ? 'dark' : 'light'); if (currentTheme === 'dark') { if (themeIcon) themeIcon.setAttribute('data-icon', 'mdi-weather-night'); if (themeText) themeText.textContent = 'Dark Mode'; } else { if (themeIcon) themeIcon.setAttribute('data-icon', 'mdi-weather-sunny'); if (themeText) themeText.textContent = 'Light Mode'; } // Theme switcher click handler themeSwitcher.addEventListener('click', function() { const isDarkMode = document.body.classList.contains('dark-mode'); applyTheme(isDarkMode ? 'light' : 'dark'); }); });