

//   (function ($) {
//   'use strict';

//   // =============================
//   // Part 0: Setup and shared utilities
//   // =============================
// window.initHorizontalMenu = function () {
//   // Constants
//   const MOBILE_MAX = 767;

//   // Root elements (cache once)
//   const $menu     = $('.inail-horizontal-menu');
//   const $collapse = $menu.find('#inail-hm-main-navbar');
//   const $toggleBtn = $menu.find('.navbar-toggle[data-target="#inail-hm-main-navbar"]');
//   const $menuTitle = $menu.find('.inail-mobile-menu-title');

//   // State
//   let panelUid = 0;
//   let panelsCreated = false;
//   let menuStack = [];
//   let lastMode = null;

//   // Mode helpers
//   function isDesktop() {
//     return window.innerWidth >= (MOBILE_MAX + 1);
//   }

//   // Focus helpers (shared)
//   function focusFirst($container) {
//     const $first = $container.find('a:visible, button:visible').first();
//     if ($first.length) $first[0].focus();
//   }
//   function focusLast($container) {
//     const $last = $container.find('> li:visible > a, > li:visible > button').last();
//     if ($last.length) $last[0].focus();
//   }

//   // Single source of truth for menu label/state
//   function setMenuState(isOpen) {
//     if (isOpen) {
//       $toggleBtn
//         .attr({ 'aria-expanded': 'true', 'aria-label': 'Chiudi il menu' })
//         .removeClass('collapsed');
//       $menuTitle.text('Chiudi');
//     } else {
//       $toggleBtn
//         .attr({ 'aria-expanded': 'false', 'aria-label': 'Apri il menu' })
//         .addClass('collapsed');
//       $menuTitle.text('Menù');
//     }
//   }

//   // Force-close Bootstrap collapse instantly (no animation)
//   function closeCollapseInstant() {
//     $collapse
//       .stop(true, true)
//       .removeClass('in collapsing')
//       .addClass('collapse')
//       .css({ height: '', display: '' })
//       .attr('aria-expanded', 'false')
//       .trigger('hidden.bs.collapse'); // keep listeners in sync
//     setMenuState(false);
//   }

//   // Safety net: keep label in sync when Bootstrap fires events (e.g., if used elsewhere)
//   $collapse
//     .on('shown.bs.collapse.safety', function () { setMenuState(true); })
//     .on('hidden.bs.collapse.safety', function () { setMenuState(false); });

// // =============================
// // Part 1: Class helpers (desktop)
// // =============================

// function showMenu($menuEl, { focus = false, markParent = null } = {}) {
//   if (!isDesktop()) return;

//   $menuEl
//     .css('display', 'block')
//     .attr('aria-hidden', 'false')
//     .find('a,button').attr('tabindex', '-1');

//   const $toggle = (markParent && markParent.length)
//     ? markParent
//     : $menuEl.siblings('button').first();

//   if ($toggle && $toggle.length) {
//     $toggle.attr('aria-expanded', 'true');
//     $toggle.closest('li').addClass('inail-hm-active-parent');
//   }

//   if (focus) focusFirst($menuEl);
// }

// function hideMenu($menuEl, { clearParent = null } = {}) {
//   if (!isDesktop()) return;

//   $menuEl
//     .css('display', 'none')
//     .attr('aria-hidden', 'true')
//     .find('a,button').attr('tabindex', '-1');

//   const $toggle = (clearParent && clearParent.length)
//     ? clearParent
//     : $menuEl.siblings('button').first();

//   if ($toggle && $toggle.length) {
//     $toggle.attr('aria-expanded', 'false');
//     $toggle.closest('li').removeClass('inail-hm-active-parent');
//   }
// }

// function adjustSubmenuDirection() {
//   if (!isDesktop()) return;

//   $menu.find('.dropdown-submenu').each(function () {
//     const $li = $(this);
//     $li.removeClass('inail-hm-open-left');

//     const $submenu = $li.children('.dropdown-menu');
//     if (!$submenu.length) return;

//     const viewportWidth = $(window).width();
//     const parentRight = $li.offset().left + $li.outerWidth();
//     if (parentRight + $submenu.outerWidth() > viewportWidth) {
//       $li.addClass('inail-hm-open-left');
//     }
//   });
// }



//    // =============================
// // Part 2: Desktop code
// // =============================

// // Level 0 toggle
// $menu.on('click.desktop', '.dropdown-toggle.inail-hm-nav-link-btn', function (e) {
//   if (!isDesktop()) return;
//   e.preventDefault();

//   const $btn = $(this);
//   const $thisDropdown = $btn.closest('.dropdown');
//   const $menuEl = $btn.siblings('.dropdown-menu');

//   // Close other Level 0 dropdowns
//   $menu.find('.dropdown').not($thisDropdown).each(function () {
//     hideMenu($(this).children('.dropdown-menu'), {
//       clearParent: $(this).find('> .dropdown-toggle.inail-hm-nav-link-btn')
//     });
//   });

//   if ($menuEl.is(':visible')) {
//     hideMenu($menuEl, { clearParent: $btn });
//   } else {
//     // Close nested submenus inside before opening
//     $menuEl.find('.dropdown-menu').each(function () { hideMenu($(this)); });
//     $menuEl.find('.inail-hm-active-parent').removeClass('inail-hm-active-parent');
//     showMenu($menuEl, { focus: true, markParent: $btn });
//   }

//   adjustSubmenuDirection();
// });

// // Submenu toggle
// $menu.on('click.desktop', '.dropdown-submenu > .inail-hm-submenu', function (e) {
//   if (!isDesktop()) return;
//   e.preventDefault();
//   e.stopPropagation();

//   const $btn = $(this);
//   const $submenu = $btn.siblings('.dropdown-menu');

//   // Close sibling submenus
//   $btn.parent().siblings('.dropdown-submenu').each(function () {
//     hideMenu($(this).children('.dropdown-menu'), {
//       clearParent: $(this).children('button.inail-hm-submenu')
//     });
//   });

//   if ($submenu.is(':visible')) hideMenu($submenu, { clearParent: $btn });
//   else showMenu($submenu, { focus: true, markParent: $btn });

//   adjustSubmenuDirection();
// });

// // Keyboard navigation (desktop)
// $menu.on('keydown.desktop', '.dropdown-menu a, .dropdown-menu button', function (e) {
//   if (!isDesktop()) return;

