/**
 * FRESH — Mega Menu
 * Category switching + hover open/close with delay.
 */
(function () {
  'use strict';

  function initMegaMenu() {
    var menus = document.querySelectorAll('.mega-menu');
    if (!menus.length) return;

    menus.forEach(function (menu) {
      var cats = menu.querySelectorAll('.mega-cat');
      var grids = menu.querySelectorAll('.mega-svc-grid');
      if (!cats.length || !grids.length) return;

      function activate(index) {
        cats.forEach(function (c, i) {
          c.classList.toggle('active', i === index);
        });
        grids.forEach(function (g, i) {
          g.classList.toggle('active', i === index);
        });
      }

      // Hover on desktop — switch categories
      cats.forEach(function (cat, index) {
        cat.addEventListener('mouseenter', function () {
          if (window.innerWidth > 1024) {
            activate(index);
          }
        });
        cat.addEventListener('click', function (e) {
          e.preventDefault();
          activate(index);
        });
      });

      // Activate first category by default
      activate(0);
    });

    /* ========== Hover open/close with 300ms delay ========== */
    document.querySelectorAll('.nav-links > li.has-mega').forEach(function (li) {
      var closeTimer = null;
      var megaEl = li.querySelector('.mega-menu');
      if (!megaEl) return;

      function openMenu() {
        clearTimeout(closeTimer);
        // Position dropdown just below the nav bar
        var nav = document.querySelector('.nav');
        if (nav && megaEl) {
          megaEl.style.top = nav.offsetHeight + 'px';
        }
        li.classList.add('mega-open');
      }

      function scheduleClose() {
        clearTimeout(closeTimer);
        closeTimer = setTimeout(function () {
          li.classList.remove('mega-open');
        }, 300);
      }

      // Desktop only — open on mouseenter, close with delay on mouseleave
      li.addEventListener('mouseenter', function () {
        if (window.innerWidth > 1024) openMenu();
      });

      li.addEventListener('mouseleave', function () {
        if (window.innerWidth > 1024) scheduleClose();
      });

      // Also keep open when hovering the dropdown itself
      megaEl.addEventListener('mouseenter', function () {
        if (window.innerWidth > 1024) openMenu();
      });

      megaEl.addEventListener('mouseleave', function () {
        if (window.innerWidth > 1024) scheduleClose();
      });
    });
  }

  // Run on DOM ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initMegaMenu);
  } else {
    initMegaMenu();
  }
})();
