<script setup>
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  User,
  Setting,
  SwitchButton,
  ChatDotRound,
  Promotion,
  Sunny,
  Moon,
} from '@element-plus/icons-vue'
import request from '../utils/request'
import { useUserStore } from '../stores/userStore'
import { openAgentDrawer } from '../stores/uiShellStore'
import { useHudTheme } from '../composables/useHudTheme'
import {
  GITCC_COMMUNITY_URL,
  GITCC_LOGO_URL,
  PRODUCT_TITLE,
  PRODUCT_TAGLINE,
} from '../shellConstants'

const requestBaseURL = request.defaults.baseURL
const router = useRouter()
const { userInfo, userLoading } = useUserStore()
const { theme, toggleTheme } = useHudTheme()

const goToUserCenter = () => {
  router.push('/user-center')
}

const handleLogout = async () => {
  try {
    const data = await request.post('/user/logout')
    console.info('【登出响应数据】', data)
    const operation = data.operation
    if (operation?.status === 'SUCCESS') {
      ElMessage.success({ message: '【登出成功】', duration: 3000 })
    }
  } catch (error) {
    console.warning('【登出警告】', error)
    ElMessage.warning({
      message: '【登出警告】登出可能未完全成功，但您已在本地退出',
      duration: 4000,
    })
  } finally {
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
    localStorage.removeItem('login_user')
    router.push('/login')
  }
}

const openCommunity = () => {
  window.open(GITCC_COMMUNITY_URL, '_blank', 'noopener,noreferrer')
}
</script>

<template>
  <header class="hud-top-chrome">
    <div class="hud-top-chrome-inner">
      <div class="brand">
        <img
          :src="GITCC_LOGO_URL"
          :alt="PRODUCT_TITLE"
          class="brand-mark"
          width="40"
          height="40"
        />
        <div class="brand-text">
          <span class="name">{{ PRODUCT_TITLE }}</span>
          <span class="tag">{{ PRODUCT_TAGLINE }}</span>
        </div>
      </div>

      <div class="actions" v-if="userInfo && !userLoading">
        <el-tooltip content="GitCC 门户（浏览器跳转）" placement="bottom">
          <el-button class="hud-btn-ghost" @click="openCommunity" :icon="Promotion">开源社区</el-button>
        </el-tooltip>
        <el-button type="primary" class="hud-btn-primary" @click="openAgentDrawer" :icon="ChatDotRound">
          智能助手
        </el-button>
        <el-button class="hud-btn-ghost" circle @click="toggleTheme" :title="theme === 'dark' ? '浅色' : '深色'">
          <el-icon><Moon v-if="theme === 'light'" /><Sunny v-else /></el-icon>
        </el-button>
        <el-dropdown trigger="click">
          <div class="user-chip">
            <el-avatar :size="36" :src="userInfo.avatar_path ? `${requestBaseURL}/file/${userInfo.avatar_path}` : ''">
              <el-icon><User /></el-icon>
            </el-avatar>
            <span class="uname">{{ userInfo.username }}</span>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="goToUserCenter">
                <el-icon><Setting /></el-icon>
                <span>个人中心</span>
              </el-dropdown-item>
              <el-dropdown-item divided @click="handleLogout">
                <el-icon><SwitchButton /></el-icon>
                <span>退出登录</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>

      <div v-else-if="userLoading" class="sk">
        <el-skeleton style="width: 220px" :rows="1" animated />
      </div>
    </div>
  </header>
</template>

<style scoped>
.brand {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
}
.brand-mark {
  border-radius: 10px;
  flex-shrink: 0;
  box-shadow: 0 0 0 1px color-mix(in srgb, var(--primary) 25%, transparent);
}
.brand-text {
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0;
}
.name {
  font-weight: 800;
  font-size: 1.05rem;
  color: var(--foreground);
  letter-spacing: -0.02em;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.tag {
  font-size: 0.72rem;
  color: var(--muted);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.actions {
  display: flex;
  align-items: center;
  gap: 10px;
}
.hud-btn-ghost {
  border-color: color-mix(in srgb, var(--primary) 32%, var(--border));
  color: var(--foreground);
  background: color-mix(in srgb, var(--card-solid) 65%, transparent);
}
.hud-btn-primary {
  background: linear-gradient(180deg, color-mix(in srgb, var(--primary) 100%, #000), var(--primary));
  border-color: color-mix(in srgb, var(--primary) 80%, #000);
  box-shadow: 0 6px 20px color-mix(in srgb, var(--primary) 35%, transparent);
}
.hud-btn-primary:active {
  transform: translateY(1px) scale(0.98);
  filter: brightness(0.95);
}
.user-chip {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 6px 10px;
  border-radius: 999px;
  background: color-mix(in srgb, var(--foreground) 5%, transparent);
  border: 1px solid var(--border);
  transition: background 0.2s, box-shadow 0.2s;
}
.user-chip:hover {
  background: color-mix(in srgb, var(--primary) 10%, transparent);
  box-shadow: 0 0 0 1px color-mix(in srgb, var(--primary) 25%, transparent);
}
.uname {
  font-size: 0.9rem;
  font-weight: 600;
  color: var(--foreground);
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.sk {
  width: 220px;
}
@media (max-width: 900px) {
  .tag {
    display: none;
  }
}
@media (max-width: 640px) {
  .hud-btn-ghost:not(.is-circle) :deep(span) {
    display: none;
  }
}
</style>
