<script lang="ts" setup>
import type { MenuGroup, MenuItem, vue } from '@factor/api'

defineProps({
  menu: { type: Object as vue.PropType<MenuGroup[]>, default: undefined },
})
function getComponentType(item: MenuItem): string {
  if (item.onClick)
    return 'div'
  else if (item.url || item.href)
    return 'a'
  else
    return 'router-link'
}
async function handleClick(event: MouseEvent, item: MenuItem): Promise<void> {
  if (item.onClick) {
    event.preventDefault()
    event.stopPropagation()
    await item.onClick(event, item)
  }
}
</script>

<template>
  <div class="space-y-4 font-sans md:space-y-6">
    <div
      v-for="(menuGroup, i) in menu"
      :key="i"
      class="menu-group"
    >
      <div class="mb-1 flex items-center space-x-3 pb-1 pr-3">
        <div
          v-if="menuGroup.groupName"
          class="text-theme-300 truncate text-xs font-semibold uppercase tracking-wide"
        >
          {{ menuGroup.groupName }}
        </div>
      </div>
      <div v-if="menuGroup.menu" class="nav-menu space-y-1">
        <component
          :is="getComponentType(sub)"
          v-for="(sub, ii) in menuGroup.menu"
          :key="ii"
          class="nav-item flex cursor-pointer items-center space-x-3 truncate rounded-lg px-3 py-2 text-sm font-semibold focus:outline-none"
          :to="sub.route?.value"
          :href="sub.href || sub.route?.value"
          :class="
            sub.active?.value || sub.selected
              ? 'bg-theme-200 text-theme-900'
              : 'hover:bg-theme-100 active:bg-theme-200 text-theme-600 hover:text-theme-900   border-theme-0'
          "
          @click="handleClick($event, sub)"
        >
          <div
            v-if="sub.icon"
            class="text-[1.4em]"
            :class="sub.active?.value ? 'text-theme-900 ' : 'text-theme-500'"
          >
            <div :class="sub.icon" />
          </div>
          <div class="">
            {{ sub.name }}
          </div>
        </component>
      </div>
    </div>
  </div>
</template>

<style lang="less"></style>
