document.addEventListener("DOMContentLoaded", function() {
  var isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
  var body = document.body;

  // Determine hover setting from body classes
  var hoverSetting = 'auto';
  if (body.classList.contains('submenu-hover-yes')) hoverSetting = 'yes';
  else if (body.classList.contains('submenu-hover-no')) hoverSetting = 'no';

  // Resolve effective hover mode
  var useHover;
  if (hoverSetting === 'yes') useHover = true;
  else if (hoverSetting === 'no') useHover = false;
  else useHover = !isTouchDevice;

  // Determine submenu display mode
  var submenuDisplayMode = 'auto';
  if (body.classList.contains('submenu-display-burger')) submenuDisplayMode = 'burger';

  // Burger submenu mode forces click-only
  if (submenuDisplayMode === 'burger') useHover = false;

  // Add body class so CSS can target resolved no-hover state
  if (!useHover) {
    body.classList.add('fps-no-hover');
  }

  // Burger menu mode
  var burgerMenuMode = 'auto';
  if (body.classList.contains('burger-menu-yes')) burgerMenuMode = 'yes';
  else if (body.classList.contains('burger-menu-no')) burgerMenuMode = 'no';

  // Touch + burger (auto or yes): add CSS class for responsive burger
  if (burgerMenuMode !== 'no' && isTouchDevice) {
    body.classList.add('fps-burger-touch');
  }

  // Default Fomantic dropdown options
  var dropdownOpts = {
    on: useHover ? 'hover' : 'click',
    showOnFocus: true,
    allowTab: true,
    forceSelection: false,
    action: function(text, value, element) { element.click(); },
    onChange: function(value, text, $choice) {}
  };

  // --- Helper: inject parent link as first submenu item (idempotent) ---
  function injectParentLink(el) {
    var parentUrl = el.getAttribute('data-parent-url');
    var parentTitle = el.getAttribute('data-parent-title');
    var parentIcon = el.getAttribute('data-parent-icon');
    if (!parentUrl || !parentTitle) return;
    var submenu = el.querySelector('.fps-submenu');
    if (!submenu) return;
    if (submenu.querySelector('.fps-parent-link')) return;
    var a = document.createElement('a');
    a.href = parentUrl;
    a.className = 'item fps-parent-link';
    a.setAttribute('role', 'menuitem');
    a.setAttribute('title', parentTitle);
    a.innerHTML = '<i class="' + parentIcon + ' menu-item-icon"></i> <span class="menu-item-title"><strong>' + parentTitle + '</strong></span>';
    submenu.insertBefore(a, submenu.firstChild);
  }

  // When hover is disabled globally, inject parent links and remove hrefs
  if (!useHover) {
    document.querySelectorAll('.fps-has-submenu').forEach(function(el) {
      injectParentLink(el);
    });
    document.querySelectorAll('.fpsDropdown > a').forEach(function(link) {
      link.removeAttribute('href');
      link.style.cursor = 'pointer';
      makeSubmenuToggle(link, false);
    });
  }

  // Initialize Fomantic dropdowns globally
  jQuery('.fpsDropdown').dropdown(dropdownOpts);
  syncDropdownExpandedState(document);

  if (window.MutationObserver) {
    document.querySelectorAll('.fpsDropdown').forEach(function(dropdown) {
      var observer = new MutationObserver(function() {
        syncDropdownExpandedState(dropdown);
      });
      observer.observe(dropdown, { attributes: true, attributeFilter: ['class'] });
    });
  }

  // Main menu mode detection
  var mainMenuMode = 'auto';
  if (body.classList.contains('menu-display-big_icon')) mainMenuMode = 'big_icon';
  else if (body.classList.contains('menu-display-small_icon_text')) mainMenuMode = 'small_icon_text';
  if (mainMenuMode === 'auto' && isTouchDevice) {
    body.classList.add('menu-display-touch');
  }

  // Narrow sidebar: watch for open dropdowns and temporarily allow overflow so
  // flyout submenus can extend beyond the sidebar boundary. CSS (overflow-x: hidden)
  // prevents the horizontal scrollbar when no dropdown is open.
  var isNarrowSidebar = mainMenuMode === 'big_icon' ||
    (mainMenuMode === 'auto' && (isTouchDevice || window.innerWidth <= 768));
  if (isNarrowSidebar && window.MutationObserver) {
    var $sidebar = jQuery('.site-sidebar');
    var sidebarObserver = new MutationObserver(function() {
      var anyActive = !!document.querySelector('.site-sidebar .fpsDropdown.active');
      // overflow:visible lets the flyout menu escape the sidebar;
      // '' removes the inline style so CSS (overflow-y:auto; overflow-x:hidden) takes over.
      $sidebar.css('overflow', anyActive ? 'visible' : '');
    });
    document.querySelectorAll('.site-sidebar .fpsDropdown').forEach(function(el) {
      sidebarObserver.observe(el, { attributes: true, attributeFilter: ['class'] });
    });
  }

  // === Focus trap + Escape key for overlay menus ===
  var FOCUSABLE = 'a[href], button:not([disabled]), [role="button"][tabindex="0"], [tabindex]:not([tabindex="-1"])';

  function isFocusableVisible(el) {
    if (!el || el.disabled || el.getAttribute('aria-hidden') === 'true') {
      return false;
    }

    var style = window.getComputedStyle(el);
    if (style.visibility === 'hidden' || style.display === 'none') {
      return false;
    }

    return !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length);
  }

  function getFocusable(container) {
    return Array.prototype.slice.call(container.querySelectorAll(FOCUSABLE)).filter(isFocusableVisible);
  }

  function makeSubmenuToggle(link, expanded) {
    if (!link) return;
    link.setAttribute('role', 'button');
    link.setAttribute('tabindex', '0');
    link.setAttribute('aria-expanded', expanded ? 'true' : 'false');
  }

  function restoreSubmenuToggle(link) {
    if (!link) return;
    link.removeAttribute('role');
    link.removeAttribute('aria-expanded');
  }

  function syncDropdownExpandedState(root) {
    var dropdowns = root.classList && root.classList.contains('fpsDropdown')
      ? [root]
      : root.querySelectorAll('.fpsDropdown');

    Array.prototype.forEach.call(dropdowns, function(dropdown) {
      var toggle = dropdown.querySelector(':scope > a[role="button"]');
      if (!toggle) return;
      toggle.setAttribute('aria-expanded', dropdown.classList.contains('active') ? 'true' : 'false');
    });
  }

  function activateOnKeyboard(handler) {
    return function(e) {
      if (e.key !== 'Enter' && e.key !== ' ') {
        return;
      }

      e.preventDefault();
      handler(e);
    };
  }

  function trapFocus(container, returnFocus) {
    var focusable = getFocusable(container);
    if (focusable.length) focusable[0].focus();

    function keyHandler(e) {
      if (e.key === 'Escape') {
        closeOverlayMenu(container, returnFocus);
        document.removeEventListener('keydown', keyHandler);
        return;
      }
      if (e.key === 'Tab') {
        var focusableNow = getFocusable(container);
        if (focusableNow.length === 0) return;
        var first = focusableNow[0];
        var last = focusableNow[focusableNow.length - 1];
        if (e.shiftKey && document.activeElement === first) {
          e.preventDefault();
          last.focus();
        } else if (!e.shiftKey && document.activeElement === last) {
          e.preventDefault();
          first.focus();
        }
      }
    }
    document.addEventListener('keydown', keyHandler);
    container._fpsTrapHandler = keyHandler;
  }

  function closeOverlayMenu(container, returnFocus) {
    if (!container) return;

    if (container.id === 'topbar-expanded-menu') {
      container.style.display = 'none';
      container.setAttribute('aria-hidden', 'true');
      restoreMenu(container);
    } else if (container.id === 'sidebar-menu-panel') {
      container.classList.remove('fps-open');
      container.style.display = '';
      restoreMenu(container);
    } else {
      container.classList.remove('fps-open');
      container.style.display = 'none';
    }

    if (returnFocus) {
      returnFocus.setAttribute('aria-expanded', 'false');
      returnFocus.focus();
    }
  }

  function releaseFocus(container) {
    if (container._fpsTrapHandler) {
      document.removeEventListener('keydown', container._fpsTrapHandler);
      delete container._fpsTrapHandler;
    }
  }

  // === Burger overlay helpers ===

  // Prepare a container for burger/overlay mode (always click-to-open)
  function prepareBurgerMenu(container) {
    // Destroy and re-init Fomantic dropdowns for click mode
    var $dd = jQuery(container).find('.fpsDropdown');
    $dd.dropdown('destroy');
    $dd.dropdown({
      on: 'click',
      showOnFocus: true,
      allowTab: true,
      forceSelection: false,
      action: function(text, value, element) { element.click(); }
    });

    // Save and remove hrefs from all parent links with submenus
    container.querySelectorAll('.fps-has-submenu > a').forEach(function(link) {
      if (link.hasAttribute('href') && !link.hasAttribute('data-burger-href')) {
        link.setAttribute('data-burger-href', link.getAttribute('href'));
        link.removeAttribute('href');
        link.style.cursor = 'pointer';
      }
      makeSubmenuToggle(link, false);
    });

    // Inject parent links into submenus
    container.querySelectorAll('.fps-has-submenu').forEach(function(el) {
      injectParentLink(el);
    });
  }

  // Restore a container from burger mode to normal sidebar mode
  function restoreMenu(container) {
    // Destroy and re-init Fomantic dropdowns with original mode
    var $dd = jQuery(container).find('.fpsDropdown');
    $dd.dropdown('destroy');
    $dd.dropdown(dropdownOpts);

    // Restore all hrefs saved during burger mode
    container.querySelectorAll('[data-burger-href]').forEach(function(link) {
      link.setAttribute('href', link.getAttribute('data-burger-href'));
      link.removeAttribute('data-burger-href');
      link.style.cursor = '';
      restoreSubmenuToggle(link);
    });

    // Re-remove hrefs for top-level dropdowns if global no-hover mode
    if (!useHover) {
      container.querySelectorAll('.fpsDropdown > a').forEach(function(link) {
        link.removeAttribute('href');
        link.style.cursor = 'pointer';
        makeSubmenuToggle(link, false);
      });
    }

    // Close any open nested submenus
    container.querySelectorAll('.fps-submenu.fps-nested-open').forEach(function(sub) {
      sub.classList.remove('fps-nested-open');
    });
  }

  // Delegated click handler for nested submenus (non-Fomantic) in burger mode
  function addNestedSubmenuClickHandler(container, activeCheck) {
    container.addEventListener('click', function(e) {
      if (activeCheck && !activeCheck()) return;

      var link = e.target.closest('.fps-has-submenu:not(.fpsDropdown) > a');
      if (!link || !container.contains(link)) return;

      var parent = link.closest('.fps-has-submenu');
      var submenu = parent.querySelector('.fps-submenu');
      if (!submenu) return;

      e.preventDefault();
      e.stopPropagation();
      var isOpen = submenu.classList.toggle('fps-nested-open');
      makeSubmenuToggle(link, isOpen);
    });

    container.addEventListener('keydown', function(e) {
      var link = e.target.closest('.fps-has-submenu:not(.fpsDropdown) > a, .fps-has-submenu > a[role="button"]');
      if (!link || !container.contains(link)) return;
      activateOnKeyboard(function(event) {
        link.click();
      })(e);
    });
  }

  // === Top bar hamburger toggle ===
  var hamburger = document.getElementById('topbar-hamburger');
  var expandedMenu = document.getElementById('topbar-expanded-menu');
  if (hamburger && expandedMenu) {
    expandedMenu.setAttribute('aria-hidden', 'true');

    // Expanded menu always uses burger/click mode
    addNestedSubmenuClickHandler(expandedMenu);

    hamburger.addEventListener('click', function() {
      if (expandedMenu.style.display === 'none' || expandedMenu.style.display === '') {
        expandedMenu.style.display = 'block';
        expandedMenu.setAttribute('aria-hidden', 'false');
        hamburger.setAttribute('aria-expanded', 'true');
        prepareBurgerMenu(expandedMenu);
        trapFocus(expandedMenu, hamburger);
      } else {
        releaseFocus(expandedMenu);
        closeOverlayMenu(expandedMenu, hamburger);
      }
    });
  }

  // === Sidebar hamburger toggle (left-sidebar layout) ===
  var sidebarHamburger = document.getElementById('sidebar-hamburger');
  var sidebarMenuPanel = document.getElementById('sidebar-menu-panel');
  if (sidebarHamburger && sidebarMenuPanel) {
    // Nested click handler only active when panel is open as overlay
    addNestedSubmenuClickHandler(sidebarMenuPanel, function() {
      return sidebarMenuPanel.classList.contains('fps-open');
    });

    sidebarHamburger.addEventListener('click', function() {
      if (sidebarMenuPanel.classList.contains('fps-open')) {
        releaseFocus(sidebarMenuPanel);
        closeOverlayMenu(sidebarMenuPanel, sidebarHamburger);
      } else {
        sidebarMenuPanel.classList.add('fps-open');
        sidebarHamburger.setAttribute('aria-expanded', 'true');
        prepareBurgerMenu(sidebarMenuPanel);
        trapFocus(sidebarMenuPanel, sidebarHamburger);
      }
    });

    var sidebarPanelClose = document.getElementById('sidebar-panel-close');
    if (sidebarPanelClose) {
      sidebarPanelClose.addEventListener('click', function() {
        releaseFocus(sidebarMenuPanel);
        closeOverlayMenu(sidebarMenuPanel, sidebarHamburger);
      });
    }
  }

  // === Top bar submenu toggle on click (no-hover / touch / burger submenu mode) ===
  var useTopbarClick = !useHover || submenuDisplayMode === 'burger';

  if (useTopbarClick) {
    document.querySelectorAll('.topbar-item.has-children').forEach(function(item) {
      var link = item.querySelector('.topbar-icon-link');
      var submenu = item.querySelector('.topbar-submenu');
      if (!link || !submenu) return;

      link.removeAttribute('href');
      link.style.cursor = 'pointer';
      makeSubmenuToggle(link, false);

      function toggleTopbarSubmenu(e) {
        e.preventDefault();
        e.stopPropagation();
        document.querySelectorAll('.topbar-submenu.fps-open').forEach(function(other) {
          if (other !== submenu) {
            other.classList.remove('fps-open');
            other.style.display = 'none';
            var otherToggle = other.closest('.topbar-item');
            if (otherToggle) {
              var otherLink = otherToggle.querySelector('.topbar-icon-link[role="button"]');
              if (otherLink) otherLink.setAttribute('aria-expanded', 'false');
            }
          }
        });
        if (submenu.classList.contains('fps-open')) {
          submenu.classList.remove('fps-open');
          submenu.style.display = 'none';
          link.setAttribute('aria-expanded', 'false');
        } else {
          submenu.classList.add('fps-open');
          submenu.style.display = 'block';
          link.setAttribute('aria-expanded', 'true');
        }
      }

      link.addEventListener('click', toggleTopbarSubmenu);
      link.addEventListener('keydown', activateOnKeyboard(toggleTopbarSubmenu));
    });

    // Nested submenu toggle on click (top bar)
    document.querySelectorAll('.topbar-nested-item.has-children').forEach(function(item) {
      var toggle = item.querySelector('.topbar-nested-toggle');
      var nested = item.querySelector('.topbar-submenu-nested');
      if (!toggle || !nested) return;

      toggle.removeAttribute('href');
      toggle.style.cursor = 'pointer';
      makeSubmenuToggle(toggle, false);

      function toggleNestedSubmenu(e) {
        e.preventDefault();
        e.stopPropagation();
        item.parentElement.querySelectorAll('.topbar-submenu-nested.fps-open').forEach(function(other) {
          if (other !== nested) {
            other.classList.remove('fps-open');
            other.style.display = 'none';
            var otherItem = other.closest('.topbar-nested-item');
            if (otherItem) {
              var otherToggle = otherItem.querySelector('.topbar-nested-toggle[role="button"]');
              if (otherToggle) otherToggle.setAttribute('aria-expanded', 'false');
            }
          }
        });
        if (nested.classList.contains('fps-open')) {
          nested.classList.remove('fps-open');
          nested.style.display = 'none';
          toggle.setAttribute('aria-expanded', 'false');
        } else {
          nested.classList.add('fps-open');
          nested.style.display = 'block';
          toggle.setAttribute('aria-expanded', 'true');
        }
      }

      toggle.addEventListener('click', toggleNestedSubmenu);
      toggle.addEventListener('keydown', activateOnKeyboard(toggleNestedSubmenu));
    });

    // Close submenus when clicking outside
    document.addEventListener('click', function(e) {
      if (!e.target.closest('.topbar-item')) {
        document.querySelectorAll('.topbar-submenu.fps-open, .topbar-submenu-nested.fps-open').forEach(function(sub) {
          sub.classList.remove('fps-open');
          sub.style.display = 'none';
        });
        document.querySelectorAll('.topbar-icon-link[role="button"], .topbar-nested-toggle[role="button"]').forEach(function(toggle) {
          toggle.setAttribute('aria-expanded', 'false');
        });
      }
    });
  }

  // === Burger submenu mode: inject close buttons ===
  if (submenuDisplayMode === 'burger') {
    document.querySelectorAll('.fps-submenu').forEach(function(submenu) {
      if (submenu.querySelector('.fps-burger-close')) return;
      var closeBtn = document.createElement('button');
      closeBtn.className = 'fps-burger-close';
      closeBtn.setAttribute('aria-label', 'Close submenu');
      closeBtn.innerHTML = '<i class="fas fa-times"></i>';
      closeBtn.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var dropdown = submenu.closest('.fpsDropdown');
        if (dropdown) jQuery(dropdown).dropdown('hide');
      });
      submenu.insertBefore(closeBtn, submenu.firstChild);
    });

    document.querySelectorAll('.topbar-submenu').forEach(function(submenu) {
      if (submenu.querySelector('.fps-burger-close')) return;
      var closeBtn = document.createElement('button');
      closeBtn.className = 'fps-burger-close';
      closeBtn.setAttribute('aria-label', 'Close submenu');
      closeBtn.innerHTML = '<i class="fas fa-times"></i>';
      closeBtn.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        submenu.classList.remove('fps-open');
        submenu.style.display = 'none';
      });
      submenu.insertBefore(closeBtn, submenu.firstChild);
    });
  }

});
