// Top Navigation Functionality
$(document).ready(function() {
    // Initialize dropdowns
    $('.dropdown-toggle').dropdown();
    
    // Mobile menu toggle
    $('.navbar-toggler').on('click', function() {
        $('#mainNavbar').toggleClass('show');
    });
    
    // Close dropdown when clicking outside
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.dropdown').length) {
            $('.dropdown-menu').removeClass('show');
        }
    });
    
    // Active menu highlighting
    var current = location.pathname.split('/').pop();
    if (current === '') current = 'dashboard';
    
    $('.navbar-nav li a').each(function() {
        var $this = $(this);
        var href = $this.attr('href');
        
        if (href && href !== '#' && href !== 'javascript:void(0)') {
            // Convert to relative URL for comparison
            var pathArray = href.split('/');
            var controller = pathArray[pathArray.length - 1];
            
            if (controller === current) {
                $this.parent().addClass('active');
                $this.closest('.dropdown').addClass('active');
                return false;
            }
        }
    });
    
    // Toggle mobile submenu
    $('.navbar-nav .dropdown > a').on('click', function(e) {
        if ($(window).width() < 992) {
            e.preventDefault();
            $(this).siblings('.dropdown-menu').slideToggle(200);
        }
    });
    
    // Search functionality
    $('.btn-search').on('click', function() {
        var searchQuery = $('.search-box input').val().trim();
        if (searchQuery) {
            // Implement search functionality here
            console.log('Searching for:', searchQuery);
            // window.location.href = '<?php echo base_url(); ?>search?q=' + encodeURIComponent(searchQuery);
        }
    });
    
    // Handle search on enter key
    $('.search-box input').on('keypress', function(e) {
        if (e.which === 13) {
            $('.btn-search').click();
        }
    });
});

// Make dropdown menus work on hover for desktop
$(document).ready(function() {
    function toggleNavbarMethod() {
        if ($(window).width() > 991) {
            $('.navbar .dropdown').hover(function() {
                $(this).find('.dropdown-menu').first().stop(true, true).delay(100).slideDown();
            }, function() {
                $(this).find('.dropdown-menu').first().stop(true, true).delay(100).slideUp();
            });
            
            $('.navbar .dropdown > a').on('click', function(e) {
                if ($(this).next('.dropdown-menu').length) {
                    e.preventDefault();
                    $(this).next('.dropdown-menu').slideToggle(200);
                }
            });
        }
    }
    
    toggleNavbarMethod();
    $(window).resize(toggleNavbarMethod);
});
