/**
 * Temporary local copy of aux-main-nav.js
 * The local version has a few differences from the CDN version.
 *
 * USING THE CDN VERSION WILL BREAK THE MAIN NAV.
 *
 * This script is enqueued globally on all front-end pages by
 * HeadService::enqueueScripts(), which is called from the wp_enqueue_scripts
 * action hook. Loaded in the footer with defer strategy.
 * @see \WP_AUX\Services\HeadService::enqueueScripts()
 * @since 1.0.0
 */
let auxDropdown = document.querySelectorAll("#navbar .dropdown-toggle, #mobile-navbar .dropdown-toggle");

for (
  let dropdownIndex = 0;
  dropdownIndex < auxDropdown.length;
  dropdownIndex++
) {
  auxDropdown[dropdownIndex].addEventListener("click", function (e) {
    let dropdownParent = this;
    let dropdownChild = this.nextElementSibling;

    document.querySelectorAll(".dropdown").forEach((el) => {
      if (el !== dropdownChild) {
        el.style.display = "none";
        el.ariaExpanded = "false";
        el.ariaPressed = "false";

        el.parentElement.children[0].ariaExpanded = "false";
        el.parentElement.children[0].ariaPressed = "false";
      } else {
        el.ariaExpanded = "true";
        el.ariaPressed = "true";

        el.parentElement.children[0].ariaExpanded = "true";
        el.parentElement.children[0].ariaPressed = "true";
      }
    });

    if (dropdownChild.style.display === "block") {
      dropdownChild.style.display = "none";

      dropdownChild.ariaExpanded = "false";
      dropdownChild.ariaPressed = "false";

      dropdownParent.ariaPressed = "false";
      dropdownParent.ariaExpanded = "false";
    } else {
      dropdownChild.style.display = "block";

      dropdownChild.ariaExpanded = "true";
      dropdownChild.ariaPressed = "true";

      dropdownParent.ariaExpanded = "true";
      dropdownParent.ariaPressed = "true";
    }

    window.addEventListener("click", function (event) {
      if (!event.target.classList.contains("dropdown-toggle")) {
        dropdownChild.style.display = "none";

        dropdownChild.ariaExpanded = "false";
        dropdownChild.ariaPressed = "false";

        dropdownParent.ariaPressed = "false";
        dropdownParent.ariaExpanded = "false";
      }
    });
  });
}
