<script setup lang="ts">
const { user, isAuthenticated, logout, goToProfile } = useAuthentik()

// Estado para el dropdown
const isOpen = ref(false)

// Computed para el avatar del usuario con gradiente dinámico
const userAvatar = computed(() => ({
  src: user.value?.avatar || `https://ui-avatars.com/api/?name=${encodeURIComponent(user.value?.name || user.value?.username || 'User')}&background=random&bold=true&format=svg`,
  alt: user.value?.name || user.value?.username || 'User'
}))

// Iniciales del usuario para efecto visual
const userInitials = computed(() => {
  const name = user.value?.name || user.value?.username || 'U'
  return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2)
})

const items = computed(() => [
  [{
    label: user.value?.name || user.value?.username || 'Usuario',
    description: user.value?.email,
    avatar: userAvatar.value,
    slot: 'account',
    type: 'label'
  }],
  [{
    label: 'Metadatos',
    description: 'Información del usuario',
    icon: 'i-heroicons-information-circle',
    iconClass: 'text-purple-500',
    slot: 'metadata'
  }],
  [{
    label: 'Mi Perfil',
    description: 'Ver y editar perfil',
    icon: 'i-lucide-user',
    iconClass: 'text-blue-500',
    click: () => goToProfile(),
    slot: 'profile'
  },
  {
    label: 'Configuración',
    description: 'Preferencias y ajustes',
    icon: 'i-lucide-settings',
    iconClass: 'text-gray-500',
    to: '/settings',
    slot: 'settings'
  }],
  [{
    label: 'Ayuda y Soporte',
    icon: 'i-lucide-help-circle',
    iconClass: 'text-indigo-500',
    to: '/help'
  }],
  [{
    label: 'Cerrar sesión',
    icon: 'i-lucide-log-out',
    iconClass: 'text-red-500',
    color: 'error',
    click: () => logout()
  }]
])
</script>

