<template>
  <UDropdownMenu
    :items="items"
    :content="{ align: 'center', collisionPadding: 12 }"
    :ui="{ content: collapsed ? 'w-48' : 'w-(--reka-dropdown-menu-trigger-width)' }"
  >
    <UButton
      v-bind="{
        ...user,
        label: collapsed ? undefined : user?.name,
        trailingIcon: collapsed ? undefined : 'i-lucide-chevrons-up-down'
      }"
      color="neutral"
      variant="ghost"
      block
      :square="collapsed"
      class="data-[state=open]:bg-elevated"
      :ui="{
        trailingIcon: 'text-(--ui-text-dimmed)'
      }"
    />
  </UDropdownMenu>
</template>

<script setup lang="ts">
import type { DropdownMenuItem } from '@nuxt/ui'
import { useUserStore } from '~~/stores/useUserStore'

defineProps<{
  collapsed?: boolean
}>()

const userStore = useUserStore()
const { user: keyCloakUser } = storeToRefs(userStore)

const user = ref({
  name: keyCloakUser.value?.name ?? 'UNKNOWN',
  avatar: {
    alt: keyCloakUser.value?.name ?? 'UNKNOWN'
  }
})

const { t: $t } = useI18n()

const items = computed<DropdownMenuItem[][]>(() => [
  [
    {
      type: 'label',
      label: user.value.name,
      avatar: user.value.avatar
    }
  ],
  [
    {
      label: $t('user.administration'),
      icon: 'i-lucide-shield',
      to: '/administration'
    },
    {
      label: $t('user.settings'),
      icon: 'i-lucide-settings',
      to: '/settings'
    }
  ],
  [
    {
      label: $t('user.logout'),
      icon: 'i-lucide-log-out',
      async onSelect(e: Event) {
        e.preventDefault()
        await navigateTo('/auth/logout', { external: true })
      }
    }
  ]
])
</script>
