/**
 * @description
 * Menu mobile
 */

function dediMenu() {
  // Déclaration des variables
  const pictoMenu = document.querySelector('.header-link-menu');
  const bodyPage = document.body;
  const submenuTrigger = document.querySelectorAll('.has-submenu > .menu-title');
  const backMenu = document.querySelectorAll('.menu-back');
  const blockMenu = document.querySelectorAll('.menu-block');

  if (!pictoMenu) {
    return;
  }

  /**
   * @description
   * Ouverture/Fermeture lors du clic sur le picto menu
   */
  pictoMenu.onclick = function (e) {
    e.preventDefault();
    bodyPage.classList.toggle('open-menu');
    if (!bodyPage.classList.contains('open-menu')) {
      // eslint-disable-next-line no-restricted-syntax
      for (const item of blockMenu) {
        item.classList.remove('open');
      }
    }
  };

  /**
   * @description
   * Detection du click pour ouvrir le menu suivant et affectation de la classe open
   */
  // eslint-disable-next-line no-restricted-syntax
  for (const item of submenuTrigger) {
    item.onclick = function (e) {
      e.preventDefault();
      this.nextElementSibling.classList.add('open');
    };
  }

  /**
   * @description
   * Detection du click pour le retour arrière et suppression de la classe open
   */
  // eslint-disable-next-line no-restricted-syntax
  for (const item of backMenu) {
    item.onclick = function (e) {
      e.preventDefault();
      this.closest('.menu-block').classList.remove('open');
    };
  }
}

/**
 * @description
 * Overlay lors de l'ouverture du menu desktop
 */
function overlayMenu() {
  const target = document.querySelector('body');

  // Init
  target.classList.remove('menu-mask');

  if (window.matchMedia('(min-width: 992px)').matches) {
    const firstLi = document.querySelectorAll('.menu-lvl1 > li');

    // eslint-disable-next-line no-restricted-syntax
    for (const item of firstLi) {
      item.onmouseenter = function () {
        if (this.classList.contains('has-submenu')) {
          target.classList.add('menu-mask');
        } else {
          target.classList.remove('menu-mask');
        }
      };
      item.onmouseleave = function () {
        target.classList.remove('menu-mask');
      };
    }
  }
}

export default () => {
  dediMenu();
  overlayMenu();

  window.addEventListener('resize', () => {
    overlayMenu();
  });
};