//   const $current = $(this);
//   const $ul = $current.closest('ul');
//   const $items = $ul.find('> li:visible > a, > li:visible > button');
//   const idx = $items.index(this);
//   const len = $items.length;

//   switch (e.key) {
//     case 'ArrowDown':
//       e.preventDefault();
//       $items.eq((idx + 1) % len).focus();
//       break;

//     case 'ArrowUp':
//       e.preventDefault();
//       $items.eq((idx - 1 + len) % len).focus();
//       break;

//     case 'ArrowRight': {
//       e.preventDefault();
//       const $submenu = $current.parent('.dropdown-submenu').children('.dropdown-menu');
//       if ($submenu.length) {
//         showMenu($submenu, { focus: true, markParent: $current });
//         adjustSubmenuDirection();
//       }
//       break;
//     }

//     case 'ArrowLeft': {
//       e.preventDefault();
//       const $parentLi = $current.closest('.dropdown-menu').parent('.dropdown-submenu');
//       if ($parentLi.length) {
//         const $currentMenu = $current.closest('.dropdown-menu');
//         hideMenu($currentMenu, { clearParent: $parentLi.children('button.inail-hm-submenu') });
//         $parentLi.children('button.inail-hm-submenu').focus();
//       }
//       break;
//     }

//     case 'Escape': {
//       e.preventDefault();
//       const $menuToClose = $current.closest('.dropdown-menu');
//       hideMenu($menuToClose);
//       $menuToClose.find('.inail-hm-active-parent').removeClass('inail-hm-active-parent');

//       const $parentLi = $menuToClose.parent('.dropdown-submenu, .dropdown');
//       if ($parentLi.hasClass('dropdown')) {
//         $parentLi.find('> .dropdown-toggle.inail-hm-nav-link-btn').focus();
//       } else if ($parentLi.hasClass('dropdown-submenu')) {
//         $parentLi.children('button.inail-hm-submenu').focus();
//       }
//       break;
//     }

//     case 'Enter':
//     case ' ': {
//       if ($current.is('a')) {
//         e.preventDefault();
//         const $rootDropdown = $current.closest('.dropdown');
//         $rootDropdown.find('.dropdown-menu').each(function () { hideMenu($(this)); });
//         $rootDropdown.find('.inail-hm-active-parent').removeClass('inail-hm-active-parent');
//         $rootDropdown.find('> .dropdown-toggle.inail-hm-nav-link-btn').focus();
//       }
//       break;
//     }

//     case 'Tab': {
//       const $rootDropdown = $current.closest('.dropdown');
//       $rootDropdown.find('.dropdown-menu').each(function () { hideMenu($(this)); });
//       $rootDropdown.find('.inail-hm-active-parent').removeClass('inail-hm-active-parent');
//       $rootDropdown.find('> .dropdown-toggle.inail-hm-nav-link-btn').attr('aria-expanded', 'false');
//       break;
//     }
//   }
// });

// // Click on any link inside dropdowns (desktop)
// $menu.on('click.desktop', '.dropdown-menu a', function () {
//   if (!isDesktop()) return;
//   const $root = $(this).closest('.dropdown');
//   $root.find('.dropdown-menu').each(function () { hideMenu($(this)); });
//   $root.find('.inail-hm-active-parent').removeClass('inail-hm-active-parent');
//   $root.find('> .dropdown-toggle.inail-hm-nav-link-btn').focus();
// });

// // Init ARIA for desktop menus
// $menu.find('.dropdown-toggle.inail-hm-nav-link-btn, .dropdown-submenu > .inail-hm-submenu').attr({
//   'aria-haspopup': 'true',
//   'aria-expanded': 'false'
// });
// $menu.find('.dropdown-menu').each(function () {
//   $(this)
//     .attr('aria-hidden', 'true')
//     .css('display', 'none')
//     .find('a,button').attr('tabindex', '-1');
// });

// // Outside click (desktop only)
// $(document).on('click.desktopOutside', function (e) {
//   if (!isDesktop()) return;
//   if (!$menu.is(e.target) && $menu.has(e.target).length === 0) {
//     $menu.find('.dropdown-menu').each(function () { hideMenu($(this)); });
//     $menu.find('.dropdown-submenu > .inail-hm-submenu').removeClass('inail-hm-active-parent');
//     $menu.find('.dropdown-toggle.inail-hm-nav-link-btn').attr('aria-expanded', 'false');
//   }
// });

// // Keep submenu directions updated on resize (desktop)
// $(window).on('resize.desktopDir', adjustSubmenuDirection);


//   // =============================
// // Part 3: Mobile helpers
// // =============================

// function createPanelForMenu($btn, $menuList) {
//   // coerce to jQuery to be safe
//   $btn = $($btn);
//   $menuList = $($menuList);

//   if (!$menuList.length || !$btn.length) return null;

//   const panelId = 'inail-hm-mobile-panel-' + (++panelUid);
//   $btn.attr('data-mobile-target', panelId);
//   if ($('#' + panelId).length) return panelId;

//   const $panel = $('<div>', { class: 'inail-hm-menu-panel', id: panelId })
//     .data('title', $btn.text().trim());

//   const $header = $('<div>', { class: 'inail-hm-menu-header' }).append(
//     $('<button>', {
//       class: 'inail-hm-back-btn',
//       type: 'button',
//       style: 'visibility:hidden',
//       'aria-expanded': 'true',
//       'aria-label': 'Vai al livello precedente'
//     })
//       .append($('<span>', { 'aria-hidden': 'true', class: 'fa-solid fa-chevron-left' }))
//       .append($('<span>', { class: 'inail-hm-back-text' }).text($btn.text().trim()))
//   );

//   $panel.append($header);

//   const $list = $('<ul>');
//   $menuList.children('li').each(function () {
//     const $li = $(this);

//     if ($li.hasClass('dropdown-submenu')) {
//       const $origSubBtn = $li.children('button.inail-hm-submenu').first();
//       const $nestedMenu = $li.children('.dropdown-menu').first();

//       // Build the opener button
//       const $openBtn = $('<button>', {
//         type: 'button',
//         class: 'inail-hm-open-mobile-submenu',
//         'aria-haspopup': 'true',
//         'aria-expanded': 'false'
//       })
//         .append($('<span>').text($origSubBtn.text().trim()))
//         .append($('<i>', { class: 'fa fa-chevron-right', 'aria-hidden': 'true' }));

