/**
 * Modern Header Functionality
 * Fully Responsive Header with Mobile Menu
 */

(function() {
  'use strict';

  // Initialize header when DOM is ready or immediately if already loaded
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
      initHeader();
    });
  } else {
    // DOM already loaded
    initHeader();
  }

  function initHeader() {
    // Sticky Header
    initStickyHeader();
    
    // Mobile Menu
    initMobileMenu();
    
    // Search Functionality
    initSearch();
    
    // Dropdown Menus
    initDropdownMenus();
    
    // Close menus on outside click
    initCloseOnOutsideClick();
    
    // Smooth scroll for anchor links
    initSmoothScroll();
  }

  /**
   * Sticky Header on Scroll
   */
  function initStickyHeader() {
    const header = document.querySelector('.header-new');
    if (!header) return;

    let lastScroll = 0;
    const scrollThreshold = 100;

    window.addEventListener('scroll', function() {
      const currentScroll = window.pageYOffset;

      if (currentScroll > scrollThreshold) {
        header.classList.add('sticky');
      } else {
        header.classList.remove('sticky');
      }

      lastScroll = currentScroll;
    });
  }

  /**
   * Mobile Menu Toggle
   */
  function initMobileMenu() {
    const mobileMenuBtn = document.querySelector('.header-mobile-menu-btn');
    const mobileMenu = document.querySelector('.header-mobile-menu');
    const overlay = document.querySelector('.header-overlay');
    const body = document.body;

    if (!mobileMenuBtn || !mobileMenu) return;

    // Toggle mobile menu
    mobileMenuBtn.addEventListener('click', function(e) {
      e.preventDefault();
      e.stopPropagation();
      
      const isActive = mobileMenuBtn.classList.contains('active');
      
      if (isActive) {
        closeMobileMenu();
      } else {
        openMobileMenu();
      }
    });

    // Close menu when overlay is clicked
    if (overlay) {
      overlay.addEventListener('click', function() {
        closeMobileMenu();
      });
    }

    // Close menu on escape key
    document.addEventListener('keydown', function(e) {
      if (e.key === 'Escape' && mobileMenu.classList.contains('active')) {
        closeMobileMenu();
      }
    });

    // Mobile submenu toggle - Improved with better selectors
    function initMobileSubmenus() {
      if (!mobileMenu) return;
      
      // Use more flexible selector - find all menu items with submenus
      const menuItems = mobileMenu.querySelectorAll('li.has-submenu');
      
      if (menuItems.length === 0) {
        return;
      }
      
      menuItems.forEach(function(menuItem) {
        // Get the anchor tag (first child)
        const menuLink = menuItem.firstElementChild;
        if (!menuLink || menuLink.tagName !== 'A') return;
        
        // Check if listener already attached
        if (menuLink.hasAttribute('data-submenu-initialized')) {
          return;
        }
        
        menuLink.setAttribute('data-submenu-initialized', 'true');
        
        menuLink.addEventListener('click', function(e) {
          e.preventDefault();
          e.stopPropagation();
          
          const isActive = menuItem.classList.contains('active');
          
          // Close other submenus
          menuItems.forEach(function(item) {
            if (item !== menuItem) {
              item.classList.remove('active');
            }
          });
          
          // Toggle current submenu
          if (isActive) {
            menuItem.classList.remove('active');
          } else {
            menuItem.classList.add('active');
          }
        });
      });
    }
    
    // Initialize submenus immediately
    setTimeout(function() {
      initMobileSubmenus();
    }, 100);
    
    // Re-initialize when menu opens (in case of dynamic content)
    mobileMenuBtn.addEventListener('click', function() {
      setTimeout(function() {
        if (mobileMenu.classList.contains('active')) {
          initMobileSubmenus();
        }
      }, 150);
    });
    
    // Also initialize when menu becomes visible
    const observer = new MutationObserver(function(mutations) {
      if (mobileMenu.classList.contains('active')) {
        setTimeout(function() {
          initMobileSubmenus();
        }, 100);
      }
    });
    
    observer.observe(mobileMenu, {
      attributes: true,
      attributeFilter: ['class']
    });

    function openMobileMenu() {
      mobileMenuBtn.classList.add('active');
      mobileMenu.classList.add('active');
      if (overlay) overlay.classList.add('active');
      body.style.overflow = 'hidden';
    }

    function closeMobileMenu() {
      mobileMenuBtn.classList.remove('active');
      mobileMenu.classList.remove('active');
      if (overlay) overlay.classList.remove('active');
      body.style.overflow = '';
      
      // Close all submenus
      const allMenuItems = mobileMenu.querySelectorAll('li.has-submenu');
      allMenuItems.forEach(function(li) {
        li.classList.remove('active');
      });
    }
  }

  /**
   * Search Functionality
   */
  function initSearch() {
    const searchBtn = document.querySelector('.header-search-btn');
    const searchContainer = document.querySelector('.header-search-container');
    const searchInput = document.querySelector('.header-search-input');
    const mobileSearchBtn = document.querySelector('.header-mobile-search-btn');
    const mobileSearchInput = document.querySelector('.header-mobile-search-input');

    // Desktop search toggle
    if (searchBtn && searchContainer) {
      searchBtn.addEventListener('click', function(e) {
        e.preventDefault();
        searchContainer.classList.toggle('active');
        
        if (searchContainer.classList.contains('active') && searchInput) {
          setTimeout(function() {
            searchInput.focus();
          }, 100);
        }
      });

      // Close search when clicking outside
      document.addEventListener('click', function(e) {
        if (!searchContainer.contains(e.target) && !searchBtn.contains(e.target)) {
          searchContainer.classList.remove('active');
        }
      });
    }

    // Mobile search
    if (mobileSearchBtn && mobileSearchInput) {
      mobileSearchBtn.addEventListener('click', function(e) {
        e.preventDefault();
        const searchQuery = mobileSearchInput.value.trim();
        if (searchQuery) {
          window.location.href = '/search?q=' + encodeURIComponent(searchQuery);
        }
      });

      mobileSearchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
          e.preventDefault();
          mobileSearchBtn.click();
        }
      });
    }

    // Desktop search on enter
    if (searchInput) {
      searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
          e.preventDefault();
          const searchQuery = this.value.trim();
          if (searchQuery) {
            window.location.href = '/search?q=' + encodeURIComponent(searchQuery);
          }
        }
      });
    }
  }

  /**
   * Dropdown Menu Hover Effects
   */
  function initDropdownMenus() {
    const navItems = document.querySelectorAll('.header-nav-menu > li.has-submenu');
    
    navItems.forEach(function(item) {
      const dropdown = item.querySelector('.header-dropdown, .header-mega-menu');
      if (!dropdown) return;

      let timeout;

      item.addEventListener('mouseenter', function() {
        clearTimeout(timeout);
        item.classList.add('active');
      });

      item.addEventListener('mouseleave', function() {
        timeout = setTimeout(function() {
          item.classList.remove('active');
        }, 200);
      });

      dropdown.addEventListener('mouseenter', function() {
        clearTimeout(timeout);
      });

      dropdown.addEventListener('mouseleave', function() {
        timeout = setTimeout(function() {
          item.classList.remove('active');
        }, 200);
      });
    });
  }

  /**
   * Close menus on outside click
   */
  function initCloseOnOutsideClick() {
    document.addEventListener('click', function(e) {
      const navItems = document.querySelectorAll('.header-nav-menu > li.has-submenu');
      
      navItems.forEach(function(item) {
        if (!item.contains(e.target)) {
          item.classList.remove('active');
        }
      });
    });
  }

  /**
   * Smooth Scroll for Anchor Links
   */
  function initSmoothScroll() {
    const anchorLinks = document.querySelectorAll('a[href^="#"]');
    
    anchorLinks.forEach(function(link) {
      link.addEventListener('click', function(e) {
        const href = this.getAttribute('href');
        if (href === '#' || href === '#!') return;
        
        const targetId = href.substring(1);
        const targetElement = document.getElementById(targetId);
        
        if (targetElement) {
          e.preventDefault();
          const headerHeight = document.querySelector('.header-new')?.offsetHeight || 80;
          const targetPosition = targetElement.getBoundingClientRect().top + window.pageYOffset - headerHeight;
          
          window.scrollTo({
            top: targetPosition,
            behavior: 'smooth'
          });
          
          // Close mobile menu if open
          const mobileMenu = document.querySelector('.header-mobile-menu');
          if (mobileMenu && mobileMenu.classList.contains('active')) {
            document.querySelector('.header-mobile-menu-btn')?.click();
          }
        }
      });
    });
  }

  // Export functions for external use
  window.HeaderNew = {
    closeMobileMenu: function() {
      const mobileMenuBtn = document.querySelector('.header-mobile-menu-btn');
      const mobileMenu = document.querySelector('.header-mobile-menu');
      const overlay = document.querySelector('.header-overlay');
      
      if (mobileMenuBtn) mobileMenuBtn.classList.remove('active');
      if (mobileMenu) mobileMenu.classList.remove('active');
      if (overlay) overlay.classList.remove('active');
      document.body.style.overflow = '';
    }
  };

})();

