<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">
        <template v-for="(item, index) in menuItems" :key="index">
          <!-- Parent Menu Item -->
          <div v-if="item.children">
            <div 
              class="flex items-center justify-between px-3 py-2.5 rounded-md cursor-pointer transition-colors duration-200 group mb-1"
              :class="[isParentActive(item) ? 'text-white' : 'text-art-muted hover:text-white hover:bg-white/5']"
              @click="toggleMenu(index)"
            >
              <div class="flex items-center gap-3 min-w-0">
                <span class="text-lg shrink-0 group-hover:text-art-accent transition-colors" :class="isParentActive(item) ? 'text-art-accent' : ''">{{ item.icon }}</span>
                <span class="text-sm font-medium truncate transition-opacity duration-300" :class="{ 'opacity-0 w-0': !isSidebarOpen }">{{ item.title }}</span>
              </div>
              <span 
                v-if="isSidebarOpen" 
                class="text-[10px] transition-transform duration-200 opacity-50 group-hover:opacity-100"
                :class="{ 'rotate-180': item.isOpen }"
              >▼</span>
            </div>
            
            <!-- Submenu -->
            <div 
              v-show="isSidebarOpen && item.isOpen" 
              class="ml-4 pl-4 border-l border-white/5 space-y-1 mb-2 overflow-hidden transition-all duration-300"
            >
              <router-link 
                v-for="(child, childIndex) in item.children" 
                :key="childIndex"
                :to="child.path"
                class="flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-all duration-200 relative group"
                active-class="text-art-accent bg-art-accent/5 font-medium"
                :class="!isActive(child.path) ? 'text-art-muted hover:text-white hover:bg-white/5' : ''"
              >
                <!-- Active Indicator Line -->
                <div v-if="isActive(child.path)" class="absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-4 bg-art-accent rounded-full"></div>
                
                <span class="truncate">{{ child.title }}</span>
              </router-link>
            </div>
          </div>
          
          <!-- Single Menu Item -->
          <router-link 
            v-else
            :to="item.path || ''" 
            class="flex items-center gap-3 px-3 py-2.5 rounded-md mb-1 transition-all duration-200 relative group"
            active-class="text-art-accent bg-art-accent/5"
            :class="!isActive(item.path || '') ? 'text-art-muted hover:text-white hover:bg-white/5' : ''"
          >
            <div v-if="isActive(item.path || '')" class="absolute left-0 top-1/2 -translate-y-1/2 w-0.5 h-5 bg-art-accent rounded-full"></div>
            <span class="text-lg shrink-0 group-hover:text-art-accent transition-colors">{{ item.icon }}</span>
            <span class="text-sm font-medium truncate transition-opacity duration-300" :class="{ 'opacity-0 w-0': !isSidebarOpen }">{{ item.title }}</span>
          </router-link>
        </template>
      </nav>
      
      <!-- User Footer -->
      <div class="p-4 border-t border-white/5">
        <div class="flex items-center gap-3">
           <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">
             {{ currentUser.username?.charAt(0).toUpperCase() || 'A' }}
           </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">Administrator</p>
           </div>
        </div>
      </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="handleChangePassword" 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>
  </div>
</template>

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

const router = useRouter()
const route = useRoute()
const toast = useToast()
const isSidebarOpen = ref(true)
const currentUser = ref(JSON.parse(localStorage.getItem('user') || '{}'))

// 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 handleChangePassword = () => {
  toast.showToast('功能开发中...', 'success')
  isUserDropdownOpen.value = false
}

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

interface MenuItem {
  title: string
  icon: string
  path?: string
  children?: { title: string; path: string; icon: string }[]
  isOpen?: boolean
}

const menuItems = ref<MenuItem[]>([
  {
    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: '代码片段', path: '/admin/snippets', 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: '操作日志', path: '/admin/logs', icon: '📋' }
    ]
  }
])

const toggleMenu = (index: number) => {
  if (!isSidebarOpen.value) {
    isSidebarOpen.value = true
    // Wait for transition
    setTimeout(() => {
       menuItems.value[index].isOpen = !menuItems.value[index].isOpen
    }, 100)
  } else {
    menuItems.value[index].isOpen = !menuItems.value[index].isOpen
  }
}

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

const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  toast.showToast('退出登录成功', 'success')
  router.push('/login')
}

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

const isParentActive = (item: MenuItem) => {
  if (item.path && isActive(item.path)) return true
  if (item.children) {
    return item.children.some(child => isActive(child.path))
  }
  return false
}

// Get current route title for header
const currentRouteTitle = computed(() => {
  // Simple logic: find matching menu item title
  for (const item of menuItems.value) {
    if (item.path === route.path) return item.title
    if (item.children) {
      const child = item.children.find(c => c.path === route.path)
      if (child) return `${item.title} / ${child.title}`
    }
  }
  return '管理控制台'
})

// Check if user is authenticated
onMounted(() => {
  const token = localStorage.getItem('token')
  if (!token) {
    router.push('/login')
  }
  document.addEventListener('click', closeDropdown)
  
  // Auto open menu based on current route
  menuItems.value.forEach(item => {
    if (item.children && item.children.some(child => isActive(child.path))) {
      item.isOpen = true
    }
  })
})

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

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