<script setup lang="ts">
import type { Link } from '@/types/link'

const props = withDefaults(
  defineProps<{
    level?: number
    links?: Link[]
    defaultOpen?: boolean
  }>(),
  {
    level: 0,
    links: () => [],
    defaultOpen: false,
  },
)

interface LinkGroup {
  type?: 'link' | 'accordion'
  defaultOpen?: boolean
  children: Link[]
}

const groups = computed<LinkGroup[]>(() => {
  const groups: LinkGroup[] = []

  let group: LinkGroup = { type: undefined, children: [] }

  for (const link of props.links) {
    const type = link.children?.length ? 'accordion' : 'link'
    if (!group.type)
      group.type = type

    if (group.type === type) {
      group.children.push(link)
    }
    else {
      groups.push(group)
      group = { type, children: [link] }
    }
  }

  if (group.children.length)
    groups.push(group)

  return groups
})
</script>

<template>
  <nav v-if="groups?.length" class="space-y-3">
    <template v-for="(group, index) in groups" :key="index">
      <UiNavigationAccordion
        v-if="group.type === 'accordion'"
        :links="group.children"
        :level="level"
        :default-open="defaultOpen"
      />
      <UiNavigationLinks v-else :links="group.children" :level="level" />
    </template>
  </nav>
</template>
