<template>
  <div class="flex h-screen bg-art-admin-bg text-white overflow-hidden font-sans">
    <!-- Sidebar Navigation -->
    <aside 
      class="flex flex-col bg-art-admin-card border-r border-white/5 transition-all duration-300 z-20"
      :class="[isSidebarOpen ? 'w-64' : 'w-20']"
    >
      <!-- Logo Area -->
      <div class="h-16 flex items-center px-6 border-b border-white/5 shrink-0">
        <h1 class="font-serif italic text-xl tracking-wide truncate transition-all duration-300" :class="{ 'opacity-0': !isSidebarOpen }">
          Niangao<span class="text-art-accent">.Admin</span>
        </h1>
        <span v-if="!isSidebarOpen" class="absolute left-1/2 -translate-x-1/2 text-art-accent font-serif text-xl italic">N</span>
      </div>
      
      <!-- Nav Menu -->
      <nav class="flex-1 overflow-y-auto py-6 px-3 space-y-1 custom-scrollbar">
        <AdminMenuItem
          v-for="(item, index) in menuItems"
          :key="index"
          :item="item"
          :depth="0"
          :is-sidebar-open="isSidebarOpen"
          :is-active="isActive"
          @request-open-sidebar="openSidebar"
        />
      </nav>
      
      <!-- User Footer -->
      <div class="p-4 border-t border-white/5">
        <router-link
          to="/admin/profile"
          class="flex items-center gap-3 rounded-md p-1 -m-1 hover:bg-white/5 transition-colors"
          :class="{ 'justify-center': !isSidebarOpen }"
        >
           <div class="w-8 h-8 rounded-full bg-art-accent/10 flex items-center justify-center text-art-accent font-bold text-xs shrink-0 overflow-hidden">
             <img v-if="currentUser.avatar" :src="currentUser.avatar" :alt="currentUser.username" class="w-full h-full object-cover" />
             <span v-else>{{ currentUser.username?.charAt(0).toUpperCase() || 'A' }}</span>
           </div>
           <div class="min-w-0 transition-opacity duration-300" :class="{ 'opacity-0 w-0': !isSidebarOpen }">
             <p class="text-sm font-medium text-white truncate">{{ currentUser.username }}</p>
             <p class="text-xs text-art-muted truncate">个人中心</p>
           </div>
        </router-link>
      </div>
    </aside>

    <!-- Main Content Area -->
    <main class="flex-1 flex flex-col min-w-0 bg-art-admin-bg relative">
      <!-- Top Header -->
      <header class="h-16 bg-art-admin-bg border-b border-white/5 flex items-center justify-between px-6 shrink-0 z-10">
        <!-- Left: Toggle & Breadcrumb (Optional) -->
        <div class="flex items-center gap-4">
          <button 
            @click="toggleSidebar"
            class="p-2 -ml-2 text-art-muted hover:text-white hover:bg-white/5 rounded-md transition-colors"
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
          </button>
          <h2 class="text-sm font-medium text-white/80 hidden sm:block">{{ currentRouteTitle }}</h2>
        </div>

        <!-- Right: Actions -->
        <div class="flex items-center gap-3">
          <button 
            @click="refreshCurrentPage"
            class="p-2 text-art-muted hover:text-white hover:bg-white/5 rounded-full transition-colors"
            title="刷新当前页面"
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"></polyline><polyline points="1 20 1 14 7 14"></polyline><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path></svg>
          </button>
          
          <button class="p-2 text-art-muted hover:text-white hover:bg-white/5 rounded-full transition-colors relative">
             <span class="absolute top-2 right-2 w-2 h-2 bg-art-accent rounded-full border-2 border-art-admin-bg"></span>
             <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path><path d="M13.73 21a2 2 0 0 1-3.46 0"></path></svg>
          </button>
          
          <div class="relative" ref="dropdownRef">
            <button 
              @click="toggleUserDropdown"
              class="flex items-center gap-2 text-sm font-medium text-art-muted hover:text-white transition-colors"
            >
              <span>设置</span>
              <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="transition-transform duration-200" :class="{ 'rotate-180': isUserDropdownOpen }"><polyline points="6 9 12 15 18 9"></polyline></svg>
            </button>
            
            <!-- Dropdown -->
            <div 
              v-if="isUserDropdownOpen"
              class="absolute right-0 mt-2 w-48 bg-art-admin-card border border-white/10 rounded-lg shadow-xl py-1 z-50 origin-top-right animate-reveal"
            >
              <button @click="goToProfile" class="flex items-center gap-2 w-full px-4 py-2.5 text-sm text-art-muted hover:text-white hover:bg-white/5 text-left transition-colors">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>
                个人中心
              </button>
              <button @click="goToProfilePassword" class="flex items-center gap-2 w-full px-4 py-2.5 text-sm text-art-muted hover:text-white hover:bg-white/5 text-left transition-colors">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></svg>
                修改密码
              </button>
              <div class="h-px bg-white/5 my-1"></div>
              <button @click="handleLogout" class="flex items-center gap-2 w-full px-4 py-2.5 text-sm text-red-400 hover:bg-red-500/10 text-left transition-colors">
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path><polyline points="16 17 21 12 16 7"></polyline><line x1="21" y1="12" x2="9" y2="12"></line></svg>
                退出登录
              </button>
            </div>
          </div>
        </div>
      </header>

      <!-- Content Scroll Area -->
      <div class="flex-1 overflow-auto p-6 scroll-smooth custom-scrollbar">
        <div class="max-w-full mx-auto animate-reveal">
          <router-view />
        </div>
      </div>
    </main>
    <SessionExpiredModal />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useToast } from '../../composables/useToast'
