<template>
  <n-dropdown
    trigger="click"
    :options="userMenuOptions"
    @select="handleUserMenuSelect"
  >
    <n-button quaternary>
      <n-avatar
        round
        size="small"
        :src="user?.avatar"
      >
        {{ user?.username?.charAt(0).toUpperCase() }}
      </n-avatar>
      <span class="username">{{ user?.username }}</span>
      <Icon icon="tabler:chevron-down" />
    </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 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>
.username {
  margin-left: 8px;
  font-weight: 500;
}

/* 移动端隐藏用户名文字 */
@media (max-width: 768px) {
  .username {
    display: none;
  }
}
</style>