//       // Store references as jQuery data, not HTML attributes
//       $openBtn
//         .data('submenuEl', $nestedMenu)
//         .data('submenuBtn', $origSubBtn);

//       $list.append($('<li>').append($openBtn));
//     } else {
//       const $childEl = $li.children('a,button').first();
//       if ($childEl.length) {
//         const $link = $('<a>', {
//           href: $childEl.is('a') ? $childEl.attr('href') : '#',
//           class: 'inail-hm-menu-link'
//         }).append($('<span>').text($childEl.text().trim()));
//         $list.append($('<li>').append($link));
//       }
//     }
//   });

//   $panel.append($list);
//   $collapse.append($panel);
//   return panelId;
// }

// function openPanel(id, opener) {
//   $menu.find('.inail-hm-menu-panel').removeClass('active');
//   const $panel = $('#' + id).addClass('active');
//   if (opener && opener.length) {
//     $panel.data('opener', opener);
//   }
//   updatePanelHeaders();
// }

// function updatePanelHeaders() {
//   const top = menuStack.length ? menuStack[menuStack.length - 1] : null;
//   $menu.find('.inail-hm-menu-panel').each(function () {
//     const $p = $(this);
//     $p.find('.inail-hm-title').text($p.data('title') || '');
//     const visibleBack = ($p.attr('id') === top && menuStack.length > 0);
//     $p.find('.inail-hm-back-btn').css('visibility', visibleBack ? 'visible' : 'hidden');
//   });
// }

// function focusFirstInPanel(id) {
//   const $panel = $('#' + id);
//   const $backBtn = $panel.find('.inail-hm-menu-header .inail-hm-back-btn:visible');
//   if ($backBtn.length) {
//     $backBtn.focus();
//   } else {
//     const $firstItem = $panel.find('a,button').first();
//     if ($firstItem.length) $firstItem.focus();
//   }
// }


//   // =============================
// // Part 4: Mobile code
// // =============================

// function initMobilePanels() {
//   if (panelsCreated) return;
//   panelsCreated = true;
//   panelUid = 0;
//   menuStack = [];

//   // Build panels for each top-level dropdown
//   $menu.find('.dropdown').each(function () {
//     const $toggle = $(this).find('> .dropdown-toggle.inail-hm-nav-link-btn').first();
//     const $ul = $(this).find('> .dropdown-menu').first();
//     if ($toggle.length && $ul.length) createPanelForMenu($toggle, $ul);
//   });

//   // Level 0 → Level 1
//   $menu.on('click.mobile', '.dropdown-toggle.inail-hm-nav-link-btn', function (e) {
//     if (isDesktop()) return;
//     e.preventDefault();
//     e.stopPropagation();

//     const target = $(this).data('mobile-target');
//     if (!target) return;

//     $collapse.data('last-root-trigger', $(this));
//     menuStack.push(target);
//     openPanel(target, $(this));
//     focusFirstInPanel(target);
//   });

//   // Level 1 → Level 2
//   $menu.on('click.mobile', '.inail-hm-open-mobile-submenu', function (e) {
//     if (isDesktop()) return;
//     e.preventDefault();
//     e.stopPropagation();

//     let target = $(this).data('target-panel');

//     // If panel doesn't exist yet, create it now from stored references
//     if (!target || !$('#' + target).length) {
//       // read from jQuery's data store (not attributes)
//       let $submenuEl = $(this).data('submenuEl');
//       let $submenuBtn = $(this).data('submenuBtn');

//       // coerce to jQuery in case a DOM node was stored
//       $submenuEl = $($submenuEl);
//       $submenuBtn = $($submenuBtn);

//       if ($submenuEl.length && $submenuBtn.length) {
//         target = createPanelForMenu($submenuBtn, $submenuEl);
//         $(this).attr('data-target-panel', target);
//       } else {
//         return; // nothing to open
//       }
//     }

//     menuStack.push(target);
//     openPanel(target, $(this));
//     focusFirstInPanel(target);
//   });

//   // Back button
//   $menu.on('click.mobile', '.inail-hm-menu-header .inail-hm-back-btn', function (e) {
//     if (isDesktop()) return;
//     e.preventDefault();
//     e.stopPropagation();

//     if (menuStack.length <= 1) {
//       menuStack = [];
//       $menu.find('.inail-hm-menu-panel').removeClass('active inail-hm-previous');
//       $('#inail-hm-mobile-panel-root').addClass('active');

//       const $rootTrigger = $collapse.data('last-root-trigger');
//       if ($rootTrigger && $rootTrigger.length) $rootTrigger.focus();
//     } else {
//       const currentPanelId = menuStack.pop();
//       const prevPanelId = menuStack[menuStack.length - 1];
//       openPanel(prevPanelId);

//       const $opener = $('#' + currentPanelId).data('opener');
//       if ($opener && $opener.length) $opener.focus();
//       else focusFirstInPanel(prevPanelId);
//     }
//   });

//   // Clicking ANY link (not submenu trigger) → back to Level 0 and close instantly
//   $menu.on('click.mobile', 'a:not(.inail-hm-open-mobile-submenu)', function (e) {
//     if (isDesktop()) return;

//     e.preventDefault();
//     e.stopPropagation();

//     const $currentPanel = $(this).closest('.inail-hm-menu-panel');
//     const isRootPanel = $currentPanel.attr('id') === 'inail-hm-mobile-panel-root';

//     let $opener = null;
//     if (!isRootPanel) {
//       $opener = $currentPanel.data('opener');
//     }

//     // Reset panels
//     menuStack = [];
//     $menu.find('.inail-hm-menu-panel').removeClass('active inail-hm-previous');
//     $('#inail-hm-mobile-panel-root').addClass('active');

//     // Close instantly
//     closeCollapseInstant();

//     // Return focus to opener if coming from a child panel
//     if ($opener && $opener.length) $opener.focus();
//   });

//   // Reset when collapse hides
//   $collapse.on('hide.bs.collapse.mobile', function () {
//     menuStack = [];
//     $menu.find('.inail-hm-menu-panel').removeClass('active inail-hm-previous');
//     $('#inail-hm-mobile-panel-root').addClass('active');
//   });

