/**
 * Reliable admin sidebar toggles (desktop minimize + mobile drawer).
 * Uses capture phase so this runs before jQuery/duplicate atlantis handlers,
 * and stopImmediatePropagation avoids double-toggle when multiple listeners exist.
 */
(function () {
    'use strict';

    function syncMinimizeButtons(minimized) {
        document.querySelectorAll('.toggle-sidebar').forEach(function (btn) {
            if (minimized) {
                btn.classList.add('toggled');
                btn.innerHTML = '<i class="icon-options-vertical"></i>';
            } else {
                btn.classList.remove('toggled');
                btn.innerHTML = '<i class="icon-menu"></i>';
            }
        });
    }

    function fireResize() {
        if (typeof jQuery !== 'undefined' && jQuery.fn) {
            jQuery(window).trigger('resize');
        } else {
            window.dispatchEvent(new Event('resize'));
        }
    }

    document.addEventListener(
        'click',
        function (e) {
            var el = e.target;
            if (!el || typeof el.closest !== 'function') {
                return;
            }

            var mini = el.closest('.toggle-sidebar');
            if (mini && mini.closest('.main-header')) {
                e.preventDefault();
                e.stopImmediatePropagation();
                var wrapper = document.querySelector('.wrapper');
                if (!wrapper) {
                    return;
                }
                wrapper.classList.toggle('sidebar_minimize');
                syncMinimizeButtons(wrapper.classList.contains('sidebar_minimize'));
                fireResize();
                return;
            }

            var navBtn = el.closest('.sidenav-toggler');
            if (navBtn && navBtn.closest('.main-header')) {
                e.preventDefault();
                e.stopImmediatePropagation();
                var html = document.documentElement;
                html.classList.toggle('nav_open');
                var open = html.classList.contains('nav_open');
                document.querySelectorAll('.sidenav-toggler').forEach(function (btn) {
                    btn.classList.toggle('toggled', open);
                });
            }
        },
        true
    );

    document.addEventListener('DOMContentLoaded', function () {
        var wrapper = document.querySelector('.wrapper');
        if (wrapper && wrapper.classList.contains('sidebar_minimize')) {
            syncMinimizeButtons(true);
        }
    });
})();
