// custom-hover.js
// Enable hover-to-open for Bootstrap 5 dropdowns on desktop (>=992px), keep click on mobile
jQuery(function($){
  'use strict';

  function enableHoverDropdowns(){
    var desktop = $(window).width() >= 992;

    // remove any previous custom handlers
    $('.navbar .nav-item.dropdown').off('.hoverDrop');

    if(!desktop) return; // nothing to do on small screens

    $('.navbar .nav-item.dropdown').on('mouseenter.hoverDrop', function(){
      var $toggle = $(this).find('.dropdown-toggle').first();
      if(!$toggle.length) return;
      var trigger = $toggle.get(0);
      // Bootstrap 5 Dropdown instance
      var dropdown = bootstrap.Dropdown.getOrCreateInstance(trigger);
      dropdown.show();
    });

    $('.navbar .nav-item.dropdown').on('mouseleave.hoverDrop', function(){
      var $toggle = $(this).find('.dropdown-toggle').first();
      if(!$toggle.length) return;
      var trigger = $toggle.get(0);
      var dropdown = bootstrap.Dropdown.getOrCreateInstance(trigger);
      dropdown.hide();
    });
  }

  // Init and re-init on resize (debounced)
  var resizeTimer;
  enableHoverDropdowns();
  $(window).on('resize', function(){
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(enableHoverDropdowns, 150);
  });
});
