<template>
  <div ref="containerRef" class="relative flex items-center">
    <!-- Avatar button — click to toggle dropdown -->
    <button
      @click="isOpen = !isOpen"
      class="flex h-9 w-9 items-center justify-center rounded-full bg-[#70BC84]/20 text-sm font-bold text-[#70BC84] ring-2 ring-white/10 transition-all duration-200 hover:ring-[#70BC84]/50 focus:outline-none focus:ring-[#70BC84]/50 cursor-pointer"
      :aria-label="t('header.userMenu')"
    >
      {{ initials }}
    </button>

    <!-- ── Dropdown Menu (Glassmorphism) ──────────────────────────── -->
    <Transition
      enter-active-class="transition duration-150 ease-out"
      enter-from-class="scale-95 opacity-0 -translate-y-2"
      enter-to-class="scale-100 opacity-100 translate-y-0"
      leave-active-class="transition duration-100 ease-in"
      leave-from-class="scale-100 opacity-100 translate-y-0"
      leave-to-class="scale-95 opacity-0 -translate-y-2"
    >
      <div
        v-if="isOpen"
        class="absolute right-0 top-full mt-2 w-64 z-50 rounded-xl border border-white/10 bg-[#04151F]/90 backdrop-blur-xl shadow-2xl shadow-black/40 overflow-hidden"
      >
        <!-- User info header -->
        <div class="px-4 py-3 border-b border-white/5">
          <p class="text-sm font-semibold text-white/90 truncate">{{ fullName }}</p>
          <p class="text-xs text-white/40 truncate mt-0.5">{{ email }}</p>
        </div>

        <!-- Menu items -->
        <div class="py-1">
          <!-- Profile settings -->
          <button
            @click="goToProfile"
            class="flex w-full items-center gap-3 px-4 py-2.5 text-sm text-white/80 transition-all duration-150 hover:bg-white/5 hover:text-white"
          >
            <svg
              class="h-4 w-4 text-white/40"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              stroke-width="2"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"
              />
            </svg>
            {{ t('common.profileSettings') }}
          </button>

          <!-- Subscription Info -->
          <button
            @click="openSubscriptionModal"
            class="flex w-full items-center gap-3 px-4 py-2.5 text-sm text-white/80 transition-all duration-150 hover:bg-white/5 hover:text-white"
          >
            <svg
              class="h-4 w-4 text-white/40"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              stroke-width="2"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"
              />
            </svg>
            {{ t('header.subscription') }}
          </button>

          <!-- Admin Center — only for admin/superadmin roles -->
          <button
            v-if="isAdmin"
            @click="goToAdmin"
            class="flex w-full items-center gap-3 px-4 py-2.5 text-sm text-yellow-400/80 transition-all duration-150 hover:bg-white/5 hover:text-yellow-300"
          >
            <svg
              class="h-4 w-4 text-yellow-400/60"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              stroke-width="2"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
              />
            </svg>
            {{ t('header.adminCenter') }}
          </button>
        </div>

        <!-- Divider -->
        <hr class="border-white/5 my-1" />

        <!-- Logout -->
        <div class="py-1">
          <button
            @click="handleLogout"
            class="flex w-full items-center gap-3 px-4 py-2.5 text-sm text-white/70 transition-all duration-150 hover:bg-white/5 hover:text-red-400"
          >
            <svg
              class="h-4 w-4 text-white/40"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              stroke-width="2"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"
              />
            </svg>
            {{ t('header.logout') }}
          </button>
        </div>
      </div>
    </Transition>

    <!-- Subscription Info Modal -->
    <SubscriptionInfoModal
      :visible="showSubscriptionModal"
      @close="showSubscriptionModal = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useAuthStore } from '@/stores/auth'
import SubscriptionInfoModal from '@/components/subscription/SubscriptionInfoModal.vue'

const router = useRouter()
const { t } = useI18n()
const authStore = useAuthStore()

const isOpen = ref(false)
const containerRef = ref<HTMLElement | null>(null)
const showSubscriptionModal = ref(false)

// ── Computed display helpers ───────────────────────────────────────
const fullName = computed(() => {
  if (!authStore.user) return t('header.user')
  const { first_name, last_name } = authStore.user
  if (first_name && last_name) return `${first_name} ${last_name}`
  if (first_name) return first_name
  if (last_name) return last_name
  return authStore.user.email || t('header.user')
})

const email = computed(() => {
  return authStore.user?.email || ''
})

const initials = computed(() => {
  if (!authStore.user) return '?'
  const { first_name, last_name } = authStore.user
  if (first_name && last_name) {
    return (first_name[0] + last_name[0]).toUpperCase()
  }
  if (first_name) return first_name[0].toUpperCase()
  if (authStore.user.email) return authStore.user.email[0].toUpperCase()
  return '?'
})

// ── Admin check: only SUPERADMIN, ADMIN, MODERATOR ──
const isAdmin = computed(() => {
  const role = authStore.user?.role
  if (!role) return false
  // CRITICAL: Backend sends UPPERCASE roles (SUPERADMIN, ADMIN, MODERATOR)
  const adminRoles = ['SUPERADMIN', 'ADMIN', 'MODERATOR']
  return adminRoles.includes(role.toUpperCase())
})

// ── Navigate to Profile ────────────────────────────────────────────
function goToProfile() {
  isOpen.value = false
  router.push('/profile')
}

// ── Navigate to Admin Center ───────────────────────────────────────
function goToAdmin() {
  isOpen.value = false
  router.push('/admin')
}

// ── Open Subscription Info Modal ───────────────────────────────────
function openSubscriptionModal() {
  isOpen.value = false
  showSubscriptionModal.value = true
}

// ── Logout handler ─────────────────────────────────────────────────
function handleLogout() {
  isOpen.value = false
  authStore.logout()
}

// ── Close dropdown on outside click ───────────────────────────────
function handleOutsideClick(e: MouseEvent) {
  const target = e.target as HTMLElement
  if (isOpen.value && containerRef.value && !containerRef.value.contains(target)) {
    isOpen.value = false
  }
}

onMounted(() => document.addEventListener('mousedown', handleOutsideClick))
onUnmounted(() => document.removeEventListener('mousedown', handleOutsideClick))
</script>
