(() => {
    const THEME_KEY = 'scrumPoker.ui.theme';
    const MODE_KEY = 'scrumPoker.ui.mode';
    const DEFAULT_THEME = 'win98';

    function applyTheme(theme) {
        const normalized = theme || DEFAULT_THEME;
        document.documentElement.setAttribute('data-ui-theme', normalized);
    }

    function applyMode(mode) {
        if (mode === 'dark') {
            document.documentElement.setAttribute('data-theme', 'dark');
            return;
        }
        document.documentElement.removeAttribute('data-theme');
    }

    function getCurrentMode() {
        return document.documentElement.getAttribute('data-theme') === 'dark' ? 'dark' : 'light';
    }

    function syncControls() {
        const theme = document.documentElement.getAttribute('data-ui-theme') || DEFAULT_THEME;
        const mode = getCurrentMode();

        document.querySelectorAll('[data-role="theme-picker"]').forEach((el) => {
            el.value = theme;
        });

        document.querySelectorAll('[data-role="mode-toggle"]').forEach((el) => {
            el.textContent = mode === 'dark' ? 'Light Mode' : 'Dark Mode';
        });
    }

    function initUIControls() {
        if (window.__uiControlsInitialized) {
            syncControls();
            return;
        }
        window.__uiControlsInitialized = true;

        const savedTheme = localStorage.getItem(THEME_KEY) || DEFAULT_THEME;
        const savedMode = localStorage.getItem(MODE_KEY) || 'light';
        applyTheme(savedTheme);
        applyMode(savedMode);
        syncControls();

        document.querySelectorAll('[data-role="theme-picker"]').forEach((picker) => {
            picker.addEventListener('change', (event) => {
                const value = event.target.value || DEFAULT_THEME;
                localStorage.setItem(THEME_KEY, value);
                applyTheme(value);
                syncControls();
            });
        });

        document.querySelectorAll('[data-role="mode-toggle"]').forEach((button) => {
            button.addEventListener('click', () => {
                const next = getCurrentMode() === 'dark' ? 'light' : 'dark';
                localStorage.setItem(MODE_KEY, next);
                applyMode(next);
                syncControls();
            });
        });
    }

    window.initUIControls = initUIControls;

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initUIControls, { once: true });
    } else {
        initUIControls();
    }
})();
