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';
    });
  }

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

  // 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]), [tabindex]:not([tabindex="-1"])';

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

    function keyHandler(e) {
      if (e.key === 'Escape') {
        container.classList.remove('fps-open');
        container.style.display = 'none';
        if (returnFocus) returnFocus.focus();
        document.removeEventListener('keydown', keyHandler);
        return;
      }
      if (e.key === 'Tab') {
        var focusableNow = container.querySelectorAll(FOCUSABLE);
        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 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';
      }
    });

    // 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 = '';
    });

    // 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';
      });
    }

    // 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();
      submenu.classList.toggle('fps-nested-open');
    });
  }

  // === Top bar hamburger toggle ===
  var hamburger = document.getElementById('topbar-hamburger');
  var expandedMenu = document.getElementById('topbar-expanded-menu');
  if (hamburger && expandedMenu) {
    // 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';
        hamburger.setAttribute('aria-expanded', 'true');
        prepareBurgerMenu(expandedMenu);
        trapFocus(expandedMenu, hamburger);
      } else {
        expandedMenu.style.display = 'none';
        hamburger.setAttribute('aria-expanded', 'false');
        releaseFocus(expandedMenu);
      }
    });
  }

  // === 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')) {
        sidebarMenuPanel.classList.remove('fps-open');
        sidebarHamburger.setAttribute('aria-expanded', 'false');
        releaseFocus(sidebarMenuPanel);
        restoreMenu(sidebarMenuPanel);
        sidebarHamburger.focus();
      } 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() {
        sidebarMenuPanel.classList.remove('fps-open');
        sidebarHamburger.setAttribute('aria-expanded', 'false');
        releaseFocus(sidebarMenuPanel);
        restoreMenu(sidebarMenuPanel);
        sidebarHamburger.focus();
      });
    }
  }

  // === 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';

      link.addEventListener('click', function(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';
          }
        });
        if (submenu.classList.contains('fps-open')) {
          submenu.classList.remove('fps-open');
          submenu.style.display = 'none';
        } else {
          submenu.classList.add('fps-open');
          submenu.style.display = 'block';
        }
      });
    });

    // 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';

      toggle.addEventListener('click', function(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';
          }
        });
        if (nested.classList.contains('fps-open')) {
          nested.classList.remove('fps-open');
          nested.style.display = 'none';
        } else {
          nested.classList.add('fps-open');
          nested.style.display = 'block';
        }
      });
    });

    // 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';
        });
      }
    });
  }

  // === 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);
    });
  }

});
