<template>
  <header class="fixed top-0 w-full z-50 glass-nav transition-all duration-300" id="main-header">
    <!-- 优化点1: 移动端高度减小 (h-16), 桌面端保持 h-20 -->
    <div class="max-w-7xl mx-auto px-4 md:px-6 h-16 md:h-20 flex items-center justify-between">
      <!-- Logo -->
      <div class="cursor-pointer group flex items-center gap-1" @click="goTo('/')">
        <span class="font-serif text-xl md:text-2xl italic tracking-wider text-white group-hover:text-art-accent transition-colors">{{ siteTitle || '年糕崽崽' }}</span>
        <span class="font-serif text-xl md:text-2xl italic tracking-wider text-art-accent group-hover:text-white transition-colors">.Blog</span>
      </div>

      <!-- Desktop Nav -->
      <nav class="hidden md:flex items-center gap-8 lg:gap-10">
        <button
            v-if="visibleMenus.includes('home')"
            @click="goTo('/')"
            class="nav-item text-sm font-medium tracking-wide text-art-muted hover:text-white transition-colors link-underline"
            :class="{ 'text-white after:w-full': activeNav === 'home' }"
        >
          首页
        </button>
        <button
            v-if="visibleMenus.includes('blog')"
            @click="goTo('/blog')"
            class="nav-item text-sm font-medium tracking-wide text-art-muted hover:text-white transition-colors link-underline"
            :class="{ 'text-white after:w-full': activeNav === 'blog' }"
        >
          思考
        </button>
        <button
            v-if="visibleMenus.includes('columns')"
            @click="goTo('/columns')"
            class="nav-item text-sm font-medium tracking-wide text-art-muted hover:text-white transition-colors link-underline"
            :class="{ 'text-white after:w-full': activeNav === 'columns' }"
        >
          专栏
        </button>
        <button
            v-if="visibleMenus.includes('works')"
            @click="goTo('/works')"
            class="nav-item text-sm font-medium tracking-wide text-art-muted hover:text-white transition-colors link-underline"
            :class="{ 'text-white after:w-full': activeNav === 'works' }"
        >
          作品
        </button>
        <button
            v-if="visibleMenus.includes('videos')"
            @click="goTo('/videos')"
            class="nav-item text-sm font-medium tracking-wide text-art-muted hover:text-white transition-colors link-underline"
            :class="{ 'text-white after:w-full': activeNav === 'videos' }"
        >
          视频
        </button>
        <button
            v-if="visibleMenus.includes('snippets')"
            @click="goTo('/snippets')"
            class="nav-item text-sm font-medium tracking-wide text-art-muted hover:text-white transition-colors link-underline"
            :class="{ 'text-white after:w-full': activeNav === 'snippets' }"
        >
          代码
        </button>
        <button
            v-if="visibleMenus.includes('about')"
            @click="goTo('/about')"
            class="nav-item text-sm font-medium tracking-wide text-art-muted hover:text-white transition-colors link-underline"
            :class="{ 'text-white after:w-full': activeNav === 'about' }"
        >
          关于
        </button>
      </nav>

      <!-- Desktop Actions -->
      <div class="hidden md:flex items-center gap-4">
        <a href="#" class="text-art-muted hover:text-white transition-colors"><Icon name="github" :size="20" /></a>
        <a href="/admin" target="_blank" class="text-art-muted hover:text-white transition-colors" title="后台管理">
          <Icon name="layout-dashboard" :size="20" />
        </a>
        <button
            v-if="visibleMenus.includes('services')"
            @click="goTo('/services')"
            class="px-5 py-2 text-xs font-bold tracking-widest uppercase border border-white/20 hover:border-art-accent hover:text-art-accent transition-all rounded-full"
        >
          合作
        </button>
      </div>

      <!-- Mobile Menu Button -->
      <button class="md:hidden text-white p-2 -mr-2 active:scale-95 transition-transform" @click="isMobileMenuOpen = true">
        <Icon name="menu" :size="24" />
      </button>
    </div>

    <!-- Mobile Drawer Menu (抽屉式) -->
    <!-- 优化点3: 使用 Teleport 传送到 body，确保不被父级遮挡，并实现抽屉动画 -->
    <Teleport to="body">
      <Transition name="fade">
        <div v-if="isMobileMenuOpen" class="fixed inset-0 z-[100] md:hidden" @click="closeMobileMenu">
          <!-- Backdrop -->
          <div class="absolute inset-0 bg-black/60 backdrop-blur-sm"></div>
        </div>
      </Transition>

      <Transition name="slide-right">
        <div v-if="isMobileMenuOpen" class="fixed top-0 right-0 bottom-0 w-64 bg-[#1a1a1a] z-[101] shadow-2xl border-l border-white/10 flex flex-col md:hidden">
          <!-- Drawer Header -->
          <div class="h-16 px-6 flex items-center justify-between border-b border-white/5">
             <span class="font-serif text-lg italic tracking-wider text-white">
               Menu
             </span>
            <button class="text-white/70 hover:text-white p-2 -mr-2" @click="closeMobileMenu">
              <Icon name="x" :size="24" />
            </button>
          </div>

          <!-- Drawer Content -->
          <div class="flex-1 overflow-y-auto py-6 px-6 space-y-6">
            <nav class="flex flex-col space-y-4">
              <button
                  v-if="visibleMenus.includes('home')"
                  @click="goTo('/')"
                  class="text-left text-base font-medium py-2 border-b border-white/5 transition-colors"
                  :class="activeNav === 'home' ? 'text-art-accent' : 'text-art-muted hover:text-white'"
              >
                首页
              </button>
              <button
                  v-if="visibleMenus.includes('blog')"
                  @click="goTo('/blog')"
                  class="text-left text-base font-medium py-2 border-b border-white/5 transition-colors"
                  :class="activeNav === 'blog' ? 'text-art-accent' : 'text-art-muted hover:text-white'"
              >
                思考
              </button>
              <button
                  v-if="visibleMenus.includes('columns')"
                  @click="goTo('/columns')"
                  class="text-left text-base font-medium py-2 border-b border-white/5 transition-colors"
                  :class="activeNav === 'columns' ? 'text-art-accent' : 'text-art-muted hover:text-white'"
              >
                专栏
              </button>
              <button
                  v-if="visibleMenus.includes('works')"
                  @click="goTo('/works')"
                  class="text-left text-base font-medium py-2 border-b border-white/5 transition-colors"
                  :class="activeNav === 'works' ? 'text-art-accent' : 'text-art-muted hover:text-white'"
              >
                作品
              </button>
              <button
                  v-if="visibleMenus.includes('videos')"
                  @click="goTo('/videos')"
                  class="text-left text-base font-medium py-2 border-b border-white/5 transition-colors"
                  :class="activeNav === 'videos' ? 'text-art-accent' : 'text-art-muted hover:text-white'"
              >
                视频
              </button>
              <button
                  v-if="visibleMenus.includes('snippets')"
                  @click="goTo('/snippets')"
                  class="text-left text-base font-medium py-2 border-b border-white/5 transition-colors"
                  :class="activeNav === 'snippets' ? 'text-art-accent' : 'text-art-muted hover:text-white'"
              >
                代码
              </button>
              <button
                  v-if="visibleMenus.includes('about')"
                  @click="goTo('/about')"
                  class="text-left text-base font-medium py-2 border-b border-white/5 transition-colors"
                  :class="activeNav === 'about' ? 'text-art-accent' : 'text-art-muted hover:text-white'"
              >
                关于
              </button>
            </nav>

            <div class="pt-6 border-t border-white/10 space-y-4">
              <div class="flex items-center gap-4">
                <a href="#" class="flex items-center gap-2 text-art-muted hover:text-white transition-colors text-sm">
                  <Icon name="github" :size="18" />
                  <span>GitHub</span>
                </a>
                <a href="/admin" target="_blank" class="flex items-center gap-2 text-art-muted hover:text-white transition-colors text-sm">
                  <Icon name="layout-dashboard" :size="18" />
                  <span>管理后台</span>
                </a>
              </div>
              <button
                  v-if="visibleMenus.includes('services')"
                  @click="goTo('/services')"
                  class="w-full py-3 text-xs font-bold tracking-widest uppercase border border-white/20 hover:bg-white/5 hover:border-art-accent hover:text-art-accent transition-all rounded-lg text-center text-white"
              >
                商业合作
              </button>
            </div>
          </div>
        </div>
      </Transition>
    </Teleport>
  </header>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { usePublicSettings } from '../composables/usePublicSettings'
