// theme-switcher.js
document.addEventListener('DOMContentLoaded', function () {

    const themeToggle       = document.getElementById('theme-toggle');
    const mobileThemeToggle = document.getElementById('mobile-theme-toggle');
    const themeCSS1C        = document.getElementById('theme-css-1c');

    // FIX: Derive the base path once so we never rely on the current href value.
    // href.replace() was silently failing when the filename didn't match exactly.
    const hljsBasePath = themeCSS1C
        ? themeCSS1C.href.replace(/1c-(light|dark)\.min\.css$/, '')
        : null;

    // console.log('Initial href:', themeCSS1C?.href);
    // console.log('Computed basePath:', hljsBasePath);

    // ── Theme application ────────────────────────────────────────────────────

    function applyTheme(isDark) {
        if (isDark) {
            document.body.classList.add('theme-dark');
            if (themeCSS1C && hljsBasePath) {
                themeCSS1C.href = hljsBasePath + '1c-dark.min.css';
            }
        } else {
            document.body.classList.remove('theme-dark');
            if (themeCSS1C && hljsBasePath) {
                themeCSS1C.href = hljsBasePath + '1c-light.min.css';
            }
        }

        // FIX: CSS defines checked = dark (moon icon).
        // Previously the handlers were calling the wrong function on check/uncheck.
        if (themeToggle)       themeToggle.checked       = isDark;
        if (mobileThemeToggle) mobileThemeToggle.checked = isDark;

        localStorage.setItem('theme', isDark ? 'dark' : 'light');
    }

    // ── Initialise from saved preference ────────────────────────────────────

    const savedTheme = localStorage.getItem('theme');
    applyTheme(savedTheme === 'dark');

    // ── Event listeners ──────────────────────────────────────────────────────

    // FIX: Both toggles now call the same applyTheme() — no duplicated logic,
    // and both are always kept in sync with each other automatically.
    if (themeToggle) {
        themeToggle.addEventListener('change', function () {
            applyTheme(this.checked);
        });
    }

    if (mobileThemeToggle) {
        mobileThemeToggle.addEventListener('change', function () {
            applyTheme(this.checked);
        });
    }

    // ── CSS error handling ───────────────────────────────────────────────────

    // FIX: was referencing undefined variable `themeCSS` instead of `themeCSS1C`
    if (themeCSS1C) {
        themeCSS1C.onerror = function () {
            console.error('Ошибка загрузки CSS файла темы подсветки кода');
            // Fall back to light theme
            applyTheme(false);
        };
    }

});