//   // Keyboard navigation (mobile): only Esc, Enter, Space, Tab
//   $menu.on('keydown.mobile', '.inail-hm-menu-panel.active a, .inail-hm-menu-panel.active button', function (e) {
//     if (isDesktop()) return;

//     const $current = $(this);

//     switch (e.key) {
//       case 'Escape':
//         e.preventDefault();
//         if (menuStack.length > 0) {
//           // Go back one level
//           $('.inail-hm-menu-header .inail-hm-back-btn:visible').trigger('click');
//         } else {
//           // At root → close instantly
//           closeCollapseInstant();
//         }
//         break;

//       case 'Enter':
//       case ' ':
//         if ($current.is('a') && !$current.hasClass('inail-hm-open-mobile-submenu')) {
//           // Normal link → close instantly
//           e.preventDefault();
//           menuStack = [];
//           $menu.find('.inail-hm-menu-panel').removeClass('active inail-hm-previous');
//           $('#inail-hm-mobile-panel-root').addClass('active');
//           closeCollapseInstant();
//         } else if ($current.hasClass('inail-hm-open-mobile-submenu')) {
//           // Submenu opener → go deeper
//           e.preventDefault();

//           let target = $current.data('target-panel');

//           // Lazy-create if needed
//           if (!target || !$('#' + target).length) {
//             let $submenuEl = $current.data('submenuEl');
//             let $submenuBtn = $current.data('submenuBtn');

//             $submenuEl = $($submenuEl);
//             $submenuBtn = $($submenuBtn);

//             if ($submenuEl.length && $submenuBtn.length) {
//               target = createPanelForMenu($submenuBtn, $submenuEl);
//               $current.attr('data-target-panel', target);
//             } else {
//               return; // nothing to open
//             }
//           }

//           menuStack.push(target);
//           openPanel(target, $current);
//           focusFirstInPanel(target);
//         }
//         break;

//       case 'Tab':
//         // Allow natural tabbing
//         break;

//       default:
//         // Ignore all other keys in mobile mode
//         break;
//     }
//   });

//   // Toggle button: update label instantly on intent
//   $toggleBtn.on('click.mobileToggle', function () {
//     const willOpen = !$collapse.hasClass('in');
//     setMenuState(willOpen);
//   });
// }

// function destroyMobilePanels() {
//   if (!panelsCreated) return;
//   panelsCreated = false;
//   menuStack = [];

//   // Remove dynamically created panels but keep root
//   $menu.find('.inail-hm-menu-panel').not('#inail-hm-mobile-panel-root').remove();

//   // Reset root panel so it's visible in desktop
//   $('#inail-hm-mobile-panel-root')
//     .removeClass('inail-hm-previous')
//     .addClass('active')
//     .css('display', '');

//   $menu.find('[data-mobile-target]').removeAttr('data-mobile-target');

//   // Remove mobile-bound events
//   $menu.off('.mobile');
//   $toggleBtn.off('.mobileToggle');
//   $collapse.off('.mobile');
// }


//   // =============================
// // Part 5: Switcher — init/destroy on resize
// // =============================

// function closeAllDesktopMenus() {
//   // Force-hide all dropdown menus regardless of current mode
//   $menu.find('.dropdown-menu').each(function () {
//     const $dm = $(this);
//     $dm.css('display', 'none')
//        .attr('aria-hidden', 'true')
//        .find('a,button').attr('tabindex', '-1');

//     // Reset its controlling toggle (sibling button or parent submenu btn)
//     const $toggle = $dm.siblings('button.inail-hm-submenu, .dropdown-toggle.inail-hm-nav-link-btn').first();
//     if ($toggle.length) $toggle.attr('aria-expanded', 'false');

//     // Remove open/show classes used by Bootstrap 3/4/5
//     $dm.removeClass('open show');
//     $dm.parent('.dropdown, .dropdown-submenu').removeClass('open show');
//   });

//   // Remove active marker classes
//   $menu.find('.inail-hm-active-parent').removeClass('inail-hm-active-parent');

//   // Reset all toggles’ aria
//   $menu
//     .find('.dropdown-toggle.inail-hm-nav-link-btn, .dropdown-submenu > .inail-hm-submenu')
//     .attr('aria-expanded', 'false')
//     .removeClass('open show active');

//   // Clear any container classes
//   $menu.find('.dropdown, .dropdown-submenu').removeClass('open show');
// }

// function resetNavbarToggle() {
//   if (isDesktop()) {
//     // Desktop: always closed
//     $collapse.removeClass('in').attr('aria-expanded', 'false').css('height', '');
//     setMenuState(false);
//   } else {
//     // Mobile: mirror current collapse state
//     setMenuState($collapse.hasClass('in'));
//   }
// }

// function handleResizeInit() {
//   const mode = isDesktop() ? 'desktop' : 'mobile';

//   if (mode !== lastMode) {
//     if (mode === 'desktop') {
//       // Leaving mobile → desktop
//       destroyMobilePanels();
//       resetNavbarToggle();

//       // Ensure collapse is closed
//       $collapse.removeClass('in').attr('aria-expanded', 'false').css('height', '');

//       // Reset panels to root
//       menuStack = [];
//       $menu.find('.inail-hm-menu-panel').removeClass('active inail-hm-previous');
//       $('#inail-hm-mobile-panel-root').addClass('active');
//     } else {
//       // Leaving desktop → mobile
//       closeAllDesktopMenus();
//       resetNavbarToggle();

//       // Reset mobile state before init
//       menuStack = [];
//       $menu.find('.inail-hm-menu-panel').removeClass('active inail-hm-previous');
//       $('#inail-hm-mobile-panel-root').addClass('active');

//       initMobilePanels();
//     }
//     lastMode = mode;
//   }
// }

// // Initial sync
// $(document).ready(function () {
//   resetNavbarToggle();
//   handleResizeInit();
// });

// // On resize
// $(window).on('resize.menuSwitch', function () {
//   resetNavbarToggle();
//   handleResizeInit();
// });
// };


// function watchForMenu() {
//   const observer = new MutationObserver(() => {
//     $('.inail-horizontal-menu').each(function () {
//       const $menu = $(this);
//       if (!$menu.data('hm-init')) {
//         $menu.data('hm-init', true);
//         window.initHorizontalMenu($menu);
//       }
//     });
//   });

