<template>
  <UNavigationMenu orientation="vertical" type="single" :items="items" class="data-[orientation=vertical]:w-72" />
</template>

<script setup lang="ts">
import { getMenu } from '@/router/menu'
import type { NavigationMenuItem } from '@nuxt/ui';
import { ref } from 'vue';
import { useRoute } from 'vue-router';

let menu = await getMenu() as NavigationMenuItem[]
const openAll = ref(false)
const route = useRoute()

let categoryId = ref(route.params.category_id)
function findPath(tree: NavigationMenuItem[], id: number, path: Array<number> = []): Array<number> | null {
  for (let item of tree) {
    let newPath: Array<number> = [...path, item.category_id]
    if (item.category_id === id) {
      return newPath
    }
    if (item.children) {
      const result: Array<number> | null = findPath(item.children, id, newPath)

      if (result) {
        return result
      }
    }
  }

  return null
}

let path = findPath(menu, Number(categoryId.value))
function adaptMenu(menu: NavigationMenuItem[]) {
  for (const item of menu) {
    if (item.children && item.children.length > 0) {
      item.open = path && path.includes(item.category_id) ? true : openAll.value
      adaptMenu(item.children);
      item.children.unshift({
        label: item.label, icon: 'i-lucide-book-open', popover: item.label, to: {
          name: 'customer-products-category', params: {
            category_id: item.params.category_id,
            link_rewrite: item.params.link_rewrite
          }
        }
      })
    } else {
      item.to = {
        name: 'customer-products-category', params: {
          category_id: item.params.category_id,
          link_rewrite: item.params.link_rewrite
        }
      };
      item.icon = 'i-lucide-file-text'
    }
  }
  return menu;
}

menu = adaptMenu(menu)
const items = ref<NavigationMenuItem[][]>([
  [
    ...menu as NavigationMenuItem[]
  ],

])
</script>