(function () {
  const header = document.querySelector('.site-header.modern');
  const menuToggle = document.querySelector('.navbar-toggler');
  const mainNav = document.querySelector('#main-navigation');
  const navLinks = document.querySelectorAll('#main-navigation a');
  const cartCount = document.querySelector('.cart-count');
  const searchToggle = document.querySelector('.header-search-toggle');
  const searchOverlay = document.querySelector('#search-overlay');
  const searchClose = document.querySelector('.search-close');
  const searchInput = searchOverlay ? searchOverlay.querySelector('.search-input') : null;

  // Scroll optimizado
  let scrollTimeout;
  window.addEventListener('scroll', () => {
    if (scrollTimeout) return;
    scrollTimeout = setTimeout(() => {
      header.classList.toggle('scrolled', window.scrollY > 50);
      scrollTimeout = null;
    }, 100);
  });

  // Menú toggle
  if (menuToggle && mainNav) {
    menuToggle.addEventListener('click', () => {
      menuToggle.classList.toggle('active');
    });

    // Cerrar en móvil al hacer clic en un enlace
    navLinks.forEach(link => {
      link.addEventListener('click', () => {
        if (window.innerWidth < 992 && mainNav.classList.contains('show')) {
          menuToggle.click();
        }
      });
    });
  }

  // Animar contador de carrito
  if (cartCount) {
    const observer = new MutationObserver(() => {
      cartCount.classList.add('updated');
      setTimeout(() => cartCount.classList.remove('updated'), 500);
    });
    observer.observe(cartCount, { childList: true });
  }

  // Búsqueda con accesibilidad
  let lastFocus;
  if (searchToggle && searchOverlay) {
    searchToggle.addEventListener('click', () => {
      lastFocus = document.activeElement;
      searchOverlay.classList.add('active');
      if (searchInput) searchInput.focus();
    });
  }
  if (searchClose && searchOverlay) {
    searchClose.addEventListener('click', () => {
      searchOverlay.classList.remove('active');
      if (lastFocus) lastFocus.focus();
    });
  }
})();
