window.addEventListener('load', function () {

    let currentTheme = localStorage.getItem('theme');
    if (currentTheme == null) {
        currentTheme = (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : ''; //default light
        localStorage.setItem('theme', currentTheme);
    }
    
    document.documentElement.setAttribute('data-theme', currentTheme);

    const toggleTheme = document.getElementById('theme-toggle');
    if (toggleTheme != null) {
        toggleTheme.checked = currentTheme != 'dark';

        toggleTheme.addEventListener('change', function () {
            const newTheme = toggleTheme.checked ? '' : 'dark';
            localStorage.setItem('theme', newTheme);
            document.documentElement.setAttribute('data-theme', newTheme);
        });
    }
});