<template>
  <nav
    v-if="navigationMenu.hasContent"
    role="navigation"
  >
    <ul class="navigation-menu">
      <li
        v-for="item in navigationMenu.items"
        :key="item.id"
        class="menu-item"
        @mouseenter="onMouseEnter(item, $event)"
        @mouseleave="onMouseLeave(item)"
        @focusin="onMouseEnter(item, $event)"
        @focusout="onMouseLeave(item)"
      >
        <a
          class="menu-link"
          @click="item.performAction"
        >
          {{ item.title }}
        </a>
        <span
          v-if="item.showStoreCategories && isItemWithCategoriesDropdown(item)"
          class="arrow"
        >
          ▶
        </span>
      </li>
    </ul>
    <CategoriesDropdown
      v-if="showCategoriesDropdown"
      :element="activeItem?.element"
      :category-id="categoryId"
      @hide="hideDropdown"
    />
  </nav>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { useNavigationMenuElementContent } from '@lightspeed/crane';
import CategoriesDropdown from './CategoriesDropdown.vue';

interface ActiveItem {
  actionLink: ActionLink;
  element?: HTMLElement;
}

const navigationMenu = useNavigationMenuElementContent();
const activeItem = ref<ActiveItem | null>();

const showCategoriesDropdown = computed(() => {
  const item = activeItem.value?.actionLink;
  if (isItemWithCategoriesDropdown(item)) {
    return item?.showStoreCategories ?? true;
  }
  return false;
});

const categoryId = computed(() => {
  const item = activeItem.value?.actionLink;
  if (item?.type === 'GO_TO_CATEGORY') {
    return item.categoryId;
  }
  return undefined;
});

function isItemWithCategoriesDropdown(item?: ActionLink) {
  return item?.type === 'GO_TO_STORE' || item?.type === 'GO_TO_CATEGORY';
}

function onMouseEnter(item: ActionLink, event: MouseEvent | FocusEvent) {
  activeItem.value = {
    actionLink: item,
    element: event.target as HTMLElement,
  };
}

function onMouseLeave(item: ActionLink | null) {
  if (activeItem.value?.actionLink === item) {
    activeItem.value = null;
  }
}

function hideDropdown() {
  activeItem.value = null;
}
</script>

<style scoped lang="scss">
.navigation-menu {
  display: flex;
  gap: 16px;
  overflow-x: auto;
  white-space: nowrap;
  height: 48px;
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.menu-item {
  position: relative;
  display: flex;
  align-items: center;
}

.menu-link {
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  color: #080d12;
  text-decoration: none;
  transition: color 0.35s ease;

  &:hover {
    color: #0056b3;
  }
}

.arrow {
  margin-left: 8px;
  font-size: 8px;
  color: #cacaca;
}
</style>
