window.AdminUI = {
    iconMap: {
        'fa-arrow-left': 'bi-arrow-left',
        'fa-arrow-right-from-bracket': 'bi-box-arrow-right',
        'fa-arrow-rotate-left': 'bi-arrow-clockwise',
        'fa-arrows-rotate': 'bi-arrow-repeat',
        'fa-bag-shopping': 'bi-bag-check',
        'fa-ban': 'bi-slash-circle',
        'fa-bars': 'bi-list',
        'fa-bars-staggered': 'bi-layout-sidebar-inset',
        'fa-bolt': 'bi-lightning-charge',
        'fa-box': 'bi-box-seam',
        'fa-chart-line': 'bi-graph-up-arrow',
        'fa-chart-pie': 'bi-pie-chart',
        'fa-chart-simple': 'bi-bar-chart',
        'fa-check-circle': 'bi-check-circle',
        'fa-circle-check': 'bi-check-circle',
        'fa-circle-exclamation': 'bi-exclamation-circle',
        'fa-circle-notch': 'bi-arrow-repeat',
        'fa-circle-question': 'bi-question-circle',
        'fa-clock': 'bi-clock',
        'fa-clone': 'bi-copy',
        'fa-code-branch': 'bi-diagram-3',
        'fa-cog': 'bi-gear',
        'fa-columns': 'bi-layout-three-columns',
        'fa-copyright': 'bi-award',
        'fa-credit-card': 'bi-credit-card',
        'fa-dollar-sign': 'bi-currency-dollar',
        'fa-edit': 'bi-pencil-square',
        'fa-ellipsis-v': 'bi-three-dots-vertical',
        'fa-envelope': 'bi-envelope',
        'fa-exclamation-circle': 'bi-exclamation-circle',
        'fa-exclamation-triangle': 'bi-exclamation-triangle',
        'fa-eye': 'bi-eye',
        'fa-file-excel': 'bi-file-earmark-spreadsheet',
        'fa-file-lines': 'bi-file-earmark-text',
        'fa-filter': 'bi-funnel',
        'fa-fire': 'bi-fire',
        'fa-floppy-disk': 'bi-floppy',
        'fa-folder-open': 'bi-folder2-open',
        'fa-folder-plus': 'bi-folder-plus',
        'fa-gauge-high': 'bi-grid-1x2',
        'fa-globe-americas': 'bi-globe-americas',
        'fa-image': 'bi-image',
        'fa-images': 'bi-images',
        'fa-inbox': 'bi-inbox',
        'fa-info-circle': 'bi-info-circle',
        'fa-key': 'bi-shield-lock',
        'fa-language': 'bi-translate',
        'fa-layer-group': 'bi-tags',
        'fa-map-marker-alt': 'bi-geo-alt',
        'fa-money-bill-wave': 'bi-cash-stack',
        'fa-moon': 'bi-moon',
        'fa-pen': 'bi-pencil-square',
        'fa-phone': 'bi-telephone',
        'fa-plus': 'bi-plus-lg',
        'fa-plus-circle': 'bi-plus-circle',
        'fa-print': 'bi-printer',
        'fa-receipt': 'bi-receipt',
        'fa-save': 'bi-floppy',
        'fa-scale-balanced': 'bi-rulers',
        'fa-search': 'bi-search',
        'fa-shopping-cart': 'bi-cart3',
        'fa-sitemap': 'bi-diagram-3',
        'fa-sliders': 'bi-gear',
        'fa-sliders-h': 'bi-sliders',
        'fa-sync': 'bi-arrow-repeat',
        'fa-tags': 'bi-tags',
        'fa-tasks': 'bi-list-check',
        'fa-times': 'bi-x-lg',
        'fa-tools': 'bi-tools',
        'fa-trash': 'bi-trash',
        'fa-triangle-exclamation': 'bi-exclamation-triangle',
        'fa-truck': 'bi-truck',
        'fa-university': 'bi-bank',
        'fa-upload': 'bi-upload',
        'fa-user': 'bi-person',
        'fa-user-gear': 'bi-person-gear',
        'fa-user-group': 'bi-people',
        'fa-user-shield': 'bi-person-badge',
        'fa-users': 'bi-people',
        'fa-wallet': 'bi-wallet2',
        'fa-xmark': 'bi-x-lg'
    },
    normalizeIcons(root = document) {
        root.querySelectorAll('i[class*="fa-"], i.fas, i.fa-solid').forEach((icon) => {
            const mapped = [...icon.classList].map((className) => this.iconMap[className]).find(Boolean);
            if (!mapped) return;
            icon.className = `bi ${mapped}`;
        });
    },
    observeIcons() {
        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                mutation.addedNodes.forEach((node) => {
                    if (node.nodeType === 1) this.normalizeIcons(node);
                });
            });
        });
        observer.observe(document.body, { childList: true, subtree: true });
    },
    toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebar-overlay');
        if (!sidebar || !overlay) return;
        const opening = !sidebar.classList.contains('sidebar-mobile-visible');
        sidebar.classList.toggle('sidebar-mobile-visible', opening);
        overlay.classList.toggle('hidden', !opening);
        document.body.classList.toggle('overflow-hidden', opening && window.innerWidth < 768);
    },
    toggleSidebarCollapse() {
        document.documentElement.classList.toggle('admin-sidebar-is-collapsed');
        localStorage.setItem('adminSidebarCollapsed', document.documentElement.classList.contains('admin-sidebar-is-collapsed'));
    },
    toggleDarkMode() {
        document.documentElement.classList.toggle('dark');
        localStorage.setItem('darkMode', document.documentElement.classList.contains('dark'));
        this.syncThemeIcon();
    },
    syncThemeIcon() {
        const icon = document.getElementById('dark-mode-icon');
        if (!icon) return;
        icon.classList.toggle('bi-sun', document.documentElement.classList.contains('dark'));
        icon.classList.toggle('bi-moon', !document.documentElement.classList.contains('dark'));
    },
    hideAlert(id) {
        const alert = document.getElementById(id);
        if (!alert) return;
        alert.style.opacity = '0';
        setTimeout(() => alert.remove(), 200);
    },
    initNavGroups() {
        document.querySelectorAll('[data-admin-nav-group]').forEach((button) => {
            button.addEventListener('click', () => {
                const group = button.closest('.admin-nav-group');
                const open = !group.classList.contains('is-open');
                group.classList.toggle('is-open', open);
                button.setAttribute('aria-expanded', open ? 'true' : 'false');
            });
        });
    },
    initSidebarScroll() {
        const sidebarNav = document.getElementById('admin-sidebar-nav');
        if (!sidebarNav) return;
        const savedSidebarScroll = sessionStorage.getItem('adminSidebarScrollTop');
        if (savedSidebarScroll !== null) sidebarNav.scrollTop = Number(savedSidebarScroll);
        sidebarNav.addEventListener('click', (event) => {
            if (event.target.closest('a')) sessionStorage.setItem('adminSidebarScrollTop', sidebarNav.scrollTop);
        });
    },
    initTooltips() {
        if (!window.bootstrap) return;
        document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach((el) => new bootstrap.Tooltip(el));
    },
    initSubmitLoading() {
        document.querySelectorAll('form').forEach((form) => {
            form.addEventListener('submit', () => {
                if ((form.getAttribute('method') || 'GET').toUpperCase() === 'GET') return;
                const submit = form.querySelector('button[type="submit"]');
                if (!submit || submit.dataset.noLoading === 'true') return;
                submit.dataset.originalHtml = submit.innerHTML;
                submit.disabled = true;
                submit.innerHTML = '<span class="admin-loading-spinner"></span><span>Saving...</span>';
            });
        });
    },
    initFormComponents() {
        const bindSearchClear = (button) => {
            if (button.dataset.bound === 'true') return;
            button.dataset.bound = 'true';
            button.addEventListener('click', () => {
                const input = button.closest('.admin-search-control')?.querySelector('input');
                if (!input) return;
                input.value = '';
                input.dispatchEvent(new Event('input', { bubbles: true }));
                input.dispatchEvent(new Event('change', { bubbles: true }));
                input.focus();
            });
        };

        const enhance = (root = document) => {
            root.querySelectorAll?.('.admin-main input:not([type="hidden"]):not([type="checkbox"]):not([type="radio"]):not([type="file"]), .admin-main select, .admin-main textarea').forEach((control) => {
                if (control.closest('.dataTables_wrapper')) return;
                control.classList.add('admin-form-control');
                if (control.tagName === 'SELECT') control.classList.add('admin-form-select');
                if (control.tagName === 'TEXTAREA') control.classList.add('admin-form-textarea');
            });

            root.querySelectorAll?.('.admin-main input[id$="Search"], .admin-main input[type="search"]').forEach((input) => {
                if (input.dataset.adminSearchEnhanced === 'true') return;
                input.dataset.adminSearchEnhanced = 'true';
                input.classList.add('admin-form-control', 'admin-search-enhanced');
                const container = input.parentElement;
                if (!container) return;
                container.classList.add('admin-search-control');
            });
        };

        enhance(document);

        if (window.jQuery?.fn?.select2) {
            window.jQuery('[data-admin-searchable-select]').each(function () {
                const select = window.jQuery(this);
                if (select.hasClass('select2-hidden-accessible')) return;
                select.select2({ width: '100%', allowClear: !this.required, placeholder: this.dataset.placeholder || '' });
            });
        }

        if (window.flatpickr) {
            document.querySelectorAll('[data-admin-date-picker], [data-admin-time-picker], [data-admin-datetime-picker]').forEach((input) => {
                if (input._flatpickr) return;
                flatpickr(input, {
                    enableTime: input.hasAttribute('data-admin-time-picker') || input.hasAttribute('data-admin-datetime-picker'),
                    noCalendar: input.hasAttribute('data-admin-time-picker'),
                    dateFormat: input.hasAttribute('data-admin-datetime-picker') ? 'Y-m-d\\TH:i' : (input.hasAttribute('data-admin-time-picker') ? 'H:i' : 'Y-m-d'),
                });
            });
        }

        if (!this.formObserver) {
            this.formObserver = new MutationObserver((mutations) => mutations.forEach((mutation) => mutation.addedNodes.forEach((node) => {
                if (node.nodeType === 1) enhance(node);
            })));
            const main = document.querySelector('.admin-main');
            if (main) this.formObserver.observe(main, { childList: true, subtree: true });
        }
    },
    boot() {
        this.normalizeIcons();
        this.observeIcons();
        this.syncThemeIcon();
        this.initNavGroups();
        this.initSidebarScroll();
        this.initTooltips();
        this.initSubmitLoading();
        this.initFormComponents();
        ['success-alert', 'error-alert'].forEach((id) => {
            if (document.getElementById(id)) setTimeout(() => this.hideAlert(id), 5000);
        });
    }
};

window.toggleDropdown = function(id) {
    var dropdown = document.getElementById('dropdown-' + id);
    if (dropdown) {
        // Hide all other open dropdowns first
        document.querySelectorAll('[id^="dropdown-"]').forEach(function(el) {
            if (el.id !== 'dropdown-' + id) {
                el.classList.add('hidden');
            }
        });
        dropdown.classList.toggle('hidden');
    }
};

window.openModal = function(id) {
    var modal = document.getElementById(id);
    if (modal) {
        modal.classList.remove('hidden');
        document.body.classList.add('overflow-hidden');
    }
};

window.closeModal = function(id) {
    var modal = document.getElementById(id);
    if (modal) {
        modal.classList.add('hidden');
        document.body.classList.remove('overflow-hidden');
    }
};

// Close dropdown when clicking outside
document.addEventListener('click', function(event) {
    if (!event.target.closest('[onclick*="toggleDropdown"]') && !event.target.closest('[id^="dropdown-"]')) {
        document.querySelectorAll('[id^="dropdown-"]').forEach(function(el) {
            el.classList.add('hidden');
        });
    }
});

document.addEventListener('DOMContentLoaded', () => window.AdminUI.boot());
