<script setup lang="ts">
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '../stores/auth';

const { t } = useI18n();
const auth = useAuthStore();
const router = useRouter();
const open = ref(false);

const initial = computed(() => {
  const name = auth.user?.username ?? '?';
  return name.charAt(0).toUpperCase();
});

function toggle() {
  open.value = !open.value;
}

function close() {
  open.value = false;
}

function goEdit() {
  close();
  router.push('/profile/edit');
}

function logout() {
  close();
  auth.logout();
  router.push('/login');
}
</script>

<template>
  <div class="avatar-wrap">
    <button type="button" class="avatar-btn" :aria-expanded="open" @click="toggle">
      <span class="avatar-letter">{{ initial }}</span>
    </button>

    <div v-if="open" class="avatar-menu">
      <div class="menu-user">{{ auth.user?.username }}</div>
      <button type="button" class="menu-item" @click="goEdit">{{ t('profile.edit') }}</button>
      <button type="button" class="menu-item danger" @click="logout">{{ t('auth.logout') }}</button>
    </div>

    <div v-if="open" class="backdrop" @click="close" />
  </div>
</template>

<style scoped>
.avatar-wrap {
  position: relative;
  z-index: 130;
}

.avatar-btn {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  border: 1px solid var(--border-gold-soft);
  background: linear-gradient(145deg, #2a2210, #141008);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  flex-shrink: 0;
}

.avatar-letter {
  font-size: 13px;
  font-weight: 800;
  color: var(--primary-light);
}

.avatar-menu {
  position: absolute;
  top: calc(100% + 8px);
  right: 0;
  min-width: 168px;
  padding: 8px 0;
  border: 1px solid var(--border);
  border-radius: var(--radius-sm);
  background: #141414;
  box-shadow: var(--shadow);
  z-index: 140;
}

.menu-user {
  padding: 8px 14px 10px;
  font-size: 13px;
  font-weight: 800;
  color: var(--primary-light);
  border-bottom: 1px solid var(--border);
  margin-bottom: 4px;
}

.menu-item {
  width: 100%;
  text-align: left;
  padding: 10px 14px;
  background: none;
  color: var(--text);
  font-size: 14px;
  font-weight: 600;
}

.menu-item:hover {
  background: rgba(255, 255, 255, 0.04);
}

.menu-item.danger {
  color: var(--danger);
}

.backdrop {
  position: fixed;
  inset: 0;
  z-index: 120;
}
</style>
