window.addEventListener('load', function() {
  let colorUnderline;
  const menu = document.querySelector('.js-menu');
  const menuMobile = document.querySelector('.js-header__main-menu');

  if (menu) {
    colorUnderline = document.querySelector('.js-selector_indicator_color').innerHTML;
    document.documentElement.style.setProperty('--menu_selector_underline', colorUnderline);
  }

  if (!menu) {
    menuMobile.classList.add('hidden');
    return;
  }
  const menuMask = menu.querySelector('.js-menu__mask');

  const nextControl = menu.querySelector('.js-menu__item--next');
  const prevControl = menu.querySelector('.js-menu__item--prev');
  const menuContainer = menu.querySelector('.js-menu__container');

  const menuItems = menuContainer.querySelectorAll('.js-menu__item');
  const subMenuItems = menuContainer.querySelectorAll('.submenu__text');

  menuItems.forEach(element => {
    if (document.querySelector('.js-menu_typography').innerHTML === 'uppercase') {
      element.querySelectorAll('span.menu__text')[0].innerHTML = element
        .querySelectorAll('span.menu__text')[0]
        .innerHTML.toLocaleUpperCase();
    }
    if (document.querySelector('.js-menu_typography').innerHTML === 'lowercase') {
      element.querySelectorAll('span.menu__text')[0].innerHTML = element
        .querySelectorAll('span.menu__text')[0]
        .innerHTML.toLocaleLowerCase();
    }
    if (document.querySelector('.js-menu_typography').innerHTML === 'firstuppercase') {
      element.querySelectorAll('span.menu__text')[0].innerHTML =
        element
          .querySelectorAll('span.menu__text')[0]
          .innerHTML.charAt(0)
          .toUpperCase() +
        element
          .querySelectorAll('span.menu__text')[0]
          .innerHTML.slice(1)
          .toLocaleLowerCase();
    }
  });

  subMenuItems.forEach(element => {
    if (document.querySelector('.js-menu_typography').innerHTML === 'uppercase') {
      element.innerHTML = element.innerHTML.toLocaleUpperCase();
    }
    if (document.querySelector('.js-menu_typography').innerHTML === 'lowercase') {
      element.innerHTML = element.innerHTML.toLocaleLowerCase();
    }
    if (document.querySelector('.js-menu_typography').innerHTML === 'firstuppercase') {
      element.innerHTML = element.innerHTML.charAt(0).toUpperCase() + element.innerHTML.slice(1).toLocaleLowerCase();
    }
  });

  const firstMenuItem = menuItems[0];
  const firstMenuItemStyle = window.getComputedStyle(firstMenuItem);
  const lastMenuItem = menuItems[menuItems.length - 1];

  const allSubmenu = menu.querySelectorAll('.js-submenu, .js-submenu__content');
  const allBack = menu.querySelectorAll('.js-submenu__item--back');

  //new submenu
  const allSubmenuItem = menu.querySelectorAll('.js-submenu__content');
  const prop = menu.getAttribute('data');
  const styleDefault = document.querySelectorAll('.submenu');

  if (prop == 0) {
    const { menuContainerRect, firstMenuItemRect, lastMenuItemRect } = getBoundingClientRect();
    const menuItemsWidth = lastMenuItemRect.right - firstMenuItemRect.left;

    styleDefault.forEach(item => {
      if (menuContainerRect.width <= menuItemsWidth) {
        item.classList.add('submenu-2');
      }
    });
    allSubmenuItem.forEach(item => {
      item.classList.add('submenu__content-2');
    });
  } else {
    positionMenu();

    menuItems.forEach(menuHeader => {
      menuHeader.addEventListener('mouseover', positionMenu);
    });

    function positionMenu() {

      menuItems.forEach(menuHeader => {
        
        if (menuHeader.children[1]) {
          if (menuHeader.children[1].getBoundingClientRect().right > window.innerWidth)
            menuHeader.children[1].classList.add('right');

          if (menuHeader.getBoundingClientRect().left < menuHeader.children[1].getBoundingClientRect().left)
            menuHeader.children[1].classList.remove('right');

          if (menuHeader.children[1].getBoundingClientRect().left < 0) menuHeader.children[1].classList.add('left');
          
          if (menuHeader.getBoundingClientRect().right >= menuHeader.children[1].getBoundingClientRect().right)
            menuHeader.children[1].classList.remove('left');
        }
      });

      allSubmenuItem.forEach(item => {
        if (item.children.length < 11) item.classList.add('default');

        if (item.children.length > 10 && item.children.length < 27) item.classList.add('small');

        if (item.children.length > 27 && item.children.length < 35) item.classList.add('average');

        if (item.children.length > 35 && item.children.length < 42) item.classList.add('large');

        if (item.children.length > 34) item.classList.add('extraLarge');
      });
    }
  }

  let heightSubmenuItem;
  if (allSubmenu.length) {
    const firstSubmenuItem = allSubmenu[0].querySelector('.js-submenu__item');

    if (firstSubmenuItem) {
      heightSubmenuItem = window.getComputedStyle(firstSubmenuItem).height.replace(/\D/g, '');
    }
  }

  allBack.forEach(back => {
    const submenu = back.parentNode.parentNode;
    const submenuContent = back.parentNode;

    back.addEventListener('click', function() {
      if (window.innerWidth >= 768) return;

      if (submenu && submenu.style.display === 'block') {
        submenu.removeAttribute('style');
      }
      if (submenuContent && submenuContent.style.display === 'block') {
        submenuContent.removeAttribute('style');
      }
    });
  });

  allSubmenu.forEach(submenu => {
    const menuContent = submenu.previousElementSibling;
    if (!menuContent) return;

    const submenuStyle = window.getComputedStyle(submenu);

    const isDepartmentsSubmenu = submenu.classList.contains('submenu__content--departments');
    
    if (isDepartmentsSubmenu) {
      const lengthSubmenuItems = submenu.querySelectorAll('.js-submenu__item').length;
      const heightSubmenu = heightSubmenuItem * lengthSubmenuItems + 16;
      const maxHeightSubmenu = submenuStyle.maxHeight.replace(/\D/g, '');
      const minHeightSubmenu = heightSubmenu > maxHeightSubmenu ? maxHeightSubmenu : heightSubmenu;
      submenu.style.minHeight = `${minHeightSubmenu}px`;
    }

    menuContent.addEventListener('click', function(event) {
      if (window.innerWidth >= 768) return;

      event.preventDefault();
      submenu.style.display = submenuStyle.display === 'none' ? 'block' : 'none';
    });
  });

  menuMobile.addEventListener('click', function() {
    menu.classList.toggle('menu--open');
  });
  menuMask.addEventListener('click', function() {
    menu.classList.remove('menu--open');
  });

  nextControl.addEventListener('click', nextMenu);
  prevControl.addEventListener('click', prevMenu);

  resetMenu();
  window.addEventListener('resize', function() {
    resetMenu();
  });

  function getBoundingClientRect() {
    return {
      menuContainerRect: menuContainer.getBoundingClientRect(),
      firstMenuItemRect: firstMenuItem.getBoundingClientRect(),
      lastMenuItemRect: lastMenuItem.getBoundingClientRect(),
    };
  }

  function resetMenu() {
    const { menuContainerRect, firstMenuItemRect, lastMenuItemRect } = getBoundingClientRect();
    const menuItemsWidth = lastMenuItemRect.right - firstMenuItemRect.left;

    firstMenuItem.removeAttribute('style');

    if (menuContainerRect.width >= menuItemsWidth) {
      nextControl.classList.add('hidden');
      prevControl.classList.add('hidden');
      menuContainer.classList.remove('menu__container--discount-nav-control');

      styleDefault.forEach(item => {
        item.classList.contains('submenu--departments') && item.classList.remove('submenu-2');
      });

    } else {
      nextControl.classList.remove('hidden');
      prevControl.classList.remove('hidden');
      menuContainer.classList.add('menu__container--discount-nav-control');
      menu.classList.remove('menu--open');
    }
  }


  function nextMenu(event) {
    event.preventDefault();
    const { menuContainerRect, lastMenuItemRect } = getBoundingClientRect();

    if (lastMenuItemRect.right === menuContainerRect.right) {
      return;
    }

    let marginLeft = 0;

    for (let menuItemIndex = 0; menuItemIndex < menuItems.length; menuItemIndex++) {
      const menuItemRect = menuItems[menuItemIndex].getBoundingClientRect();

      if (menuItemRect.right - 5 > menuContainerRect.right) {
        marginLeft = menuItemRect.right - menuContainerRect.right;
        break;
      }
    }
    const oldMarginLeft = parseFloat(firstMenuItemStyle.marginLeft);
    const newMarginLeft = oldMarginLeft - marginLeft;
    firstMenuItem.style.marginLeft = `${newMarginLeft}px`;
  }

  function prevMenu(event) {
    event.preventDefault();
    const { menuContainerRect, firstMenuItemRect } = getBoundingClientRect();

    if (firstMenuItemRect.left === menuContainerRect.left) {
      return;
    }

    let marginLeft = 0;

    for (let menuItemIndex = 0; menuItemIndex < menuItems.length; menuItemIndex++) {
      const menuItemRect = menuItems[menuItemIndex].getBoundingClientRect();

      if (menuContainerRect.left <= menuItemRect.right + 5) {
        marginLeft = menuContainerRect.left - menuItemRect.left;
        break;
      }
    }

    const oldMarginLeft = parseFloat(firstMenuItemStyle.marginLeft);
    const newMarginLeft = oldMarginLeft + marginLeft;
    firstMenuItem.style.marginLeft = `${newMarginLeft}px`;
  }
});
