<template>
  <n-dropdown
    trigger="click"
    :options="userMenuOptions"
    @select="handleUserMenuSelect"
  >
    <n-button quaternary class="user-menu-trigger">
      <n-avatar
        round
        size="small"
        :src="user?.avatar"
        style="margin-right: 8px;"
      >
        {{ user?.username?.charAt(0).toUpperCase() }}
      </n-avatar>
      <div class="user-info">
        <span v-if="displayFullName" class="full-name">{{ displayFullName }}</span>
        <span v-else class="username-fallback">{{ user?.username }}</span>
        <span class="username-label">{{ displayFullName ? user?.username : '' }}</span>
      </div>
      <Icon icon="tabler:chevron-down" class="chevron-icon" />
    </n-button>
  </n-dropdown>
</template>

<script setup lang="ts">
import { computed, h } from 'vue'
import { useRouter } from 'vue-router'
import { NButton, NDropdown, NAvatar, useMessage } from 'naive-ui'
import { Icon } from '@iconify/vue'
import { useAuthStore } from '../stores/auth'
import { api } from '../api/common'
import { t } from '../i18n'

const router = useRouter()
const message = useMessage()
const authStore = useAuthStore()

const user = computed(() => authStore.user)

const displayFullName = computed(() => {
  const first = user.value?.first_name?.trim()
  const last = user.value?.last_name?.trim()
  if (first || last) {
    return [first, last].filter(Boolean).join(' ')
  }
  return ''
})

const PRESERVED_KEYS = ['appName', 'app.sidebar.collapsed', 'locale']

const userMenuOptions = computed(() => [
    {
      label: t('Workspace'),
      key: 'workspace',
      icon: () => h(Icon, { icon: 'tabler:menu-2' })
    },
    {
      label: t('Settings'),
      key: 'settings',
      icon: () => h(Icon, { icon: 'tabler:settings' })
    },
    {
      label: t('Clear Cache'),
      key: 'clear_cache',
      icon: () => h(Icon, { icon: 'tabler:refresh' })
    },
    {
      type: 'divider'
    },
    {
      label: t('Logout'),
      key: 'logout',
      icon: () => h(Icon, { icon: 'tabler:logout' })
    }
])

const handleUserMenuSelect = async (key: string) => {
  if (key === 'logout') {
    await authStore.logout()
    message.success(t('Logged out'))
    router.push('/login')
  } else if (key === 'workspace') {
    router.push('/app/workspace')
  } else if (key === 'settings') {
    const name = user.value?.name
    if (name) {
      router.push(`/app/user/${name}`)
    }
  } else if (key === 'clear_cache') {
    handleClearCache()
  }
}

async function handleClearCache() {
  try {
    const preserved = Object.fromEntries(
      PRESERVED_KEYS.map(k => [k, localStorage.getItem(k)] as const).filter(([, v]) => v !== null)
    )
    localStorage.clear()
    Object.entries(preserved).forEach(([k, v]) => localStorage.setItem(k, v!))
    
    const res = await api.call('jingrow.sessions.clear')
    message.info(res?.message || t('Cache Cleared'))
    window.location.reload()
  } catch (e: any) {
    message.error(e.message || t('Clear cache failed'))
  }
}
</script>

<style scoped>
.user-menu-trigger {
  display: flex;
  align-items: center;
  padding: 4px 10px 4px 4px;
  border-radius: 10px;
  height: auto;
  transition: background-color 0.2s ease;
}

.user-menu-trigger:hover {
  background-color: var(--n-color-hover, rgba(0, 0, 0, 0.06));
}

.user-menu-trigger > :deep(.n-avatar) {
  margin-right: 14px;
  flex-shrink: 0;
}

.user-menu-trigger > :deep(.n-icon) {
  margin-left: 2px;
}

.user-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  min-width: 0;
}

.full-name {
  font-weight: 500;
  font-size: 13px;
  color: var(--n-text-color, rgba(51, 51, 51, 1));
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 140px;
}

.username-label {
  font-size: 12px;
  color: var(--n-text-color-3, rgba(102, 102, 102, 0.8));
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 140px;
  font-weight: 400;
}

.username-fallback {
  font-weight: 500;
  font-size: 13px;
  color: var(--n-text-color, rgba(51, 51, 51, 1));
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 140px;
}

.chevron-icon {
  flex-shrink: 0;
  color: var(--n-text-color-3, rgba(102, 102, 102, 0.8));
  transition: transform 0.2s ease;
}

.user-menu-trigger:hover .chevron-icon {
  color: var(--n-text-color, rgba(51, 51, 51, 1));
}

/* 移动端隐藏用户信息文字 */
@media (max-width: 768px) {
  .user-info {
    display: none;
  }
  .user-menu-trigger {
    padding: 4px;
  }
}
</style>

