<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-[var(--brand-surface)] shadow-xl border border-[var(--brand-border)] backdrop-blur-xl',
      item: {
        disabled: 'cursor-default select-text opacity-100',
        base: 'group gap-3 rounded-xl transition-all duration-300 hover:bg-[var(--brand-primary)]/10 active:scale-[0.98]',
        padding: 'px-4 py-3'
      },
      separator: 'my-1.5',
      arrow: 'before:bg-[var(--brand-surface)] before:border before:border-[var(--brand-border)]'
    }"
    :popper="{ placement: 'bottom-end', offsetDistance: 12 }"
    arrow
  >
    <UButton
      color="neutral"
      variant="ghost"
      :ui="{
        rounded: 'rounded-full',
        padding: { sm: 'p-1' }
      }"
      class="relative hover:bg-[var(--brand-primary)]/10 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-[var(--brand-bg)] ring-[var(--brand-primary)]/30 group-hover:ring-[var(--brand-primary)]/60 transition-all duration-300 shadow-lg group-hover:shadow-[var(--brand-primary)]/20'
          }"
        />
        <span
          class="absolute -bottom-0.5 -right-0.5 w-3 h-3 bg-green-500 border-2 border-[var(--brand-bg)] 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-[var(--brand-border)] mb-1">
        <div class="relative">
          <UAvatar
            v-bind="item.avatar"
            size="lg"
            :ui="{
              wrapper: 'ring-2 ring-[var(--brand-primary)]/40 shadow-lg'
            }"
          />
          <span
            class="absolute -bottom-1 -right-1 w-4 h-4 bg-green-500 border-2 border-[var(--brand-surface)] rounded-full"
            title="En línea"
          />
        </div>
        <div class="flex-1 min-w-0">
          <p class="font-bold text-base text-[var(--brand-text)] truncate mb-0.5">
            {{ item.label }}
          </p>
          <p class="text-xs text-[var(--brand-text-muted)] 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-[var(--brand-primary)]/20 flex items-center justify-center transition-colors duration-200 group-hover:bg-[var(--brand-primary)]/30']">
          <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-[var(--brand-text)]">
            {{ item.label }}
          </p>
          <p class="text-xs text-[var(--brand-text-muted)]">
            {{ item.description }}
          </p>
        </div>
        <UIcon name="i-lucide-chevron-right" class="w-4 h-4 text-[var(--brand-text-muted)] 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-[var(--brand-text-muted)] mt-0.5" />
          <div class="flex-1 min-w-0">
            <p class="text-xs text-[var(--brand-text-muted)]">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-[var(--brand-text-muted)] mt-0.5" />
          <div class="flex-1 min-w-0">
            <p class="text-xs text-[var(--brand-text-muted)]">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-[var(--brand-text-muted)] mt-0.5" />
          <div class="flex-1 min-w-0">
            <p class="text-xs text-[var(--brand-text-muted)]">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-[var(--brand-text-muted)] mt-0.5" />
          <div class="flex-1 min-w-0">
            <p class="text-xs text-[var(--brand-text-muted)]">ID Único</p>
            <p class="font-mono text-xs text-[var(--brand-text)]">{{ user?.uid }}</p>
          </div>
        </div>

        <!-- Grupos -->
        <div class="flex items-start gap-3">
          <UIcon name="i-heroicons-user-group" class="text-[var(--brand-text-muted)] mt-0.5" />
          <div class="flex-1 min-w-0">
            <p class="text-xs text-[var(--brand-text-muted)] 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-[var(--brand-border)]">
          <p class="text-xs text-[var(--brand-text-muted)] 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-[var(--brand-text-muted)]" />
              <span class="text-[var(--brand-text)]">App:</span>
              <code class="text-xs bg-[var(--brand-bg)]/50 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-[var(--brand-text-muted)]" />
              <span class="text-[var(--brand-text)]">Outpost:</span>
              <code class="text-xs bg-[var(--brand-bg)]/50 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-[var(--brand-surface)] flex items-center justify-center transition-colors duration-200 group-hover:bg-[var(--brand-primary)]/30']">
          <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-[var(--brand-text-muted)]">
            {{ item.description }}
          </p>
        </div>
        <UIcon name="i-lucide-chevron-right" class="w-4 h-4 text-[var(--brand-text-muted)] opacity-0 group-hover:opacity-100 transition-opacity duration-200" />
      </div>
    </template>

  </UDropdownMenu>
</template>
