/**
 * Admin Dashboard JavaScript
 * Material Dashboard Theme
 */

(function () {
    'use strict';

    // Initialize on DOM ready
    document.addEventListener('DOMContentLoaded', function () {
        initComponents();
        initSidebar();
        initTopbar();
        initTheme();
        initCounterAnimation();
    });

    /**
     * Initialize Bootstrap components
     */
    function initComponents() {
        // Initialize all tooltips
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });

        // Initialize all popovers
        var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
        popoverTriggerList.map(function (popoverTriggerEl) {
            return new bootstrap.Popover(popoverTriggerEl);
        });

        // Initialize SimpleBar if available
        if (typeof SimpleBar !== 'undefined') {
            var scrollbarElements = document.querySelectorAll('[data-simplebar]');
            scrollbarElements.forEach(function (el) {
                new SimpleBar(el);
            });
        }

        // Initialize Feather icons if available
        if (typeof feather !== 'undefined') {
            feather.replace();
        }
    }

    /**
     * Initialize Sidebar
     */
    function initSidebar() {
        var sidebar = document.querySelector('.app-menu');
        var overlay = document.querySelector('.vertical-overlay');
        var hamburger = document.getElementById('topnav-hamburger-icon');

        if (hamburger) {
            hamburger.addEventListener('click', function () {
                if (sidebar) {
                    sidebar.classList.toggle('show');
                }
                if (overlay) {
                    overlay.classList.toggle('show');
                }
                document.body.classList.toggle('menu-open');
            });
        }

        if (overlay) {
            overlay.addEventListener('click', function () {
                if (sidebar) {
                    sidebar.classList.remove('show');
                }
                overlay.classList.remove('show');
                document.body.classList.remove('menu-open');
            });
        }

        // Handle submenu toggles
        var menuLinks = document.querySelectorAll('.menu-link[data-bs-toggle="collapse"]');
        menuLinks.forEach(function (link) {
            link.addEventListener('click', function (e) {
                var target = document.querySelector(this.getAttribute('href'));
                if (target) {
                    // Close other submenus at the same level
                    var parent = this.closest('.nav-item');
                    var siblings = parent.parentElement.querySelectorAll('.menu-dropdown.show');
                    siblings.forEach(function (sibling) {
                        if (sibling !== target) {
                            sibling.classList.remove('show');
                        }
                    });
                }
            });
        });

        // Keep active menu expanded
        var activeLink = document.querySelector('.navbar-nav .nav-link.active');
        if (activeLink) {
            var parentCollapse = activeLink.closest('.menu-dropdown');
            while (parentCollapse) {
                parentCollapse.classList.add('show');
                var toggle = document.querySelector('[href="#' + parentCollapse.id + '"]');
                if (toggle) {
                    toggle.setAttribute('aria-expanded', 'true');
                }
                parentCollapse = parentCollapse.parentElement.closest('.menu-dropdown');
            }
        }
    }

    /**
     * Initialize Topbar
     */
    function initTopbar() {
        // Fullscreen toggle
        var fullscreenBtn = document.querySelector('[data-toggle="fullscreen"]');
        if (fullscreenBtn) {
            fullscreenBtn.addEventListener('click', function (e) {
                e.preventDefault();
                if (!document.fullscreenElement) {
                    document.documentElement.requestFullscreen();
                    this.querySelector('i').classList.remove('bx-fullscreen');
                    this.querySelector('i').classList.add('bx-exit-fullscreen');
                } else {
                    document.exitFullscreen();
                    this.querySelector('i').classList.remove('bx-exit-fullscreen');
                    this.querySelector('i').classList.add('bx-fullscreen');
                }
            });
        }

        // Search functionality
        var searchInput = document.getElementById('search-options');
        var searchDropdown = document.getElementById('search-dropdown');
        var searchClose = document.getElementById('search-close-options');

        if (searchInput && searchDropdown) {
            searchInput.addEventListener('focus', function () {
                searchDropdown.classList.add('show');
            });

            searchInput.addEventListener('blur', function () {
                setTimeout(function () {
                    searchDropdown.classList.remove('show');
                }, 200);
            });

            if (searchClose) {
                searchClose.addEventListener('click', function () {
                    searchInput.value = '';
                    searchDropdown.classList.remove('show');
                });
            }
        }
    }

    /**
     * Initialize Theme
     */
    function initTheme() {
        var lightDarkBtn = document.querySelector('.light-dark-mode');
        if (lightDarkBtn) {
            lightDarkBtn.addEventListener('click', function () {
                var currentTheme = document.documentElement.getAttribute('data-bs-theme');
                var newTheme = currentTheme === 'dark' ? 'light' : 'dark';
                document.documentElement.setAttribute('data-bs-theme', newTheme);
                localStorage.setItem('theme', newTheme);

                // Update icon
                var icon = this.querySelector('i');
                if (icon) {
                    if (newTheme === 'dark') {
                        icon.classList.remove('bx-moon');
                        icon.classList.add('bx-sun');
                    } else {
                        icon.classList.remove('bx-sun');
                        icon.classList.add('bx-moon');
                    }
                }
            });

            // Load saved theme
            var savedTheme = localStorage.getItem('theme');
            if (savedTheme) {
                document.documentElement.setAttribute('data-bs-theme', savedTheme);
                var icon = lightDarkBtn.querySelector('i');
                if (icon && savedTheme === 'dark') {
                    icon.classList.remove('bx-moon');
                    icon.classList.add('bx-sun');
                }
            }
        }
    }

    /**
     * Initialize Counter Animation
     */
    function initCounterAnimation() {
        var counters = document.querySelectorAll('.counter-value');
        counters.forEach(function (counter) {
            var target = parseFloat(counter.getAttribute('data-target')) || 0;
            var duration = 1000;
            var startTime = null;

            function animate(currentTime) {
                if (!startTime) startTime = currentTime;
                var progress = Math.min((currentTime - startTime) / duration, 1);
                var currentValue = progress * target;

                if (Number.isInteger(target)) {
                    counter.textContent = Math.floor(currentValue);
                } else {
                    counter.textContent = currentValue.toFixed(2);
                }

                if (progress < 1) {
                    requestAnimationFrame(animate);
                } else {
                    counter.textContent = target;
                }
            }

            // Use Intersection Observer to trigger animation when visible
            var observer = new IntersectionObserver(function (entries) {
                entries.forEach(function (entry) {
                    if (entry.isIntersecting) {
                        requestAnimationFrame(animate);
                        observer.unobserve(entry.target);
                    }
                });
            }, { threshold: 0.5 });

            observer.observe(counter);
        });
    }

    /**
     * Show loading overlay
     */
    window.showLoading = function () {
        var overlay = document.createElement('div');
        overlay.className = 'loading-overlay';
        overlay.innerHTML = '<div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div>';
        document.body.appendChild(overlay);
    };

    /**
     * Hide loading overlay
     */
    window.hideLoading = function () {
        var overlay = document.querySelector('.loading-overlay');
        if (overlay) {
            overlay.remove();
        }
    };

    /**
     * Show toast notification
     */
    window.showToast = function (message, type) {
        type = type || 'info';

        var toastContainer = document.getElementById('toast-container');
        if (!toastContainer) {
            toastContainer = document.createElement('div');
            toastContainer.id = 'toast-container';
            toastContainer.className = 'toast-container position-fixed bottom-0 end-0 p-3';
            document.body.appendChild(toastContainer);
        }

        var toastId = 'toast-' + Date.now();
        var toast = document.createElement('div');
        toast.id = toastId;
        toast.className = 'toast align-items-center text-white bg-' + type + ' border-0';
        toast.setAttribute('role', 'alert');
        toast.innerHTML = `
            <div class="d-flex">
                <div class="toast-body">${message}</div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        `;

        toastContainer.appendChild(toast);
        var bsToast = new bootstrap.Toast(toast);
        bsToast.show();

        toast.addEventListener('hidden.bs.toast', function () {
            toast.remove();
        });
    };

    /**
     * Confirm dialog
     */
    window.confirmAction = function (message, callback) {
        if (confirm(message)) {
            callback();
        }
    };

    /**
     * Delete confirmation
     */
    document.querySelectorAll('[data-confirm-delete]').forEach(function (btn) {
        btn.addEventListener('click', function (e) {
            e.preventDefault();
            var form = this.closest('form');
            var message = this.getAttribute('data-confirm-delete') || 'Are you sure you want to delete this item?';

            if (confirm(message)) {
                form.submit();
            }
        });
    });

})();
