<script setup lang="ts">
import { navigationMenuTriggerStyle } from '../ui/navigation-menu/index'
import type { Link } from '@/types/link'

withDefaults(
  defineProps<{
    links?: Link[]
  }>(),
  {},
)
const active = ref()
const rootRef = ref<HTMLDivElement>()

watch(active, () => {
  if (active.value) {
    nextTick(() => {
      const triggerEl = rootRef.value?.querySelector(
        `[data-id="trigger-${active.value}"]`,
      )
      const contentEl = rootRef.value?.querySelector<HTMLDivElement>(
        `[data-id="content-${active.value}"]`,
      )
      if (triggerEl && contentEl) {
        const { left: triggerLeft, width: triggerWidth }
          = triggerEl.getBoundingClientRect()
        const { left: contentLeft, width: contentWidth }
          = contentEl.getBoundingClientRect()
        const offset
          = triggerLeft - contentLeft + triggerWidth / 2 - contentWidth / 2
        contentEl.parentElement!.style.left = `${offset}px`
      }
    })
  }
})
</script>

<template>
  <div ref="rootRef">
    <NavigationMenu>
      <NavigationMenuList>
        <NavigationMenuItem v-for="(link, index) of links" :key="index">
          <template v-if="link.children?.length">
            <NavigationMenuTrigger>
              <UiButton
                variant="ghost"
                size="sm"
                v-bind="omit(link, ['children'])"
                active-class="text-primary!"
                inactive-class="bg-transparent"
                class="px-0"
                @click="link.click"
              />
            </NavigationMenuTrigger>
            <NavigationMenuContent>
              <UiHeaderPopoverLinks :links="link.children" />
            </NavigationMenuContent>
          </template>
          <NavigationMenuLink
            v-else
            :class="navigationMenuTriggerStyle()"
            as-child
          >
            <UiButton
              variant="ghost"
              size="sm"
              v-bind="omit(link, ['children'])"
              active-class="bg-accent!"
              inactive-class="bg-transparent"
              @click="link.click"
            >
              <span
                v-if="link.target === '_blank'"
                class="i-ph:arrow-up-right-light w-3 h-3 absolute top-1.5 right-1"
              />
            </UiButton>
          </NavigationMenuLink>
        </NavigationMenuItem>
      </NavigationMenuList>
    </NavigationMenu>
  </div>
</template>