//   observer.observe(document.body, { childList: true, subtree: true });
// }

//   if (document.readyState === 'interactive' || document.readyState === 'complete') {
//     watchForMenu();
//   } else {
//     $(document).ready(watchForMenu);
//   }


// })(jQuery);




function initHorizontalMenu() {
  (function ($) {
  'use strict';

  // =============================
  // Part 0: Setup and shared utilities
  // =============================

  // Constants
  const MOBILE_MAX = 767;

  // Root elements (cache once)
  const $menu     = $('.inail-horizontal-menu');
  const $collapse = $menu.find('#inail-hm-main-navbar');
  const $toggleBtn = $menu.find('.navbar-toggle[data-target="#inail-hm-main-navbar"]');
  const $menuTitle = $menu.find('.inail-mobile-menu-title');

  // State
  let panelUid = 0;
  let panelsCreated = false;
  let menuStack = [];
  let lastMode = null;

  // Mode helpers
  function isDesktop() {
    return window.innerWidth >= (MOBILE_MAX + 1);
  }

  // Focus helpers (shared)
  function focusFirst($container) {
    const $first = $container.find('a:visible, button:visible').first();
    if ($first.length) $first[0].focus();
  }
  function focusLast($container) {
    const $last = $container.find('> li:visible > a, > li:visible > button').last();
    if ($last.length) $last[0].focus();
  }

  // Single source of truth for menu label/state
  function setMenuState(isOpen) {
    if (isOpen) {
      $toggleBtn
        .attr({ 'aria-expanded': 'true', 'aria-label': 'Chiudi il menu' })
        .removeClass('collapsed');
      $menuTitle.text('Chiudi');
    } else {
      $toggleBtn
        .attr({ 'aria-expanded': 'false', 'aria-label': 'Apri il menu' })
        .addClass('collapsed');
      $menuTitle.text('Menù');
    }
  }

  // Force-close Bootstrap collapse instantly (no animation)
  function closeCollapseInstant() {
    $collapse
      .stop(true, true)
      .removeClass('in collapsing')
      .addClass('collapse')
      .css({ height: '', display: '' })
      .attr('aria-expanded', 'false')
      .trigger('hidden.bs.collapse'); // keep listeners in sync
    setMenuState(false);
  }

  // Safety net: keep label in sync when Bootstrap fires events (e.g., if used elsewhere)
  $collapse
    .on('shown.bs.collapse.safety', function () { setMenuState(true); })
    .on('hidden.bs.collapse.safety', function () { setMenuState(false); });

// =============================
// Part 1: Class helpers (desktop)
// =============================

function showMenu($menuEl, { focus = false, markParent = null } = {}) {
  if (!isDesktop()) return;

  $menuEl
    .css('display', 'block')
    .attr('aria-hidden', 'false')
    .find('a,button').attr('tabindex', '-1');

  const $toggle = (markParent && markParent.length)
    ? markParent
    : $menuEl.siblings('button').first();

  if ($toggle && $toggle.length) {
    $toggle.attr('aria-expanded', 'true');
    $toggle.closest('li').addClass('inail-hm-active-parent');
  }

  if (focus) focusFirst($menuEl);
}

function hideMenu($menuEl, { clearParent = null } = {}) {
  if (!isDesktop()) return;

  $menuEl
    .css('display', 'none')
    .attr('aria-hidden', 'true')
    .find('a,button').attr('tabindex', '-1');

  const $toggle = (clearParent && clearParent.length)
    ? clearParent
    : $menuEl.siblings('button').first();

  if ($toggle && $toggle.length) {
    $toggle.attr('aria-expanded', 'false');
    $toggle.closest('li').removeClass('inail-hm-active-parent');
  }
}

function adjustSubmenuDirection() {
  if (!isDesktop()) return;

  $menu.find('.dropdown-submenu').each(function () {
    const $li = $(this);
    $li.removeClass('inail-hm-open-left');

    const $submenu = $li.children('.dropdown-menu');
    if (!$submenu.length) return;

    const viewportWidth = $(window).width();
    const parentRight = $li.offset().left + $li.outerWidth();
    if (parentRight + $submenu.outerWidth() > viewportWidth) {
      $li.addClass('inail-hm-open-left');
    }
  });
}



   // =============================
// Part 2: Desktop code
// =============================

// Level 0 toggle
$menu.on('click.desktop', '.dropdown-toggle.inail-hm-nav-link-btn', function (e) {
  if (!isDesktop()) return;
  e.preventDefault();

  const $btn = $(this);
  const $thisDropdown = $btn.closest('.dropdown');
  const $menuEl = $btn.siblings('.dropdown-menu');

  // Close other Level 0 dropdowns
  $menu.find('.dropdown').not($thisDropdown).each(function () {
    hideMenu($(this).children('.dropdown-menu'), {
      clearParent: $(this).find('> .dropdown-toggle.inail-hm-nav-link-btn')
    });
  });

  if ($menuEl.is(':visible')) {
    hideMenu($menuEl, { clearParent: $btn });
  } else {
    // Close nested submenus inside before opening
    $menuEl.find('.dropdown-menu').each(function () { hideMenu($(this)); });
    $menuEl.find('.inail-hm-active-parent').removeClass('inail-hm-active-parent');
    showMenu($menuEl, { focus: true, markParent: $btn });
  }

  adjustSubmenuDirection();
});

// Submenu toggle
$menu.on('click.desktop', '.dropdown-submenu > .inail-hm-submenu', function (e) {
  if (!isDesktop()) return;
  e.preventDefault();
  e.stopPropagation();

  const $btn = $(this);
  const $submenu = $btn.siblings('.dropdown-menu');

  // Close sibling submenus
  $btn.parent().siblings('.dropdown-submenu').each(function () {
    hideMenu($(this).children('.dropdown-menu'), {
      clearParent: $(this).children('button.inail-hm-submenu')
    });
  });

  if ($submenu.is(':visible')) hideMenu($submenu, { clearParent: $btn });
  else showMenu($submenu, { focus: true, markParent: $btn });

  adjustSubmenuDirection();
});

// Keyboard navigation (desktop)
$menu.on('keydown.desktop', '.dropdown-menu a, .dropdown-menu button', function (e) {
  if (!isDesktop()) return;

  const $current = $(this);
  const $ul = $current.closest('ul');
  const $items = $ul.find('> li:visible > a, > li:visible > button');
  const idx = $items.index(this);
  const len = $items.length;

  switch (e.key) {
    case 'ArrowDown':
      e.preventDefault();
      $items.eq((idx + 1) % len).focus();
      break;

    case 'ArrowUp':
      e.preventDefault();
      $items.eq((idx - 1 + len) % len).focus();
      break;

    case 'ArrowRight': {
      e.preventDefault();
      const $submenu = $current.parent('.dropdown-submenu').children('.dropdown-menu');
      if ($submenu.length) {
        showMenu($submenu, { focus: true, markParent: $current });
        adjustSubmenuDirection();
      }
      break;
    }

    case 'ArrowLeft': {
      e.preventDefault();
      const $parentLi = $current.closest('.dropdown-menu').parent('.dropdown-submenu');
      if ($parentLi.length) {
        const $currentMenu = $current.closest('.dropdown-menu');
        hideMenu($currentMenu, { clearParent: $parentLi.children('button.inail-hm-submenu') });
        $parentLi.children('button.inail-hm-submenu').focus();
      }
      break;
    }

    case 'Escape': {
      e.preventDefault();
      const $menuToClose = $current.closest('.dropdown-menu');
      hideMenu($menuToClose);
      $menuToClose.find('.inail-hm-active-parent').removeClass('inail-hm-active-parent');

      const $parentLi = $menuToClose.parent('.dropdown-submenu, .dropdown');
      if ($parentLi.hasClass('dropdown')) {
        $parentLi.find('> .dropdown-toggle.inail-hm-nav-link-btn').focus();
      } else if ($parentLi.hasClass('dropdown-submenu')) {
        $parentLi.children('button.inail-hm-submenu').focus();
      }
      break;
    }

    case 'Enter':
    case ' ': {
      if ($current.is('a')) {
        e.preventDefault();
        const $rootDropdown = $current.closest('.dropdown');
        $rootDropdown.find('.dropdown-menu').each(function () { hideMenu($(this)); });
        $rootDropdown.find('.inail-hm-active-parent').removeClass('inail-hm-active-parent');
        $rootDropdown.find('> .dropdown-toggle.inail-hm-nav-link-btn').focus();
      }
      break;
    }

    case 'Tab': {
      const $rootDropdown = $current.closest('.dropdown');
      $rootDropdown.find('.dropdown-menu').each(function () { hideMenu($(this)); });
      $rootDropdown.find('.inail-hm-active-parent').removeClass('inail-hm-active-parent');
      $rootDropdown.find('> .dropdown-toggle.inail-hm-nav-link-btn').attr('aria-expanded', 'false');
      break;
    }
  }
});

// Click on any link inside dropdowns (desktop)
$menu.on('click.desktop', '.dropdown-menu a', function () {
  if (!isDesktop()) return;
  const $root = $(this).closest('.dropdown');
  $root.find('.dropdown-menu').each(function () { hideMenu($(this)); });
  $root.find('.inail-hm-active-parent').removeClass('inail-hm-active-parent');
  $root.find('> .dropdown-toggle.inail-hm-nav-link-btn').focus();
});

// Init ARIA for desktop menus
$menu.find('.dropdown-toggle.inail-hm-nav-link-btn, .dropdown-submenu > .inail-hm-submenu').attr({
  'aria-haspopup': 'true',
  'aria-expanded': 'false'
});
$menu.find('.dropdown-menu').each(function () {
  $(this)
    .attr('aria-hidden', 'true')
    .css('display', 'none')
    .find('a,button').attr('tabindex', '-1');
});

// Outside click (desktop only)
$(document).on('click.desktopOutside', function (e) {
  if (!isDesktop()) return;
  if (!$menu.is(e.target) && $menu.has(e.target).length === 0) {
    $menu.find('.dropdown-menu').each(function () { hideMenu($(this)); });
    $menu.find('.dropdown-submenu > .inail-hm-submenu').removeClass('inail-hm-active-parent');
    $menu.find('.dropdown-toggle.inail-hm-nav-link-btn').attr('aria-expanded', 'false');
  }
});

// Keep submenu directions updated on resize (desktop)
$(window).on('resize.desktopDir', adjustSubmenuDirection);


  // =============================
// Part 3: Mobile helpers
// =============================

function createPanelForMenu($btn, $menuList) {
  // coerce to jQuery to be safe
  $btn = $($btn);
  $menuList = $($menuList);

  if (!$menuList.length || !$btn.length) return null;

  const panelId = 'inail-hm-mobile-panel-' + (++panelUid);
  $btn.attr('data-mobile-target', panelId);
  if ($('#' + panelId).length) return panelId;

  const $panel = $('<div>', { class: 'inail-hm-menu-panel', id: panelId })
    .data('title', $btn.text().trim());

  const $header = $('<div>', { class: 'inail-hm-menu-header' }).append(
    $('<button>', {
      class: 'inail-hm-back-btn',
      type: 'button',
      style: 'visibility:hidden',
      'aria-expanded': 'true',
      'aria-label': 'Vai al livello precedente'
    })
      .append($('<span>', { 'aria-hidden': 'true', class: 'fa-solid fa-chevron-left' }))
      .append($('<span>', { class: 'inail-hm-back-text' }).text($btn.text().trim()))
  );

  $panel.append($header);

  const $list = $('<ul>');
  $menuList.children('li').each(function () {
    const $li = $(this);

    if ($li.hasClass('dropdown-submenu')) {
      const $origSubBtn = $li.children('button.inail-hm-submenu').first();
      const $nestedMenu = $li.children('.dropdown-menu').first();

      // Build the opener button
      const $openBtn = $('<button>', {
        type: 'button',
        class: 'inail-hm-open-mobile-submenu',
        'aria-haspopup': 'true',
        'aria-expanded': 'false'
      })
        .append($('<span>').text($origSubBtn.text().trim()))
        .append($('<i>', { class: 'fa fa-chevron-right', 'aria-hidden': 'true' }));

      // Store references as jQuery data, not HTML attributes
      $openBtn
        .data('submenuEl', $nestedMenu)
        .data('submenuBtn', $origSubBtn);

      $list.append($('<li>').append($openBtn));
    } else {
      const $childEl = $li.children('a,button').first();
      if ($childEl.length) {
        const $link = $('<a>', {
          href: $childEl.is('a') ? $childEl.attr('href') : '#',
          class: 'inail-hm-menu-link'
        }).append($('<span>').text($childEl.text().trim()));
        $list.append($('<li>').append($link));
      }
    }
  });

  $panel.append($list);
  $collapse.append($panel);
  return panelId;
}

function openPanel(id, opener) {
  $menu.find('.inail-hm-menu-panel').removeClass('active');
  const $panel = $('#' + id).addClass('active');
  if (opener && opener.length) {
    $panel.data('opener', opener);
  }
  updatePanelHeaders();
}

function updatePanelHeaders() {
  const top = menuStack.length ? menuStack[menuStack.length - 1] : null;
  $menu.find('.inail-hm-menu-panel').each(function () {
    const $p = $(this);
    $p.find('.inail-hm-title').text($p.data('title') || '');
    const visibleBack = ($p.attr('id') === top && menuStack.length > 0);
    $p.find('.inail-hm-back-btn').css('visibility', visibleBack ? 'visible' : 'hidden');
  });
}

function focusFirstInPanel(id) {
  const $panel = $('#' + id);
  const $backBtn = $panel.find('.inail-hm-menu-header .inail-hm-back-btn:visible');
  if ($backBtn.length) {
    $backBtn.focus();
  } else {
    const $firstItem = $panel.find('a,button').first();
    if ($firstItem.length) $firstItem.focus();
  }
}


  // =============================
// Part 4: Mobile code
// =============================

function initMobilePanels() {
  if (panelsCreated) return;
  panelsCreated = true;
  panelUid = 0;
  menuStack = [];

  // Build panels for each top-level dropdown
  $menu.find('.dropdown').each(function () {
    const $toggle = $(this).find('> .dropdown-toggle.inail-hm-nav-link-btn').first();
    const $ul = $(this).find('> .dropdown-menu').first();
    if ($toggle.length && $ul.length) createPanelForMenu($toggle, $ul);
  });

  // Level 0 → Level 1
  $menu.on('click.mobile', '.dropdown-toggle.inail-hm-nav-link-btn', function (e) {
    if (isDesktop()) return;
    e.preventDefault();
    e.stopPropagation();

    const target = $(this).data('mobile-target');
    if (!target) return;

    $collapse.data('last-root-trigger', $(this));
    menuStack.push(target);
    openPanel(target, $(this));
    focusFirstInPanel(target);
  });

  // Level 1 → Level 2
  $menu.on('click.mobile', '.inail-hm-open-mobile-submenu', function (e) {
    if (isDesktop()) return;
    e.preventDefault();
    e.stopPropagation();

    let target = $(this).data('target-panel');

    // If panel doesn't exist yet, create it now from stored references
    if (!target || !$('#' + target).length) {
      // read from jQuery's data store (not attributes)
      let $submenuEl = $(this).data('submenuEl');
      let $submenuBtn = $(this).data('submenuBtn');

      // coerce to jQuery in case a DOM node was stored
      $submenuEl = $($submenuEl);
      $submenuBtn = $($submenuBtn);

      if ($submenuEl.length && $submenuBtn.length) {
        target = createPanelForMenu($submenuBtn, $submenuEl);
        $(this).attr('data-target-panel', target);
      } else {
        return; // nothing to open
      }
    }

    menuStack.push(target);
    openPanel(target, $(this));
    focusFirstInPanel(target);
  });

  // Back button
  $menu.on('click.mobile', '.inail-hm-menu-header .inail-hm-back-btn', function (e) {
    if (isDesktop()) return;
    e.preventDefault();
    e.stopPropagation();

    if (menuStack.length <= 1) {
      menuStack = [];
      $menu.find('.inail-hm-menu-panel').removeClass('active inail-hm-previous');
      $('#inail-hm-mobile-panel-root').addClass('active');

      const $rootTrigger = $collapse.data('last-root-trigger');
      if ($rootTrigger && $rootTrigger.length) $rootTrigger.focus();
    } else {
      const currentPanelId = menuStack.pop();
      const prevPanelId = menuStack[menuStack.length - 1];
      openPanel(prevPanelId);

      const $opener = $('#' + currentPanelId).data('opener');
      if ($opener && $opener.length) $opener.focus();
      else focusFirstInPanel(prevPanelId);
    }
  });

  // Clicking ANY link (not submenu trigger) → back to Level 0 and close instantly
  $menu.on('click.mobile', 'a:not(.inail-hm-open-mobile-submenu)', function (e) {
    if (isDesktop()) return;

    e.preventDefault();
    e.stopPropagation();

    const $currentPanel = $(this).closest('.inail-hm-menu-panel');
    const isRootPanel = $currentPanel.attr('id') === 'inail-hm-mobile-panel-root';

    let $opener = null;
    if (!isRootPanel) {
      $opener = $currentPanel.data('opener');
    }

    // Reset panels
    menuStack = [];
    $menu.find('.inail-hm-menu-panel').removeClass('active inail-hm-previous');
    $('#inail-hm-mobile-panel-root').addClass('active');

    // Close instantly
    closeCollapseInstant();

    // Return focus to opener if coming from a child panel
    if ($opener && $opener.length) $opener.focus();
  });

  // Reset when collapse hides
  $collapse.on('hide.bs.collapse.mobile', function () {
    menuStack = [];
    $menu.find('.inail-hm-menu-panel').removeClass('active inail-hm-previous');
    $('#inail-hm-mobile-panel-root').addClass('active');
  });

  // Keyboard navigation (mobile): only Esc, Enter, Space, Tab
  $menu.on('keydown.mobile', '.inail-hm-menu-panel.active a, .inail-hm-menu-panel.active button', function (e) {
    if (isDesktop()) return;

    const $current = $(this);

    switch (e.key) {
      case 'Escape':
        e.preventDefault();
        if (menuStack.length > 0) {
          // Go back one level
          $('.inail-hm-menu-header .inail-hm-back-btn:visible').trigger('click');
        } else {
          // At root → close instantly
          closeCollapseInstant();
        }
        break;

      case 'Enter':
      case ' ':
        if ($current.is('a') && !$current.hasClass('inail-hm-open-mobile-submenu')) {
          // Normal link → close instantly
          e.preventDefault();
          menuStack = [];
          $menu.find('.inail-hm-menu-panel').removeClass('active inail-hm-previous');
          $('#inail-hm-mobile-panel-root').addClass('active');
          closeCollapseInstant();
        } else if ($current.hasClass('inail-hm-open-mobile-submenu')) {
          // Submenu opener → go deeper
          e.preventDefault();

          let target = $current.data('target-panel');

          // Lazy-create if needed
          if (!target || !$('#' + target).length) {
            let $submenuEl = $current.data('submenuEl');
            let $submenuBtn = $current.data('submenuBtn');

            $submenuEl = $($submenuEl);
            $submenuBtn = $($submenuBtn);

            if ($submenuEl.length && $submenuBtn.length) {
              target = createPanelForMenu($submenuBtn, $submenuEl);
              $current.attr('data-target-panel', target);
            } else {
              return; // nothing to open
            }
          }

          menuStack.push(target);
          openPanel(target, $current);
          focusFirstInPanel(target);
        }
        break;

      case 'Tab':
        // Allow natural tabbing
        break;

      default:
        // Ignore all other keys in mobile mode
        break;
    }
  });

  // Toggle button: update label instantly on intent
  $toggleBtn.on('click.mobileToggle', function () {
    const willOpen = !$collapse.hasClass('in');
    setMenuState(willOpen);
  });
}

function destroyMobilePanels() {
  if (!panelsCreated) return;
  panelsCreated = false;
  menuStack = [];

  // Remove dynamically created panels but keep root
  $menu.find('.inail-hm-menu-panel').not('#inail-hm-mobile-panel-root').remove();

  // Reset root panel so it's visible in desktop
  $('#inail-hm-mobile-panel-root')
    .removeClass('inail-hm-previous')
    .addClass('active')
    .css('display', '');

  $menu.find('[data-mobile-target]').removeAttr('data-mobile-target');

  // Remove mobile-bound events
  $menu.off('.mobile');
  $toggleBtn.off('.mobileToggle');
  $collapse.off('.mobile');
}


  // =============================
// Part 5: Switcher — init/destroy on resize
// =============================

function closeAllDesktopMenus() {
  // Force-hide all dropdown menus regardless of current mode
  $menu.find('.dropdown-menu').each(function () {
    const $dm = $(this);
    $dm.css('display', 'none')
       .attr('aria-hidden', 'true')
       .find('a,button').attr('tabindex', '-1');

    // Reset its controlling toggle (sibling button or parent submenu btn)
    const $toggle = $dm.siblings('button.inail-hm-submenu, .dropdown-toggle.inail-hm-nav-link-btn').first();
    if ($toggle.length) $toggle.attr('aria-expanded', 'false');

    // Remove open/show classes used by Bootstrap 3/4/5
    $dm.removeClass('open show');
    $dm.parent('.dropdown, .dropdown-submenu').removeClass('open show');
  });

  // Remove active marker classes
  $menu.find('.inail-hm-active-parent').removeClass('inail-hm-active-parent');

  // Reset all toggles’ aria
  $menu
    .find('.dropdown-toggle.inail-hm-nav-link-btn, .dropdown-submenu > .inail-hm-submenu')
    .attr('aria-expanded', 'false')
    .removeClass('open show active');

  // Clear any container classes
  $menu.find('.dropdown, .dropdown-submenu').removeClass('open show');
}

function resetNavbarToggle() {
  if (isDesktop()) {
    // Desktop: always closed
    $collapse.removeClass('in').attr('aria-expanded', 'false').css('height', '');
    setMenuState(false);
  } else {
    // Mobile: mirror current collapse state
    setMenuState($collapse.hasClass('in'));
  }
}

function handleResizeInit() {
  const mode = isDesktop() ? 'desktop' : 'mobile';

  if (mode !== lastMode) {
    if (mode === 'desktop') {
      // Leaving mobile → desktop
      destroyMobilePanels();
      resetNavbarToggle();

      // Ensure collapse is closed
      $collapse.removeClass('in').attr('aria-expanded', 'false').css('height', '');

      // Reset panels to root
      menuStack = [];
      $menu.find('.inail-hm-menu-panel').removeClass('active inail-hm-previous');
      $('#inail-hm-mobile-panel-root').addClass('active');
    } else {
      // Leaving desktop → mobile
      closeAllDesktopMenus();
      resetNavbarToggle();

      // Reset mobile state before init
      menuStack = [];
      $menu.find('.inail-hm-menu-panel').removeClass('active inail-hm-previous');
      $('#inail-hm-mobile-panel-root').addClass('active');

      initMobilePanels();
    }
    lastMode = mode;
  }
}

// Initial sync
$(document).ready(function () {
  resetNavbarToggle();
  handleResizeInit();
});

// On resize
$(window).on('resize.menuSwitch', function () {
  resetNavbarToggle();
  handleResizeInit();
});

})(jQuery);
}

