/* Bootstrap 5 Initialization Script for WHP */
/* This replaces Bootstrap 3 specific functionality with Bootstrap 5 compatible versions */

(function($) {
    'use strict';
    
    // Wait for DOM to be ready
    $(document).ready(function() {
        
        // Initialize Bootstrap 5 components
        initializeBootstrap5Components();
        
        // Replace incompatible MetisMenu with Bootstrap 5 collapse
        initializeNavigationMenu();
        
        // Fix dropdown functionality
        initializeDropdowns();
        
        // Initialize modals
        initializeModals();
        
        // Fix splash screen hiding
        hideSplashScreen();
        
    });
    
    // Initialize all Bootstrap 5 components
    function initializeBootstrap5Components() {
        // Tooltips
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl);
        });
        
        // Popovers
        var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
        var popoverList = popoverTriggerList.map(function (popoverTriggerEl) {
            return new bootstrap.Popover(popoverTriggerEl);
        });
        
        // Initialize all modals
        var modalList = document.querySelectorAll('.modal');
        modalList.forEach(function(modalEl) {
            new bootstrap.Modal(modalEl, {
                backdrop: true,
                keyboard: true
            });
        });
        
        // Initialize all dropdowns
        var dropdownElementList = [].slice.call(document.querySelectorAll('[data-bs-toggle="dropdown"]'));
        var dropdownList = dropdownElementList.map(function (dropdownToggleEl) {
            return new bootstrap.Dropdown(dropdownToggleEl);
        });
        
        // Initialize collapse components
        var collapseElementList = [].slice.call(document.querySelectorAll('[data-bs-toggle="collapse"]'));
        var collapseList = collapseElementList.map(function (collapseEl) {
            return new bootstrap.Collapse(collapseEl, {
                toggle: false
            });
        });
    }
    
    // Replace MetisMenu with Bootstrap 5 compatible navigation
    function initializeNavigationMenu() {
        // Remove MetisMenu if it exists
        if (typeof $.fn.metisMenu !== 'undefined') {
            $('#side-menu').off('.metis');
        }
        
        // Simple accordion-style navigation
        $('#side-menu li').each(function() {
            var $li = $(this);
            var $link = $li.children('a');
            var $submenu = $li.children('ul');
            
            if ($submenu.length > 0) {
                // Add collapse functionality
                $link.on('click', function(e) {
                    e.preventDefault();
                    
                    var $parent = $(this).parent();
                    var $submenu = $parent.children('ul');
                    
                    if ($submenu.hasClass('show')) {
                        $submenu.removeClass('show').slideUp(200);
                        $parent.removeClass('active');
                    } else {
                        // Close other open submenus
                        $('#side-menu ul.show').removeClass('show').slideUp(200);
                        $('#side-menu li.active').removeClass('active');
                        
                        // Open this submenu
                        $submenu.addClass('show').slideDown(200);
                        $parent.addClass('active');
                    }
                });
                
                // Add arrow indicator
                if ($link.find('.arrow').length === 0) {
                    $link.append('<span class="arrow fa fa-angle-left pull-right"></span>');
                }
            }
        });
    }
    
    // Fix dropdown functionality
    function initializeDropdowns() {
        // Manual dropdown handling for user dropdown
        $(document).on('click', '.dropdown-toggle', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            var $this = $(this);
            var $dropdown = $this.next('.dropdown-menu');
            var $parent = $this.parent('.dropdown');
            
            // Close other dropdowns first
            $('.dropdown-menu').not($dropdown).removeClass('show').hide();
            $('.dropdown').not($parent).removeClass('show');
            
            // Toggle this dropdown
            if ($dropdown.hasClass('show')) {
                $dropdown.removeClass('show').hide();
                $parent.removeClass('show');
            } else {
                $dropdown.addClass('show').show();
                $parent.addClass('show');
                
                // Ensure proper positioning
                $dropdown.css({
                    'position': 'absolute',
                    'top': '100%',
                    'right': '0',
                    'left': 'auto',
                    'z-index': '10000',
                    'display': 'block'
                });
            }
        });
        
        // Close dropdowns when clicking outside
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.dropdown').length) {
                $('.dropdown-menu.show').removeClass('show').hide();
                $('.dropdown.show').removeClass('show');
            }
        });
        
        // Prevent dropdown from closing when clicking inside
        $(document).on('click', '.dropdown-menu', function(e) {
            e.stopPropagation();
        });
    }
    
    // Initialize modal functionality
    function initializeModals() {
        // Ensure modals work with both jQuery and native Bootstrap 5 API
        $('[data-bs-toggle="modal"]').on('click', function(e) {
            e.preventDefault();
            var target = $(this).attr('data-bs-target') || $(this).attr('data-target');
            if (target) {
                var modal = document.querySelector(target);
                if (modal) {
                    var bsModal = bootstrap.Modal.getInstance(modal) || new bootstrap.Modal(modal);
                    bsModal.show();
                }
            }
        });
        
        // Handle modal close buttons
        $('.modal').on('click', '[data-bs-dismiss="modal"], [data-dismiss="modal"]', function() {
            var modal = $(this).closest('.modal')[0];
            if (modal) {
                var bsModal = bootstrap.Modal.getInstance(modal);
                if (bsModal) {
                    bsModal.hide();
                }
            }
        });
    }
    
    // Fix navbar collapse for mobile
    function initializeNavbarToggle() {
        $('.navbar-toggle, .navbar-toggler').on('click', function() {
            var target = $(this).attr('data-bs-target') || $(this).attr('data-target');
            if (target) {
                var $collapse = $(target);
                $collapse.toggleClass('show');
            }
        });
    }
    
    // Initialize navbar toggle
    initializeNavbarToggle();
    
    // Fix panel collapse functionality
    function initializePanelCollapse() {
        $(document).on('click', '[data-panel-toggle]', function(e) {
            e.preventDefault();
            var $panel = $(this).closest('.panel');
            var $body = $panel.find('.panel-body, .panel-footer');
            
            if ($panel.hasClass('panel-collapsed')) {
                $body.slideDown(200);
                $panel.removeClass('panel-collapsed');
            } else {
                $body.slideUp(200);
                $panel.addClass('panel-collapsed');
            }
        });
        
        $(document).on('click', '[data-panel-dismiss]', function(e) {
            e.preventDefault();
            var $panel = $(this).closest('.panel');
            $panel.fadeOut(200, function() {
                $panel.remove();
            });
        });
    }
    
    // Initialize panel functionality
    initializePanelCollapse();
    
    // Fix sidebar functionality
    function initializeSidebar() {
        var $body = $('body');
        var $sidebar = $('.navbar-aside');
        
        // Sidebar toggle functionality
        $('.navbar-minimalize').off('click').on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            console.log('Hamburger menu clicked'); // Debug log
            
            if ($(window).width() < 769) {
                $body.toggleClass('show-sidebar');
            } else {
                $body.toggleClass('hide-sidebar');
            }
        });
        
        // Handle window resize
        $(window).on('resize', function() {
            if ($(window).width() < 769) {
                $body.addClass('page-small');
                $body.removeClass('hide-sidebar');
            } else {
                $body.removeClass('page-small show-sidebar');
            }
        });
        
        // Initial call
        $(window).trigger('resize');
        
        // Fix sidebar navigation spacing and clickability
        $('#side-menu li a').css({
            'display': 'block',
            'padding': '15px 20px',
            'line-height': '15px',
            'color': '#6a6c6f',
            'text-decoration': 'none',
            'background': 'transparent'
        });
        
        // Fix active state styling
        $('#side-menu li.active a, #side-menu li:hover a').css({
            'color': '#067b9f',
            'background': 'transparent'
        });
        
        // Ensure sidebar links are clickable
        $('#side-menu li a').off('click').on('click', function(e) {
            // Remove active class from all items
            $('#side-menu li').removeClass('active');
            // Add active class to clicked item
            $(this).parent().addClass('active');
        });
    }
    
    // Initialize sidebar
    initializeSidebar();
    
    // Fix splash screen hiding
    function hideSplashScreen() {
        var $splash = $('.splash');
        
        function removeSplash() {
            if ($splash.length) {
                $splash.addClass('fade-out');
                setTimeout(function() {
                    $splash.addClass('hidden').remove();
                }, 350);
            }
        }
        
        // Method 1: Hide immediately if everything is ready
        if (document.readyState === 'complete') {
            removeSplash();
            return;
        }
        
        // Method 2: Hide after DOM is fully loaded
        $(document).ready(function() {
            setTimeout(removeSplash, 500);
        });
        
        // Method 3: Hide after window load event
        $(window).on('load', function() {
            removeSplash();
        });
        
        // Method 4: Emergency fallback - hide after 2 seconds regardless
        setTimeout(function() {
            removeSplash();
        }, 2000);
        
        // Method 5: Hide when Bootstrap components are initialized
        setTimeout(function() {
            if (typeof bootstrap !== 'undefined') {
                removeSplash();
            }
        }, 1000);
    }
    
})(jQuery); 