const toggle = document.querySelector('.theme-toggle');
const iconMoon = toggle.querySelector('.icon-moon');
const iconSun = toggle.querySelector('.icon-sun');

function getPreferredTheme() {
    const stored = localStorage.getItem('theme');
    if (stored) return stored;
    return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
}

function applyTheme(theme) {
    document.documentElement.setAttribute('data-theme', theme);
    iconMoon.style.display = theme === 'dark' ? 'block' : 'none';
    iconSun.style.display = theme === 'light' ? 'block' : 'none';
}

applyTheme(getPreferredTheme());

toggle.addEventListener('click', () => {
    const current = document.documentElement.getAttribute('data-theme');
    const next = current === 'dark' ? 'light' : 'dark';
    document.documentElement.classList.add('theme-transitioning');
    localStorage.setItem('theme', next);
    applyTheme(next);
    setTimeout(() => {
        document.documentElement.classList.remove('theme-transitioning');
    }, 500);
});