import { useAuth } from '../../composables/useAuth'
import SessionExpiredModal from './SessionExpiredModal.vue'
import AdminMenuItem from './AdminMenuItem.vue'
import { getCurrentUser } from '../../services/api'
import { openActiveMenuAncestors, findRouteTitle, type MenuItem } from './adminMenuTypes'

const router = useRouter()
const route = useRoute()
const toast = useToast()
const { logout, scheduleExpiryCheck, getUser, isAuthenticated, setUser } = useAuth()
const isSidebarOpen = ref(true)
const currentUser = ref(getUser())

// Dropdown logic
const isUserDropdownOpen = ref(false)
const dropdownRef = ref<HTMLElement | null>(null)

const toggleUserDropdown = () => {
  isUserDropdownOpen.value = !isUserDropdownOpen.value
}

const closeDropdown = (e: MouseEvent) => {
  if (dropdownRef.value && !dropdownRef.value.contains(e.target as Node)) {
    isUserDropdownOpen.value = false
  }
}

const goToProfile = () => {
  router.push('/admin/profile')
  isUserDropdownOpen.value = false
}

const goToProfilePassword = () => {
  router.push({ path: '/admin/profile', hash: '#password' })
  isUserDropdownOpen.value = false
}

const refreshCurrentPage = () => {
  // 强制刷新当前路由页面
  router.go(0)
}

interface MenuItemWithState extends MenuItem {}

const menuItems = ref<MenuItemWithState[]>([
  {
    title: '概览',
    icon: '📊',
    path: '/admin/dashboard'
  },
  {
    title: '数据分析',
    icon: '📈',
    path: '/admin/analytics'
  },
  {
    title: '内容管理',
    icon: '📚',
    isOpen: true,
    children: [
      { title: '文章管理', path: '/admin/posts', icon: '📝' },
      { title: '分类管理', path: '/admin/categories', icon: '📂' },
      { title: '专栏管理', path: '/admin/columns', icon: '📚' },
      { title: '作品管理', path: '/admin/works', icon: '🎨' },
      {
        title: '视频管理',
        isOpen: false,
        children: [
          { title: '视频分类', path: '/admin/video-categories', icon: '📁' },
          { title: '视频专辑', path: '/admin/video-albums', icon: '📀' },
          { title: '视频列表', path: '/admin/videos', icon: '🎬' },
        ]
      },
      {
        title: '代码管理',
        isOpen: false,
        children: [
          { title: '代码片段', path: '/admin/snippets', icon: '💻' },
          { title: '代码分类', path: '/admin/code-types', icon: '🏷️' }
        ]
      },
      { title: '标签管理', path: '/admin/tags', icon: '🏷️' }
    ]
  },
  {
    title: '页面配置',
    icon: '🔧',
    isOpen: false,
    children: [
      { title: '关于页面', path: '/admin/about', icon: '👤' },
      { title: '客户评价', path: '/admin/testimonials', icon: '💬' },
      { title: '合作伙伴', path: '/admin/partners', icon: '🤝' }
    ]
  },
  {
    title: '业务中心',
    icon: '💼',
    isOpen: false,
    children: [
      { title: '合作咨询', path: '/admin/inquiries', icon: '📩' },
      { title: '邮箱配置', path: '/admin/email-suffixes', icon: '📧' }
    ]
  },
  {
    title: '用户权限',
    icon: '🛡️',
    isOpen: false,
    children: [
      { title: '用户管理', path: '/admin/users', icon: '👥' },
      { title: '角色管理', path: '/admin/roles', icon: '🔒' }
    ]
  },
  {
    title: '附件管理',
    icon: '📎',
    isOpen: false,
    children: [
      { title: '附件库', path: '/admin/attachments', icon: '📦' },
      { title: '附件分类管理', path: '/admin/attachment-categories', icon: '📂' },
      { title: 'OSS配置', path: '/admin/oss-configs', icon: '☁️' }
    ]
  },
  {
    title: '系统设置',
    icon: '⚙️',
    isOpen: false,
    children: [
      { title: '全局配置', path: '/admin/settings', icon: '🛠️' },
      { title: 'PPT 模板', path: '/admin/ppt-templates', icon: '📽️' },
      { title: '操作日志', path: '/admin/logs', icon: '📋' },
      { title: '访问日志', path: '/admin/access-logs', icon: '🌐' }
    ]
  }
])

const openSidebar = () => {
  if (!isSidebarOpen.value) {
    isSidebarOpen.value = true
  }
}

const toggleSidebar = () => {
  isSidebarOpen.value = !isSidebarOpen.value
}

const handleLogout = () => {
  logout()
  toast.showToast('退出登录成功', 'success')
}

// Helper to determine active state
const isActive = (path: string) => {
  return route.path === path || route.path.startsWith(path + '/')
}

// Get current route title for header
const currentRouteTitle = computed(() => {
  return findRouteTitle(menuItems.value, route.path) || '管理控制台'
})

// Check if user is authenticated
onMounted(() => {
  if (!isAuthenticated()) {
    router.push('/login')
    return
  }
  scheduleExpiryCheck()
  document.addEventListener('click', closeDropdown)
  openActiveMenuAncestors(menuItems.value, isActive)

  getCurrentUser()
    .then(user => {
      currentUser.value = user
      setUser(user)
    })
    .catch(() => {
      currentUser.value = getUser()
    })
})

watch(() => route.path, () => {
  openActiveMenuAncestors(menuItems.value, isActive)
})

onUnmounted(() => {
  document.removeEventListener('click', closeDropdown)
})
</script>

<style scoped>
/* Scoped styles replaced by Tailwind classes */
</style>
