(function () {
    var cfg = window.zertiAdminTheme || {};
    var storageKey = cfg.storageKey || 'zertiAdminColorTheme';
    var root = document.getElementById('zertiAdmin');
    if (!root) {
        return;
    }

    function apply(theme) {
        if (theme !== 'light' && theme !== 'dark') {
            theme = 'dark';
        }
        root.setAttribute('data-bs-theme', theme);
        document.body.setAttribute('data-zerti-bs-theme', theme);
        try {
            localStorage.setItem(storageKey, theme);
        } catch (e) {}
        var isDark = theme === 'dark';
        root.querySelectorAll('[data-zerti-theme-toggle]').forEach(function (btn) {
            btn.setAttribute('aria-checked', isDark ? 'true' : 'false');
            btn.setAttribute(
                'aria-label',
                isDark ? btn.getAttribute('data-zerti-aria-light') : btn.getAttribute('data-zerti-aria-dark')
            );
        });
        if (typeof window.zertiInitHomeRevenueChart === 'function') {
            window.zertiInitHomeRevenueChart(root);
        }
    }

    root.querySelectorAll('[data-zerti-theme-toggle]').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var next = root.getAttribute('data-bs-theme') === 'dark' ? 'light' : 'dark';
            apply(next);
        });
    });

    apply(root.getAttribute('data-bs-theme') || 'dark');
})();
