<template>
  <component :is="RouterLink" v-if="item.route"
    :to="{ name: item.route, hash: item.hash ? '#' + item.hash : undefined, params }" custom
    v-slot="{ href, route, navigate, isActive }">
    <li class="c-sidebar-nav__item" v-bind="subMenuAttr(!!item.children, isActive)">
      <a :href="href" @click="navigate" class="c-sidebar-nav__link"
        :aria-current="route.fullPath === $route.fullPath ? 'page' : undefined">
        <content />
      </a>
      <sub-menu />
    </li>
  </component>

  <li v-else-if="item.url" class="c-sidebar-nav__item">
    <a :href="item.url" class="c-sidebar-nav__link" target="_blank" rel="noopener noreferrer">
      <content />
    </a>
    <sub-menu />
  </li>

  <li v-else-if="item" class="c-sidebar-nav__item">
    <span class="c-sidebar-nav__link">
      <content />
    </span>
    <sub-menu />
  </li>
</template>

<script setup lang="ts">
import type SidebarNavItem from '../../models/SidebarNavItem';
import { computed, defineAsyncComponent, defineComponent, h } from 'vue';
import CSidebarNavItem from './CSidebarNavItem.vue';

const { item } = defineProps<{ item: SidebarNavItem }>();

const params = item?.slug
  ? { slug: item?.slug } // When it is a slug
  : undefined;

// only import RouterLink if item.route exists
const RouterLink = computed(() => {
  return item.route == null
    ? null
    : defineAsyncComponent(() => import('vue-router').then(r => r.RouterLink))
});

// a11y attributes for submenu
const subMenuAttr: any = (submenu: boolean, isActive: boolean) => {
  if (submenu) {
    return {
      'aria-haspopup': 'menu',
      'aria-expanded': isActive ? 'true' : 'false',
    };
  }
};

// render the text and icons
const content = defineComponent({
  setup() {
    return () => [
      item.icon &&
      h('span', { class: `c-sidebar-nav__symbol-left icon-${item.icon}` }), // icon,
      item.text, // plain text
      item.showArrow && h('span', { class: 'c-sidebar-nav__symbol-right' })
    ]
  }
});

// loop all the children and render them
const subMenu = defineComponent({
  setup() {
    return () => item.children && [
      h('button', { 'type': 'button', class: 'c-sidebar-nav__open-submenu', 'aria-expanded': 'false' }),
      h('ul', { class: 'c-sidebar-nav__submenu', 'aria-expanded': 'false' }, [
        item.children.map(child => h(CSidebarNavItem, {
          key: child.url ?? child.route,
          item: child
        }))
      ])
    ]
  }
});

</script>