<script setup lang="ts">
/**
 * 顶部导航栏
 *
 * - 固定在顶部，白色背景 + 暖色底部阴影
 * - 左侧：Logo + "零食商城"
 * - 中间：分类导航菜单（从 /api/category/tree 加载一级分类）
 * - 右侧：搜索框 + 购物车图标 + 用户头像/登录按钮
 */
import { ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Search, ShoppingCart, User as UserIcon } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/modules/user'
import { getCategoryTreeApi } from '@/api/category'
import { getCartCountApi } from '@/api/cart'
import type { CategoryTreeNode } from '@/types/category'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const searchKeyword = ref('')
const categories = ref<CategoryTreeNode[]>([])
const cartCount = ref(0)

onMounted(async () => {
  try {
    categories.value = await getCategoryTreeApi()
  } catch {
    /* 分类加载失败不阻塞页面 */
  }
  fetchCartCount()
})

// 路由切换时刷新购物车数量
watch(() => route.path, () => {
  fetchCartCount()
})

async function fetchCartCount() {
  if (userStore.isLoggedIn) {
    try {
      cartCount.value = await getCartCountApi()
    } catch {
      cartCount.value = 0
    }
  } else {
    cartCount.value = 0
  }
}

function handleSearch() {
  const keyword = searchKeyword.value.trim()
  if (keyword) {
    router.push({ path: '/search', query: { q: keyword } })
  }
}

function goToCart() {
  router.push('/cart')
}

function goToUser() {
  if (userStore.isLoggedIn) {
    router.push('/user')
  } else {
    router.push('/login')
  }
}
</script>

<template>
  <header class="app-header">
    <div class="header-inner">
      <!-- Logo 区域 -->
      <div class="header-brand" @click="router.push('/')">
        <span class="brand-icon">🍪</span>
        <span class="brand-name">零食商城</span>
      </div>

      <!-- 分类导航 -->
      <nav class="header-nav">
        <router-link to="/" class="nav-item" active-class="active" exact>
          首页
        </router-link>
        <router-link
          v-for="cat in categories"
          :key="cat.id"
          :to="`/category/${cat.id}`"
          class="nav-item"
        >
          {{ cat.name }}
        </router-link>
        <router-link to="/seckill" class="nav-item nav-hot">
          限时抢购
        </router-link>
      </nav>

      <!-- 右侧操作区 -->
      <div class="header-actions">
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索零食..."
            :prefix-icon="Search"
            size="default"
            class="search-input"
            @keyup.enter="handleSearch"
          />
        </div>

        <el-badge :value="cartCount" :max="99" :show-zero="false" class="action-badge">
          <el-button
            :icon="ShoppingCart"
            circle
            class="action-btn"
            @click="goToCart"
          />
        </el-badge>

        <el-button
          v-if="userStore.isLoggedIn"
          :icon="UserIcon"
          circle
          class="action-btn"
          @click="goToUser"
        />
        <el-button
          v-else
          type="primary"
          round
          size="small"
          class="login-btn"
          @click="router.push('/login')"
        >
          登录
        </el-button>
      </div>
    </div>
  </header>
</template>

<style lang="scss" scoped>
.app-header {
  position: sticky;
  top: 0;
  z-index: 100;
  width: 100%;
  height: $header-height;
  background: rgba(255, 253, 249, 0.92);
  backdrop-filter: blur(12px);
  border-bottom: 2px solid $color-border;
  box-shadow: 0 2px 12px rgba(80, 40, 20, 0.06);
}

.header-inner {
  max-width: $container-max;
  margin: 0 auto;
  height: 100%;
  display: flex;
  align-items: center;
  gap: 28px;
  padding: 0 24px;
}

// Brand
.header-brand {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  flex-shrink: 0;

  .brand-icon {
    font-size: 28px;
  }

  .brand-name {
    font-family: 'Fredoka', 'PingFang SC', sans-serif;
    font-size: 20px;
    font-weight: 600;
    color: $color-primary;
  }
}

// Nav
.header-nav {
  display: flex;
  align-items: center;
  gap: 4px;
  flex: 1;

  .nav-item {
    padding: 8px 16px;
    border-radius: $radius-full;
    font-size: $font-size-md;
    font-weight: 500;
    color: $color-text-regular;
    cursor: pointer;
    transition: color 0.2s, background-color 0.2s;

    &:hover {
      color: $color-primary;
      background-color: $color-primary-light;
    }

    &.active {
      color: $color-primary;
      font-weight: 600;
    }

    &.nav-hot {
      color: $color-primary;
      position: relative;

      &::after {
        content: 'HOT';
        position: absolute;
        top: -4px;
        right: -4px;
        font-size: 9px;
        font-weight: 700;
        color: #fff;
        background: $color-primary;
        padding: 1px 5px;
        border-radius: 4px;
        line-height: 1.2;
      }
    }
  }
}

// Actions
.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.search-box {
  width: 200px;

  .search-input {
    :deep(.el-input__wrapper) {
      border-radius: $radius-full;
      background: $bg-page;
      border: 2px solid $color-border;
      box-shadow: none;
      padding: 2px 12px;
      transition: border-color 0.2s;

      &:hover,
      &.is-focus {
        border-color: $color-primary;
      }
    }
  }
}

.action-btn {
  width: 40px;
  height: 40px;
  border: 2px solid $color-border;
  color: $color-text-regular;
  transition: color 0.2s, border-color 0.2s, background-color 0.2s;

  &:hover {
    color: $color-primary;
    border-color: $color-primary;
    background-color: $color-primary-light;
  }
}

.login-btn {
  min-width: 72px;
  height: 40px;
  font-weight: 600;
  border: 2px solid $color-border-dark;
  background: linear-gradient(135deg, $color-primary, $color-cta);
  box-shadow: 0 3px 0 0 $color-primary-dark;
  transition: transform 0.2s, box-shadow 0.2s, filter 0.2s;

  &:hover {
    filter: brightness(1.04);
    transform: translateY(-1px);
  }

  &:active {
    box-shadow: 0 1px 0 0 $color-primary-dark;
    transform: translateY(2px);
  }
}

.action-badge {
  :deep(.el-badge__content) {
    background-color: $color-primary;
  }
}

// Responsive
@media (max-width: 1024px) {
  .header-nav {
    display: none;
  }
  .search-box {
    width: 160px;
  }
}

@media (max-width: 640px) {
  .search-box {
    display: none;
  }
}
</style>
