import "./menu.main.scss";

document.addEventListener('DOMContentLoaded', (event) => {
  const MAIN_MENU = document.querySelector('[data-js="main-menu"]');
  if (!MAIN_MENU) return;

  const MENU_ITEMS = MAIN_MENU.querySelectorAll('li');

  MENU_ITEMS.forEach((item, index) => {
    item.style.opacity = '0';
    item.style.transition = 'opacity 200ms ease-in-out';
  });

  window.addEventListener('main-menu:animate-in:start', () => {
    MENU_ITEMS.forEach((item, index) => {
      let reverseIndex = MENU_ITEMS.length - 1 - index;
      // Add 200(ms) to each delay.
      // The "+ 200(ms)" makes sure the first item also gets delayed.
      let delay = reverseIndex * 200 + 200;

      setTimeout(() => {
        item.style.opacity = '1';

        // Wait for the last item before firing the custom event.
        if (index === 0) {
          setTimeout(() => {
            window.dispatchEvent(new CustomEvent('main-menu:animate-in:complete'));
          }, 200);
        }
      }, delay);
    });
  }, { passive: true });

  window.addEventListener('main-menu:animate-out:start', () => {
    MENU_ITEMS.forEach((item, index) => {
      let delay = index * 200;

      setTimeout(() => {
        item.style.opacity = '0';

        // Wait for the last item before firing the custom event.
        if (index === MENU_ITEMS.length - 1) {
          setTimeout(() => {
            window.dispatchEvent(new CustomEvent('main-menu:animate-out:complete'));
          }, 200);
        }
      }, delay);
    });
  }, { passive: true });
});