<template>
  <UDropdownMenu
    v-if="isAuthenticated"
    v-model:open="isOpen"
    :items="items"
    :ui="{
      content: 'w-72 p-2 bg-white dark:bg-gray-900 shadow-xl border border-gray-200 dark:border-gray-800 backdrop-blur-xl',
      item: {
        disabled: 'cursor-default select-text opacity-100',
        base: 'group gap-3 rounded-xl transition-all duration-300 hover:bg-gray-50 dark:hover:bg-gray-800/50 active:scale-[0.98]',
        padding: 'px-4 py-3'
      },
      separator: 'my-1.5',
      arrow: 'before:bg-white dark:before:bg-gray-900 before:border before:border-gray-200 dark:before:border-gray-800'
    }"
    :popper="{ placement: 'bottom-end', offsetDistance: 12 }"
    arrow
  >
    <UButton
      color="neutral"
      variant="ghost"
      :ui="{
        rounded: 'rounded-full',
        padding: { sm: 'p-1' }
      }"
      class="relative hover:bg-gray-100/80 dark:hover:bg-gray-800/80 transition-all duration-300 hover:scale-110 active:scale-95 group"
    >
      <div class="relative">
        <UAvatar
          v-bind="userAvatar"
          size="sm"
          :ui="{
            wrapper: 'ring-2 ring-offset-2 ring-offset-white dark:ring-offset-gray-950 ring-primary-500/30 group-hover:ring-primary-500/60 transition-all duration-300 shadow-lg group-hover:shadow-primary-500/20'
          }"
        />
        <span
          class="absolute -bottom-0.5 -right-0.5 w-3 h-3 bg-green-500 border-2 border-white dark:border-gray-950 rounded-full transition-all duration-300 group-hover:scale-110"
          title="En línea"
        />
      </div>
    </UButton>

    <template #account="{ item }">
      <div class="flex items-center gap-4 py-2 px-2 border-b border-gray-100 dark:border-gray-800 mb-1">
        <div class="relative">
          <UAvatar
            v-bind="item.avatar"
            size="lg"
            :ui="{
              wrapper: 'ring-2 ring-primary-500/40 shadow-lg'
            }"
          />
          <span
            class="absolute -bottom-1 -right-1 w-4 h-4 bg-green-500 border-2 border-white dark:border-gray-900 rounded-full"
            title="En línea"
          />
        </div>
        <div class="flex-1 min-w-0">
          <p class="font-bold text-base text-gray-900 dark:text-white truncate mb-0.5">
            {{ item.label }}
          </p>
          <p class="text-xs text-gray-500 dark:text-gray-400 truncate font-medium">
            {{ item.description }}
          </p>
        </div>
      </div>
    </template>

    <template #profile="{ item }">
      <div class="flex items-center gap-3">
        <div :class="['w-9 h-9 rounded-lg bg-blue-50 dark:bg-blue-950/30 flex items-center justify-center transition-colors duration-200 group-hover:bg-blue-100 dark:group-hover:bg-blue-950/50']">
          <UIcon :name="item.icon" :class="['w-4 h-4', item.iconClass]" />
        </div>
        <div class="flex-1 min-w-0">
          <p class="font-semibold text-sm text-gray-900 dark:text-white">
            {{ item.label }}
          </p>
          <p class="text-xs text-gray-500 dark:text-gray-400">
            {{ item.description }}
          </p>
        </div>
        <UIcon name="i-lucide-chevron-right" class="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
      </div>
    </template>

    <template #metadata="{ item }">
      <div class="px-2 py-3 space-y-3 max-h-96 overflow-y-auto">
        <!-- Username -->
        <div class="flex items-start gap-3">
          <UIcon name="i-heroicons-at-symbol" class="text-gray-500 dark:text-gray-400 mt-0.5" />
          <div class="flex-1 min-w-0">
            <p class="text-xs text-gray-500 dark:text-gray-400">Username</p>
            <p class="font-medium text-sm">{{ user?.username }}</p>
          </div>
        </div>

        <!-- Email -->
        <div class="flex items-start gap-3">
          <UIcon name="i-heroicons-envelope" class="text-gray-500 dark:text-gray-400 mt-0.5" />
          <div class="flex-1 min-w-0">
            <p class="text-xs text-gray-500 dark:text-gray-400">Email</p>
            <p class="font-medium text-sm">{{ user?.email || 'No especificado' }}</p>
          </div>
        </div>

        <!-- Nombre completo -->
        <div class="flex items-start gap-3">
          <UIcon name="i-heroicons-user" class="text-gray-500 dark:text-gray-400 mt-0.5" />
          <div class="flex-1 min-w-0">
            <p class="text-xs text-gray-500 dark:text-gray-400">Nombre Completo</p>
            <p class="font-medium text-sm">{{ user?.name || 'No especificado' }}</p>
          </div>
        </div>

        <!-- UID -->
        <div class="flex items-start gap-3">
          <UIcon name="i-heroicons-key" class="text-gray-500 dark:text-gray-400 mt-0.5" />
          <div class="flex-1 min-w-0">
            <p class="text-xs text-gray-500 dark:text-gray-400">ID Único</p>
            <p class="font-mono text-xs text-gray-600 dark:text-gray-300">{{ user?.uid }}</p>
          </div>
        </div>

        <!-- Grupos -->
        <div class="flex items-start gap-3">
          <UIcon name="i-heroicons-user-group" class="text-gray-500 dark:text-gray-400 mt-0.5" />
          <div class="flex-1 min-w-0">
            <p class="text-xs text-gray-500 dark:text-gray-400 mb-2">Grupos</p>
            <div class="flex flex-wrap gap-2">
              <UBadge
                v-for="group in user?.groups"
                :key="group"
                color="primary"
                variant="soft"
                size="xs"
              >
                {{ group }}
              </UBadge>
              <UBadge v-if="!user?.groups || user.groups.length === 0" color="gray" variant="soft" size="xs">
                Sin grupos
              </UBadge>
            </div>
          </div>
        </div>

        <!-- Metadata de Authentik -->
        <div v-if="user?.appSlug || user?.outpostName" class="pt-3 border-t border-gray-200 dark:border-gray-700">
          <p class="text-xs text-gray-500 dark:text-gray-400 mb-2">Conexión Authentik</p>
          <div class="space-y-2">
            <div v-if="user?.appSlug" class="flex items-center gap-2 text-xs">
              <UIcon name="i-heroicons-cube" class="text-gray-400" />
              <span class="text-gray-600 dark:text-gray-300">App:</span>
              <code class="text-xs bg-gray-100 dark:bg-gray-800 px-1.5 py-0.5 rounded">{{ user.appSlug }}</code>
            </div>
            <div v-if="user?.outpostName" class="flex items-center gap-2 text-xs">
              <UIcon name="i-heroicons-server" class="text-gray-400" />
              <span class="text-gray-600 dark:text-gray-300">Outpost:</span>
              <code class="text-xs bg-gray-100 dark:bg-gray-800 px-1.5 py-0.5 rounded">{{ user.outpostName }}</code>
            </div>
          </div>
        </div>
      </div>
    </template>

    <template #settings="{ item }">
      <div class="flex items-center gap-3">
        <div :class="['w-9 h-9 rounded-lg bg-gray-50 dark:bg-gray-800/50 flex items-center justify-center transition-colors duration-200 group-hover:bg-gray-100 dark:group-hover:bg-gray-800']">
          <UIcon :name="item.icon" :class="['w-4 h-4', item.iconClass]" />
        </div>
        <div class="flex-1 min-w-0">
          <p class="font-semibold text-sm text-gray-900 dark:text-white">
            {{ item.label }}
          </p>
          <p class="text-xs text-gray-500 dark:text-gray-400">
            {{ item.description }}
          </p>
        </div>
        <UIcon name="i-lucide-chevron-right" class="w-4 h-4 text-gray-400 opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
      </div>
    </template>

  </UDropdownMenu>
</template>
