<template>
  <header class="app-header">
    <router-link class="brand" to="/">
      <span class="brand-mark">EC</span>
      <span>EasyCode</span>
    </router-link>

    <nav class="nav">
      <router-link to="/">工作台</router-link>
      <router-link to="/generate">生成项目</router-link>
      <router-link to="/source-store">源码库</router-link>
      <router-link to="/projects">我的项目</router-link>
    </nav>

    <div class="actions">
      <template v-if="token">
        <span class="user-name">{{ displayName }}</span>
        <el-button :icon="SwitchButton" @click="handleLogout">退出</el-button>
      </template>
      <template v-else>
        <el-button @click="router.push('/login')">登录</el-button>
        <el-button type="primary" @click="router.push('/register')">注册</el-button>
      </template>
    </div>
  </header>
</template>

<script setup>
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { SwitchButton } from '@element-plus/icons-vue'
import { logout } from '@/api/auth'
import { getToken, getUser, removeToken } from '@/utils/auth'

const router = useRouter()
const route = useRoute()
const token = computed(() => {
  route.fullPath
  return getToken()
})
const user = computed(() => {
  route.fullPath
  return getUser()
})
const displayName = computed(() => user.value?.nickName || user.value?.userName || '已登录')

async function handleLogout() {
  try {
    await logout()
  } finally {
    removeToken()
    router.push('/')
  }
}
</script>

<style scoped lang="scss">
.app-header {
  position: sticky;
  top: 0;
  z-index: 10;
  display: grid;
  grid-template-columns: auto 1fr auto;
  align-items: center;
  gap: 28px;
  height: 64px;
  padding: 0 28px;
  border-bottom: 1px solid #dfe5ee;
  background: rgba(255, 255, 255, 0.94);
  backdrop-filter: blur(12px);
}

.brand {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  color: #111827;
  font-size: 18px;
  font-weight: 700;
}

.brand-mark {
  display: inline-grid;
  width: 34px;
  height: 34px;
  place-items: center;
  border-radius: 8px;
  color: #ffffff;
  background: #2563eb;
  font-size: 13px;
}

.nav {
  display: flex;
  align-items: center;
  gap: 20px;
  color: #4b5563;
  font-size: 14px;

  .router-link-active {
    color: #1d4ed8;
    font-weight: 700;
  }
}

.actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-name {
  color: #475467;
  font-size: 14px;
}

@media (max-width: 720px) {
  .app-header {
    grid-template-columns: 1fr auto;
    height: auto;
    min-height: 64px;
    padding: 12px;
  }

  .nav {
    order: 3;
    grid-column: 1 / -1;
  }
}
</style>
