// Theme toggle functionality document.addEventListener('DOMContentLoaded', () => { const root = document.documentElement; const themeToggle = document.querySelector('.theme-toggle'); const sunIcon = themeToggle.querySelector('.sun-icon'); const moonIcon = themeToggle.querySelector('.moon-icon'); // Function to update icon visibility const updateIcon = (isDark) => { sunIcon.style.display = isDark ? 'none' : 'block'; moonIcon.style.display = isDark ? 'block' : 'none'; }; // Function to get current theme const getCurrentTheme = () => { if (root.classList.contains('light-theme')) return 'light'; if (root.classList.contains('dark-theme')) return 'dark'; return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; }; // Function to set theme const setTheme = (theme) => { root.classList.remove('light-theme', 'dark-theme'); if (theme !== 'system') { root.classList.add(`${theme}-theme`); localStorage.setItem('theme', theme); } else { localStorage.removeItem('theme'); } updateIcon(theme === 'dark' || (theme === 'system' && window.matchMedia('(prefers-color-scheme: dark)').matches)); }; // Initialize theme const savedTheme = localStorage.getItem('theme') || 'system'; setTheme(savedTheme); // Toggle theme on button click themeToggle.addEventListener('click', () => { const currentTheme = getCurrentTheme(); setTheme(currentTheme === 'dark' ? 'light' : 'dark'); }); // Listen for system theme changes window.matchMedia('(prefers-color-scheme: dark)') .addEventListener('change', (e) => { if (!localStorage.getItem('theme')) { updateIcon(e.matches); } }); }); // Remove no-js class if JavaScript is enabled document.documentElement.classList.remove('no-js'); // Apply saved theme immediately to prevent flash const savedTheme = localStorage.getItem('theme'); if (savedTheme) { document.documentElement.classList.add(savedTheme + '-theme'); }