jQuery(function ($) {
  const menuItems = $("#adminmenu > li.menu-top");

  const active = $("#adminmenu li.wp-has-current-submenu");
  if (active.length) {
    const submenu = active.children(".wp-submenu");
    active.addClass("submenu-open menu-active");

    submenu.hide().slideDown(250);

    addBackButton(active, submenu);
  }

  function addBackButton(item, submenu) {
    if (!submenu.find(".back-button").length) {
      const back = $('<div class="back-button">&#8592;</div>').hide();

      back.on("click", function (evt) {
        evt.stopPropagation();
        submenu.slideUp(250, () => {
          item.removeClass("submenu-open menu-active");
          submenu.hide();
          menuItems.addClass("menu-active");
        });
      });

      submenu.prepend(back);
      back.fadeIn(250);
    }
  }

  menuItems.on("click", function (e) {
    const item = $(this);
    const submenu = item.children(".wp-submenu");

    if ($(e.target).closest(".wp-submenu").length) return;

    if (!submenu.length) {
      menuItems.removeClass("submenu-open menu-active");
      item.addClass("menu-active");
      return;
    }

    e.preventDefault();

    if (item.hasClass("submenu-open")) {
      submenu.slideUp(250, () => {
        item.removeClass("submenu-open menu-active");
        menuItems.addClass("menu-active");
      });
      return;
    }

    $("#adminmenu .wp-submenu:visible").slideUp(250);
    menuItems.removeClass("submenu-open menu-active");

    item.addClass("submenu-open menu-active");
    submenu.hide().slideDown(250);

    addBackButton(item, submenu);
  });
});
