<template>
    <nav class="tp-main-menu-content">
      <ul v-for="(menu, i) in menu_data" :key="menu?.id || i">
        <li v-if="menu.drop_down" :key="menu.id" :class="`has-dropdown ${isActiveMenu === menu.title?'dropdown-opened':''}`">
          <a :class="`${isActiveMenu === menu.title?'expanded':''}`"
             @click="handleOpenSubMenu(menu.title)"
          >
            {{ menu.title }}
            <button
                :class="`dropdown-toggle-btn ${isActiveMenu === menu.title?'dropdown-opened':''}`"
            >
              <i class="fa-regular fa-angle-right"></i>
            </button>
          </a>
          <ul :class="`tp-submenu pe-3 ${isActiveMenu === menu.title ? 'active':''}`">
            <li v-for="(subMenu, i) in menu.dropdown_menus?.data" :key="subMenu?.id || i">
              <nuxt-link :to="subMenu.link" @click="handleOpenSubMenu(subMenu.title, true)">{{ subMenu.title }}</nuxt-link>
            </li>
          </ul>
        </li>
        <li v-else :key="menu?.id || i">
          <nuxt-link :to="menu.link" @click="handleOpenSubMenu(menu.title, true)">{{ menu.title }}</nuxt-link>
        </li>
      </ul>
    </nav>
</template>

<script lang="ts" setup>
import {useUtilityStore} from "@/pinia/useUtilityStore";

const router = useRouter();
const utilsStore = useUtilityStore();
// const menu_data = ref<IMenuItem[]>([] as IMenuItem[]);
const isActiveMenu = ref<string>("");

const handleOpenSubMenu = (title: string, closeMainMenu = false) => {
	if (title === isActiveMenu.value) {
		isActiveMenu.value = "";
	} else {
		isActiveMenu.value = title;
	}

  if (closeMainMenu) {
    utilsStore.handleOpenMobileMenu();
  }
};

const currentPath = computed(() => router.currentRoute.value.path);
const {
  data: menu_data,
  error,
  pending
} = useLazyAsyncData(
    `site-menu`,
    () => $axios.get(`menu`)
        .then(res => res?.data?.data || {}),
    {
      watch: [currentPath],
      immediate: true
    }
);

if (error.value) {
  console.error('Failed to load menus data:', error.value);
}

// onMounted(() => {
	// api.menuData({
	// 	slug: ""
	// })
	// 		.then((d) => console.log(51,menu_data.value = d))
// });
</script>