import Icon from './Icon.vue'

const router = useRouter()
const route = useRoute()
const { cache, getStringSetting } = usePublicSettings()
const activeNav = ref('home')
const siteTitle = ref<string>('')
const visibleMenus = ref<string[]>(['home', 'blog', 'columns', 'works', 'videos', 'snippets', 'about', 'services'])
const isMobileMenuOpen = ref(false)

const closeMobileMenu = () => {
  isMobileMenuOpen.value = false
}

const updateActiveNav = () => {
  const path = route.path
  if (path === '/') activeNav.value = 'home'
  else if (path === '/blog' || path.startsWith('/blog/')) activeNav.value = 'blog'
  else if (path === '/columns' || path.startsWith('/columns/')) activeNav.value = 'columns'
  else if (path === '/categories' || path.startsWith('/categories/')) activeNav.value = 'categories'
  else if (path === '/works' || path.startsWith('/works/')) activeNav.value = 'works'
  else if (path === '/videos' || path.startsWith('/videos/')) activeNav.value = 'videos'
  else if (path === '/snippets') activeNav.value = 'snippets'
  else if (path === '/services') activeNav.value = 'services'
  else if (path === '/about') activeNav.value = 'about'
}

const applySettingsFromCache = () => {
  const title = getStringSetting('site_title')
  if (title) siteTitle.value = title

  const menusRaw = getStringSetting('visible_menus')
  if (menusRaw) {
    try {
      const parsed = JSON.parse(menusRaw)
      if (Array.isArray(parsed)) {
        visibleMenus.value = parsed
      }
    } catch {
      visibleMenus.value = menusRaw.split(',').map((m: string) => m.trim()).filter((m: string) => m)
    }
  }
}

onMounted(() => {
  updateActiveNav()
  applySettingsFromCache()
})

watch(cache, () => {
  applySettingsFromCache()
})

watch(
    () => route.path,
    () => {
      updateActiveNav()
    }
)

const goTo = (target: string) => {
  router.push(target)
  closeMobileMenu() // 跳转时关闭菜单
}

// 监听菜单状态，控制 body 滚动，防止抽屉打开时背景还能滚动
watch(isMobileMenuOpen, (isOpen) => {
  if (isOpen) {
    document.body.style.overflow = 'hidden'
  } else {
    document.body.style.overflow = ''
  }
})
</script>

<style scoped>
/* Fade Animation */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* Slide Right Animation */
.slide-right-enter-active,
.slide-right-leave-active {
  transition: transform 0.3s cubic-bezier(0.16, 1, 0.3, 1);
}

.slide-right-enter-from,
.slide-right-leave-to {
  transform: translateX(100%);
}
</style>