(function () {
    'use strict';

    var LEGACY_COLLAPSE_CLASSES = [
        'sidebar-collapsed','sidebar-mini','sidebar-compact','sidebar-hidden',
        'nav-collapsed','is-collapsed','collapsed','elite-sidebar-collapsed'
    ];
    var LEGACY_SHELL_CLASSES = ['diar-layout-parent','diar-layout-grid','diar-layout-flex'];
    var LEGACY_SIDEBAR_CLASSES = ['diar-layout-sidebar','diar-layout-sidebar-fixed'];
    var LEGACY_MAIN_CLASSES = ['diar-layout-main','diar-layout-main-fixed-offset'];
    var STORAGE_KEYS = ['sidebarCollapsed','sidebar-collapsed','eliteSidebarCollapsed','ddbSidebarCollapsed','sidebarState'];
    var enforcing = false;
    var resizeTimer = 0;

    function removeClasses(node, names) {
        if (!node || !node.classList) return;
        names.forEach(function (name) { if (node.classList.contains(name)) node.classList.remove(name); });
    }
    function clearProperties(node, names) {
        if (!node || !node.style) return;
        names.forEach(function (name) { if (node.style.getPropertyValue(name)) node.style.removeProperty(name); });
    }
    function setOpen(group, open) {
        var toggle = group.querySelector('[data-nav-group-toggle]');
        group.classList.toggle('is-open', open);
        if (toggle) toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
    }
    function closeOtherGroups(groups, current) {
        groups.forEach(function (group) { if (group !== current) setOpen(group, false); });
    }

    function enforceShell(sidebar) {
        if (enforcing) return;
        enforcing = true;
        try {
            var root = document.documentElement;
            var body = document.body;
            var shell = sidebar.closest('[data-native-shell]') || sidebar.parentElement;
            var main = shell ? shell.querySelector('[data-native-main]') : null;
            var rtl = root.dir === 'rtl' || String(root.lang || '').toLowerCase().indexOf('ar') === 0;

            removeClasses(body, LEGACY_COLLAPSE_CLASSES);
            removeClasses(shell, LEGACY_COLLAPSE_CLASSES.concat(LEGACY_SHELL_CLASSES));
            removeClasses(sidebar, LEGACY_COLLAPSE_CLASSES.concat(LEGACY_SIDEBAR_CLASSES));
            removeClasses(main, LEGACY_COLLAPSE_CLASSES.concat(LEGACY_MAIN_CLASSES));

            clearProperties(shell, ['display','grid-template-columns','grid-template-areas','width','max-width','min-width','margin','margin-left','margin-right','padding','transform','translate','direction']);
            clearProperties(sidebar, ['display','position','width','min-width','max-width','flex','flex-basis','margin','margin-left','margin-right','left','right','inset','inset-inline-start','inset-inline-end','transform','translate','visibility','opacity','clip-path','direction']);
            clearProperties(main, ['position','width','min-width','max-width','margin','margin-left','margin-right','left','right','inset','transform','translate','flex','flex-basis','direction']);

            if (shell) {
                shell.setAttribute('data-native-shell-contract','R4');
                shell.setAttribute('data-native-direction', rtl ? 'rtl' : 'ltr');
            }
            sidebar.setAttribute('data-native-sidebar-contract','R4');
            sidebar.setAttribute('dir', rtl ? 'rtl' : 'ltr');
            sidebar.removeAttribute('data-diar-sidebar-target');
            if (main) main.setAttribute('data-native-main-contract','R4');
            root.setAttribute('data-native-sidebar-direction', rtl ? 'RTL' : 'LTR');
            root.setAttribute('data-native-sidebar-release','R4');
        } finally {
            enforcing = false;
        }
    }

    function contentFits(sidebar) {
        var nav = sidebar.querySelector('[data-native-nav]');
        return sidebar.scrollHeight <= sidebar.clientHeight + 1 && (!nav || nav.scrollHeight <= nav.clientHeight + 1);
    }
    function applyDensity(sidebar) {
        sidebar.classList.remove('native-sidebar-height-compact','native-sidebar-height-ultra');
        requestAnimationFrame(function () {
            if (!contentFits(sidebar)) sidebar.classList.add('native-sidebar-height-compact');
            requestAnimationFrame(function () {
                if (!contentFits(sidebar)) sidebar.classList.add('native-sidebar-height-ultra');
                requestAnimationFrame(function () {
                    var pass = contentFits(sidebar);
                    var density = sidebar.classList.contains('native-sidebar-height-ultra') ? 'ULTRA' : (sidebar.classList.contains('native-sidebar-height-compact') ? 'COMPACT' : 'NORMAL');
                    sidebar.setAttribute('data-native-sidebar-density', density);
                    sidebar.setAttribute('data-native-sidebar-no-scroll', pass ? 'PASS' : 'FAIL');
                    document.documentElement.setAttribute('data-native-sidebar-no-scroll', pass ? 'PASS' : 'FAIL');
                });
            });
        });
    }

    function geometry(sidebar) {
        var root = document.documentElement;
        var shell = sidebar.closest('[data-native-shell]') || sidebar.parentElement;
        var main = shell ? shell.querySelector('[data-native-main]') : null;
        var mobile = window.matchMedia && window.matchMedia('(max-width: 760px)').matches;
        var rtl = root.dir === 'rtl' || String(root.lang || '').toLowerCase().indexOf('ar') === 0;
        var pass = true;
        var side = rtl ? 'RIGHT' : 'LEFT';
        if (!mobile && main) {
            var s = sidebar.getBoundingClientRect();
            var m = main.getBoundingClientRect();
            var h = shell.getBoundingClientRect();
            var tolerance = 5;
            var widthOk = s.width >= 286 && s.width <= 306;
            var sideOk = rtl ? Math.abs(h.right - s.right) <= tolerance : Math.abs(s.left - h.left) <= tolerance;
            var overlapOk = rtl ? m.right <= s.left + 2 : m.left >= s.right - 2;
            pass = widthOk && sideOk && overlapOk;
            root.setAttribute('data-native-sidebar-width', widthOk ? 'PASS' : 'FAIL');
            root.setAttribute('data-native-sidebar-side', sideOk ? side : 'FAIL');
            root.setAttribute('data-native-sidebar-overlap', overlapOk ? 'PASS' : 'FAIL');
            root.setAttribute('data-native-sidebar-shell-left', String(Math.round(h.left)));
            root.setAttribute('data-native-sidebar-shell-right', String(Math.round(h.right)));
            root.setAttribute('data-native-sidebar-left', String(Math.round(s.left)));
            root.setAttribute('data-native-sidebar-right', String(Math.round(s.right)));
        } else {
            root.setAttribute('data-native-sidebar-width','MOBILE');
            root.setAttribute('data-native-sidebar-side',side);
            root.setAttribute('data-native-sidebar-overlap','MOBILE');
        }
        root.setAttribute('data-native-sidebar-shell-contract', pass ? 'PASS' : 'FAIL');
        return pass;
    }

    function scheduleContract(sidebar) {
        window.clearTimeout(resizeTimer);
        resizeTimer = window.setTimeout(function () {
            enforceShell(sidebar);
            applyDensity(sidebar);
            requestAnimationFrame(function () {
                var shellPass = geometry(sidebar);
                var scrollPass = sidebar.getAttribute('data-native-sidebar-no-scroll') !== 'FAIL';
                document.documentElement.setAttribute('data-native-sidebar-contract-ready', shellPass && scrollPass ? 'PASS' : 'FAIL');
            });
        }, 30);
    }

    function initSidebar(sidebar) {
        var groups = Array.prototype.slice.call(sidebar.querySelectorAll('[data-nav-group]'));
        if (!groups.length) return;
        enforceShell(sidebar);

        var activeGroup = null;
        groups.forEach(function (group) { if (group.querySelector('[aria-current="page"]')) activeGroup = group; });
        if (!activeGroup) activeGroup = groups.filter(function (group) { return group.classList.contains('is-open'); })[0] || groups[0];
        closeOtherGroups(groups, activeGroup);
        setOpen(activeGroup, true);

        groups.forEach(function (group) {
            var toggle = group.querySelector('[data-nav-group-toggle]');
            if (!toggle) return;
            toggle.addEventListener('click', function () {
                var shouldOpen = !group.classList.contains('is-open');
                closeOtherGroups(groups, group);
                setOpen(group, shouldOpen);
                scheduleContract(sidebar);
            });
        });

        sidebar.querySelectorAll('.native-nav-item[href]').forEach(function (link) {
            link.addEventListener('click', function () {
                if (window.matchMedia && window.matchMedia('(max-width: 760px)').matches) document.body.classList.remove('sidebar-open');
            });
        });

        try { STORAGE_KEYS.forEach(function (key) { window.localStorage.removeItem(key); }); } catch (ignore) {}

        var shell = sidebar.closest('[data-native-shell]') || sidebar.parentElement;
        var main = shell ? shell.querySelector('[data-native-main]') : null;
        var observer = new MutationObserver(function () { scheduleContract(sidebar); });
        [document.body, shell, sidebar, main].forEach(function (node) {
            if (node) observer.observe(node, { attributes:true, attributeFilter:['class','style','dir'] });
        });

        scheduleContract(sidebar);
        window.addEventListener('resize', function () { scheduleContract(sidebar); }, { passive:true });
        window.addEventListener('load', function () { scheduleContract(sidebar); }, { once:true });
        if (document.fonts && document.fonts.ready) document.fonts.ready.then(function () { scheduleContract(sidebar); });
    }

    function boot() {
        document.documentElement.classList.add('native-sidebar-enhanced');
        document.querySelectorAll('[data-native-sidebar]').forEach(initSidebar);
    }

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