<template>
  <template v-if="Array.isArray(nav)">
    <ol
      v-if="nav.length > 0"
      class="a-nav-menu tw-p-0 tw-m-0 tw-mb-2 tw-flex tw-flex-col tw-gap-2"
      :class="`a-nav-menu-level-${level}`"
      v-bind="attrs"
    >
      <li v-for="(navItem, navItemIndex) of nav" :key="navItemIndex" class="tw-block">
        <ANavMenu :nav="navItem" :level="level + 1" />
      </li>
    </ol>
  </template>
  <template v-else>
    <RouterLink
      v-if="nav.link && !nav.link.requiresAdmin"
      :to="nav.link.route"
      :data-testid="nav.link.testId"
      active-class="has-active-child"
      exact-active-class="is-active"
      class="a-nav-link tw-no-underline tw-block tw-py-3 tw-px-6"
      v-bind="attrs"
    >
      <SafeHTML :html="nav.link.label" sanitize-preset="inline-noninteractive" />
    </RouterLink>

    <template v-if="nav.menus">
      <template v-for="(menuItem, menuItemIndex) in nav.menus" :key="menuItemIndex">
        <div class="tw-ml-4 tw-mt-2">
          <p
            class="a-nav-label tw-m-0 tw-px-6 tw-py-1 tw-text-gray-500 tw-text-sm tw-leading-snug tw-truncate"
            v-bind="attrs"
            :title="sanitizeHTML(menuItem.title, 'strip')"
          >
            <SafeHTML :html="menuItem.title" sanitize-preset="inline-noninteractive" />
          </p>

          <ANavMenu :nav="menuItem.items" :level="level" />
        </div>
      </template>
    </template>
  </template>
</template>

<script setup lang="ts">
import SafeHTML from '@/components/generic/SafeHTML'
import { MenuItem } from '@/components/nav/nav'
import { useAttrs } from 'vue'
import { sanitizeHTML } from '@/util'

defineOptions({
  inheritAttrs: false,
  compatConfig: { MODE: 3 },
})

withDefaults(
  defineProps<{
    nav: MenuItem | MenuItem[]
    level?: number
  }>(),
  {
    level: 0,
  },
)
const attrs = useAttrs()
</script>

<style lang="postcss" scoped>
.a-nav-menu {
  @apply tw-font-medium;

  &.a-nav-menu-level-0 > li {
    &:has(ol) + li {
      @apply !tw-mt-3;
    }
  }
}

.a-nav-link {
  @apply tw-bg-white tw-rounded tw-transition-colors tw-border tw-border-solid tw-border-black/5;
  color: inherit;

  &:hover {
    @apply tw-bg-blue-100;
  }

  &.is-active {
    @apply tw-bg-aura-primary tw-text-white;
  }
}
</style>