/**
 * HVAC Navigation - Robust & Simple
 * Ensures navigation dropdowns work reliably for all users
 * 
 * @version 1.0.1
 * @since 2025-08-21
 */

// CRITICAL: Disable the original menu system IMMEDIATELY to prevent conflicts
// This must be set OUTSIDE of jQuery ready to ensure it's available first
window.hvacRobustNavigationActive = true;

jQuery(document).ready(function($) {
    'use strict';
    
    
    // CRITICAL FIX: Ensure navigation runs AFTER dashboard scripts
    // Use a small delay to let dashboard scripts initialize first
    setTimeout(function() {
        initRobustNavigation();
    }, 100);
    
    // Ensure the menu system works even if other JavaScript fails
    function initRobustNavigation() {
        // Find all menu toggle elements
        const $menuToggles = $('.hvac-trainer-menu .menu-toggle');
        
        
        // AGGRESSIVE: Remove ALL competing handlers first
        $menuToggles.off(); // Remove all handlers
        $menuToggles.unbind(); // jQuery < 3.0 compatibility
        
        // Add click handlers to dropdown toggles
        $menuToggles.on('click.hvacRobust', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const $this = $(this);
            const $menuItem = $this.closest('.menu-item');
            const $submenu = $menuItem.find('> .sub-menu');
            
            
            // Close other open menus at the same level
            $this.closest('ul').find('> .menu-item.open').not($menuItem).removeClass('open');
            
            // Toggle this menu - FORCE the class change
            if ($menuItem.hasClass('open')) {
                $menuItem.removeClass('open');
                // Menu closed
            } else {
                $menuItem.addClass('open');
                // Menu opened
            }
            
            // State updated
        });
        
        // Ensure hamburger menu works
        const $hamburger = $('#hvac-hamburger-menu, .hvac-hamburger-menu');
        const $menu = $('#hvac-trainer-menu, .hvac-trainer-menu');
        
        if ($hamburger.length && $menu.length) {
            
            // CRITICAL: Aggressively remove all existing handlers to prevent conflicts
            // This ensures only our handler runs
            $hamburger.off(); // Remove ALL handlers
            $hamburger.unbind(); // jQuery < 3.0 compatibility
            $hamburger.removeClass('active'); // Reset state
            
            // Add only our handler with immediate effect
            $hamburger.on('click.hvacRobust', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                
                $hamburger.toggleClass('active');
                $menu.toggleClass('active');
                
                // Update aria attributes
                const isOpen = $menu.hasClass('active');
                $hamburger.attr('aria-expanded', isOpen);
                
                // Menu state updated
            });
            
            // AGGRESSIVE: Monitor and remove conflicting handlers continuously
            setInterval(function() {
                const events = $._data($hamburger[0], 'events');
                if (events && events.click && events.click.length > 1) {
                    // Remove conflicting handlers
                    // Keep only our namespaced handler
                    $hamburger.off('click');
                    $hamburger.on('click.hvacRobust', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        $hamburger.toggleClass('active');
                        $menu.toggleClass('active');
                        const isOpen = $menu.hasClass('active');
                        $hamburger.attr('aria-expanded', isOpen);
                        // Menu state updated
                    });
                }
            }, 1000);
        }
        
        // Close menu when clicking outside (on mobile)
        $(document).off('click.hvacRobustOutside').on('click.hvacRobustOutside', function(e) {
            if (!$(e.target).closest('.hvac-trainer-nav').length) {
                if (window.innerWidth <= 992) {
                    $menu.removeClass('active');
                    $hamburger.removeClass('active');
                    $hamburger.attr('aria-expanded', 'false');
                }
                
                // Close all open dropdowns
                $('.hvac-trainer-menu .menu-item.open').removeClass('open');
            }
        });
        
        // Handle window resize
        $(window).off('resize.hvacRobust').on('resize.hvacRobust', function() {
            if (window.innerWidth > 992) {
                // Reset mobile menu state on desktop
                $menu.removeClass('active');
                $hamburger.removeClass('active');
                $hamburger.attr('aria-expanded', 'false');
            }
        });
        
        // Navigation initialized
    }
    
    // Removed immediate initialization - now handled by setTimeout above
    
    // Reinitialize after AJAX or dynamic content changes
    $(document).on('hvac-content-updated', initRobustNavigation);
    
    // CRITICAL: Also reinitialize when dashboard AJAX completes
    $(document).ajaxComplete(function(event, xhr, settings) {
        // Check if this was a dashboard AJAX request
        if (settings && settings.data && settings.data.indexOf('hvac_filter_events') > -1) {
            // Dashboard AJAX completed, reinitializing navigation
            setTimeout(initRobustNavigation, 100);
        }
    });
    
    // Fallback initialization after a delay
    setTimeout(function() {
        // Check if dropdowns are working
        const $firstToggle = $('.hvac-trainer-menu .menu-toggle').first();
        if ($firstToggle.length) {
            // Simulate a click to test functionality
            const events = $._data($firstToggle[0], 'events');
            if (!events || !events.click || events.click.length === 0) {
                // No click handlers found, reinitializing
                initRobustNavigation();
            }
        }
    }, 1000);
    
    // Extra safety net - ensure menu visibility
    function ensureMenuVisibility() {
        const $activeMenu = $('.hvac-trainer-menu.active');
        if ($activeMenu.length && $activeMenu.is(':hidden')) {
            $activeMenu.css({
                'display': 'block',
                'visibility': 'visible',
                'opacity': '1'
            });
        }
    }
    
    // Check menu visibility periodically
    setInterval(ensureMenuVisibility, 2000);
});