(function ($) {
  'use strict';

  const initialisedMenus = new WeakSet();

  function initMenu($menu) {
    if (initialisedMenus.has($menu[0])) return; // already done
    initialisedMenus.add($menu[0]);
    $menu.data('hm-init', true);
    window.initHorizontalMenu($menu);
    console.log('[HM] Initialised menu:', $menu.get(0));
  }

  function initExistingMenus() {
    $('.inail-horizontal-menu').each(function () {
      initMenu($(this));
    });
  }

  function attachMenuObserver(container) {
    const observer = new MutationObserver((mutations) => {
      for (const m of mutations) {
        for (const node of m.addedNodes) {
          if (!(node instanceof Element)) continue;

          const $targets = $(node).is('.inail-horizontal-menu')
            ? $(node)
            : $(node).find('.inail-horizontal-menu');

          $targets.each(function () {
            initMenu($(this));
          });
        }
      }
    });

    observer.observe(container, { childList: true, subtree: true });
    return observer;
  }

  function boot() {
    initExistingMenus();
    const container = document.body;
    return attachMenuObserver(container);
  }

  let menuObserver;
  if (document.readyState === 'complete') {
    menuObserver = boot();
  } else {
    $(window).on('load', () => {
      menuObserver = boot();
    });
  }

})(jQuery);


