<template>
  <n-menu
    :value="activeKey"
    :options="menuOptions"
  />
</template>

<script setup>
import { NuxtLink, NaiveIcon } from "#components";
import { computed, h, useRouter } from "#imports";
const props = defineProps({
  routes: { type: Array, required: false, default: () => [] },
  activeBy: { type: String, required: false, default: "path" }
});
const router = useRouter();
if (!router.currentRoute.value) {
  console.warn("[nuxt-naiveui] make sure to create page components when using `NaiveMenuLink`");
}
const activeKey = computed(() => getActiveKey(router.currentRoute.value));
function getActiveKey(activeRoute) {
  if (props.activeBy === "name") {
    return activeRoute.name?.toString();
  }
  const activePath = activeRoute.path;
  let activeKey2 = activePath;
  const cb = (routes) => {
    for (const route of routes) {
      const path = route.to && router.resolve(route.to).path;
      if (path && activePath === path) {
        activeKey2 = path;
        break;
      }
      if (path && activePath.startsWith(`${path}/`)) {
        activeKey2 = path;
      }
      if (route.children) {
        cb(route.children);
      }
    }
  };
  cb(props.routes);
  return activeKey2;
}
const menuOptions = computed(() => {
  const cb = (routes) => routes.map((route) => {
    const name = route.to && router.resolve(route.to).name?.toString();
    const path = route.to && router.resolve(route.to).path;
    const key = (props.activeBy === "name" ? name : path) ?? route.label;
    const menuOption = {
      label: route.to ? () => h(NuxtLink, { to: route.to }, { default: () => route.label }) : route.label,
      icon: route.icon ? () => h(NaiveIcon, { name: route.icon }) : void 0,
      key
    };
    if (route.children) {
      menuOption.children = cb(route.children);
    }
    return menuOption;
  });
  return cb(props.routes);
});
</script>
