export default function menuInit() {
  let main_navigation =
    document.querySelector('#primary-menu');
  const header = document.querySelector('#primary-header');
  const primary_menu =
    header.querySelector('#primary-menu');
  const burgerMenuToggle = header.querySelector(
    '#burger-menu-toggle'
  );
  const submenuToggles = primary_menu.querySelectorAll(
    '.menu-item-submenu-toggle'
  );

  // #### Open/close burger nav
  burgerMenuToggle.addEventListener('click', function (e) {
    e.preventDefault();
    header.classList.toggle('nav-open');
    burgerMenuToggle.toggleAttribute('aria-expanded');
    gsap.from(primary_menu, {
      opacity: 20,
      y: '-100vh',
      duration: 0.5,
      ease: Power4.easeOut,
    });
  });

  // #### Close nav when reaching the end of the menu with tab
  document.addEventListener(
    'focusin',
    (e) => {
      const header = document.querySelector(
        '#primary-header'
      );
      console.log(header.contains(document.activeElement));
      if (
        header.classList.contains('nav-open') &&
        !header.contains(document.activeElement)
      ) {
        header.classList.remove('nav-open');
        burgerMenuToggle.setAttribute(
          'aria-expanded',
          false
        );

        burgerMenuToggle.focus();
      }
    },
    true
  );

  submenuToggles.forEach((button) => {
    button.addEventListener('click', function (e) {
      let isExpanded =
        button.getAttribute('aria-expanded') === 'true';
      button.setAttribute('aria-expanded', !isExpanded);

      button.parentElement
        .querySelector('.sub-menu')
        .classList.toggle('sub-menu-open');
    });
  });
}
