(function () {
    const storageKey = 'fk-theme';

    function applyTheme(theme) {
        document.documentElement.setAttribute('data-theme', theme);
        const sun = document.querySelector('.fk-icon-sun');
        const moon = document.querySelector('.fk-icon-moon');
        if (sun && moon) {
            sun.hidden = theme === 'dark';
            moon.hidden = theme !== 'dark';
        }
    }

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

    applyTheme(preferredTheme());

    document.addEventListener('DOMContentLoaded', function () {
        const toggle = document.getElementById('fk-theme-toggle');
        if (!toggle) {
            return;
        }
        toggle.addEventListener('click', function () {
            const next = document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark';
            localStorage.setItem(storageKey, next);
            applyTheme(next);
        });
    });
})();
