(function () {
    'use strict';

    var root = document.documentElement;
    root.classList.add('diar-ui1-r3-active');
    root.classList.add('diar-ui3-r0-active');

    function uniquePush(list, node) {
        if (node && list.indexOf(node) === -1) {
            list.push(node);
        }
    }

    function textLeafNodes(container) {
        return container ? container.querySelectorAll('*') : [];
    }

    function normalizeSidebarIdentity(sidebar) {
        if (!sidebar) {
            return;
        }
        var isRtl = root.dir === 'rtl' || (root.lang || '').toLowerCase().indexOf('ar') === 0;
        var replacement = isRtl ? 'مجموعة HMH · لوحة القيادة التنفيذية' : 'HMH Group · Executive Dashboard';
        textLeafNodes(sidebar).forEach(function (node) {
            if (node.children.length !== 0) {
                return;
            }
            var text = (node.textContent || '').trim();
            if (text === 'Madina National Hospital' || text === 'New Jeddah Clinic Hospital' || text === 'مستشفى المدينة الوطني' || text === 'مستشفى جدة الوطني الجديد') {
                node.textContent = replacement;
                node.setAttribute('data-diar-group-identity', 'true');
            }
        });
    }

    function scoreSidebar(node) {
        if (!node || node === document.body || node === root) {
            return -1;
        }
        var rect = node.getBoundingClientRect();
        var style = window.getComputedStyle(node);
        var signature = ((node.id || '') + ' ' + (typeof node.className === 'string' ? node.className : '')).toLowerCase();
        var actions = node.querySelectorAll('a,button,[role="menuitem"]').length;
        var score = 0;
        if (/sidebar|side-nav|sidenav|navigation-drawer|main-nav/.test(signature)) { score += 12; }
        if (node.tagName === 'ASIDE') { score += 4; }
        if (actions >= 4) { score += 5; }
        if (rect.width >= 64 && rect.width <= 380) { score += 4; }
        if (rect.height >= Math.min(window.innerHeight * 0.55, 480)) { score += 4; }
        if (style.position === 'fixed' || style.position === 'sticky' || style.position === 'absolute') { score += 3; }
        if ((rect.width < 40 || rect.height < 180) && !/sidebar|side-nav|sidenav|navigation-drawer|main-nav/.test(signature)) { score -= 20; }
        return score;
    }

    function locateSidebar() {
        var candidates = [];
        [
            '.sidebar', '.main-sidebar', '.app-sidebar', '.executive-sidebar', '.side-nav', '.sidenav',
            '#sidebar', '[data-sidebar]', '[class*="sidebar"]', '[class*="side-nav"]', 'aside'
        ].forEach(function (selector) {
            document.querySelectorAll(selector).forEach(function (node) {
                uniquePush(candidates, node);
            });
        });
        var best = null;
        var bestScore = -1;
        candidates.forEach(function (node) {
            var score = scoreSidebar(node);
            if (score > bestScore) {
                best = node;
                bestScore = score;
            }
        });
        return bestScore >= 6 ? best : null;
    }

    function findPrimaryMain(sidebar) {
        var candidates = [];
        [
            'main', '[role="main"]', '.main-content', '.content-wrapper', '.page-wrapper', '.app-main',
            '.dashboard-main', '.main-wrapper', '.content-shell', '.page-shell'
        ].forEach(function (selector) {
            document.querySelectorAll(selector).forEach(function (node) {
                if (!sidebar.contains(node) && !node.contains(sidebar)) {
                    uniquePush(candidates, node);
                }
            });
        });
        if (sidebar.parentElement) {
            Array.prototype.forEach.call(sidebar.parentElement.children, function (node) {
                if (node !== sidebar) {
                    uniquePush(candidates, node);
                }
            });
        }
        var best = null;
        var bestArea = 0;
        candidates.forEach(function (node) {
            var rect = node.getBoundingClientRect();
            var area = Math.max(0, rect.width) * Math.max(0, rect.height);
            if (rect.width >= Math.min(320, window.innerWidth * 0.45) && area > bestArea) {
                best = node;
                bestArea = area;
            }
        });
        return best;
    }

    function clearSidebarLayoutClasses() {
        document.querySelectorAll('.diar-layout-sidebar').forEach(function (node) {
            node.classList.remove('diar-layout-sidebar', 'diar-layout-sidebar-fixed');
            node.removeAttribute('data-diar-sidebar-target');
        });
        document.querySelectorAll('.diar-layout-main').forEach(function (node) {
            node.classList.remove('diar-layout-main', 'diar-layout-main-fixed-offset');
        });
        document.querySelectorAll('.diar-layout-parent').forEach(function (node) {
            node.classList.remove('diar-layout-parent', 'diar-layout-grid', 'diar-layout-flex');
        });
    }

    function applySidebarDirection() {
        clearSidebarLayoutClasses();
        var sidebar = locateSidebar();
        if (!sidebar) {
            root.setAttribute('data-diar-sidebar-detected', 'FAIL');
            root.setAttribute('data-diar-sidebar-rtl', 'FAIL');
            root.setAttribute('data-diar-sidebar-position', 'FAIL');
            return;
        }

        normalizeSidebarIdentity(sidebar);
        sidebar.classList.add('diar-layout-sidebar');
        sidebar.setAttribute('data-diar-sidebar-target', 'true');
        root.setAttribute('data-diar-sidebar-detected', 'PASS');

        var rect = sidebar.getBoundingClientRect();
        var width = Math.max(64, Math.round(rect.width || 240));
        root.style.setProperty('--diar-shell-sidebar-width', width + 'px');

        var parent = sidebar.parentElement;
        var main = findPrimaryMain(sidebar);
        var parentDisplay = parent ? window.getComputedStyle(parent).display : '';
        if (parent && parentDisplay.indexOf('grid') !== -1 && main && main.parentElement === parent) {
            parent.classList.add('diar-layout-parent', 'diar-layout-grid');
            main.classList.add('diar-layout-main');
        } else if (parent && parentDisplay.indexOf('flex') !== -1 && main && main.parentElement === parent) {
            parent.classList.add('diar-layout-parent', 'diar-layout-flex');
            main.classList.add('diar-layout-main');
        } else {
            sidebar.classList.add('diar-layout-sidebar-fixed');
            if (main) {
                main.classList.add('diar-layout-main', 'diar-layout-main-fixed-offset');
            }
        }

        var isRtl = root.dir === 'rtl' || (root.lang || '').toLowerCase().indexOf('ar') === 0;
        root.classList.toggle('diar-rtl-shell', isRtl);
        sidebar.setAttribute('dir', isRtl ? 'rtl' : 'ltr');

        window.setTimeout(function () {
            var currentRect = sidebar.getBoundingClientRect();
            var visible = currentRect.width > 1 && currentRect.height > 1 && window.getComputedStyle(sidebar).display !== 'none';
            var compact = window.innerWidth <= 720;
            var containerRect = parent ? parent.getBoundingClientRect() : {left: 0, right: window.innerWidth};
            var positionPass;
            if (!visible || compact) {
                positionPass = true;
            } else if (isRtl) {
                positionPass = Math.abs(currentRect.right - Math.min(window.innerWidth, containerRect.right)) <= 5;
            } else {
                positionPass = Math.abs(currentRect.left - Math.max(0, containerRect.left)) <= 5;
            }
            var directionPass = !isRtl || window.getComputedStyle(sidebar).direction === 'rtl';
            root.setAttribute('data-diar-sidebar-rtl', directionPass ? 'PASS' : 'FAIL');
            root.setAttribute('data-diar-sidebar-position', positionPass ? 'PASS' : 'FAIL');
        }, 120);
    }

    applySidebarDirection();
    window.addEventListener('resize', applySidebarDirection);
    if (window.MutationObserver) {
        new MutationObserver(function (records) {
            var changed = records.some(function (record) {
                return record.type === 'attributes' && (record.attributeName === 'dir' || record.attributeName === 'lang');
            });
            if (changed) {
                applySidebarDirection();
            }
        }).observe(root, {attributes: true, attributeFilter: ['dir', 'lang']});
    }

    var forms = document.querySelectorAll('.diar-command-filters, .diar-fact-filters, .diar-profile-filters');
    forms.forEach(function (form) {
        form.addEventListener('submit', function () {
            var button = form.querySelector('button[type="submit"]');
            if (!button) {
                return;
            }
            button.disabled = true;
            button.setAttribute('aria-busy', 'true');
        });
    });

    var dateFrom = document.querySelector('.diar-fact-filters input[name="date_from"]');
    var dateTo = document.querySelector('.diar-fact-filters input[name="date_to"]');
    if (dateFrom && dateTo) {
        var validateRange = function () {
            dateFrom.setCustomValidity('');
            if (!dateFrom.value || !dateTo.value) {
                return;
            }
            var from = new Date(dateFrom.value + 'T00:00:00');
            var to = new Date(dateTo.value + 'T00:00:00');
            var days = Math.floor((to.getTime() - from.getTime()) / 86400000);
            if (days < 0) {
                dateFrom.setCustomValidity(root.dir === 'rtl' ? 'تاريخ البداية يجب ألا يتجاوز تاريخ النهاية.' : 'From date cannot be after to date.');
            } else if (days > 30) {
                dateFrom.setCustomValidity(root.dir === 'rtl' ? 'الحد الأقصى للفترة هو 31 يومًا.' : 'The maximum query window is 31 days.');
            }
        };
        dateFrom.addEventListener('change', validateRange);
        dateTo.addEventListener('change', validateRange);
    }
}());
