import { ref, computed, watch, onMounted, onUnmounted } from 'vue'

export const useNavbarState = () => {
  const showContactDiv = ref(false)

  const handleMouseEnter = (event) => {
    $(event.currentTarget).find(".category-level").show();
  }

  const handleMouseLeave = (event) => {
    $(event.currentTarget).find(".category-level").hide();
  }

  const handleMouseClick = (event) => {
    const wsmenuClick = $(event.currentTarget).find(".wsmenu-click");
    wsmenuClick
      .toggleClass("ws-activearrow")
      .parent()
      .siblings()
      .children()
      .removeClass("ws-activearrow");
    $(".wsmenu > .wsmenu-list > li > .sub-menu, .wsmegamenu")
      .not(
        wsmenuClick.siblings(
          ".wsmenu > .wsmenu-list > li > .sub-menu, .wsmegamenu"
        )
      )
      .slideUp("slow");
    wsmenuClick.siblings(".sub-menu").slideToggle("slow");
    wsmenuClick.siblings(".wsmegamenu").slideToggle("slow");
  }

  const checkOutsideClick = (event) => {
    const contactDiv = document.querySelector('.contact-div');
    const toggleContactDiv = document.querySelector('.toggleContactDiv');


    if (contactDiv && toggleContactDiv)
      if (contactDiv.contains(event.target) || (toggleContactDiv.contains(event.target) && !showContactDiv.value)) {
        showContactDiv.value = true;
      }else{
        showContactDiv.value = false;
      }
  }


  onMounted(() => {
    document.addEventListener("click", checkOutsideClick);

    const topHeaderMenu = document.querySelectorAll('.topHeaderDropDownMenu')
    topHeaderMenu.forEach(item => {
      item.addEventListener('mouseover', handleMouseEnter)
      item.addEventListener('mouseout', handleMouseLeave)
      item.addEventListener('click', handleMouseClick)
    })
  })

  onUnmounted(() => {
    document.removeEventListener("click", checkOutsideClick);

    const topHeaderMenu = document.querySelectorAll('.topHeaderDropDownMenu')
    topHeaderMenu.forEach(item => {
      item.removeEventListener('mouseover', handleMouseEnter)
      item.removeEventListener('mouseout', handleMouseLeave)
      item.removeEventListener('click', handleMouseClick)
    })
  })

  return {
    showContactDiv
  }
}