<template>
  <div class="app-wrapper">
    <!-- 自定义标题栏 -->
    <div class="title-bar">
      <div class="title-bar-drag">
        <div class="title-bar-logo">
          <svg class="logo-icon" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
            <defs>
              <linearGradient id="titlebar-gradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:#4f8cff"/>
                <stop offset="100%" style="stop-color:#6366f1"/>
              </linearGradient>
            </defs>
            <rect x="32" y="32" width="448" height="448" rx="96" fill="url(#titlebar-gradient)"/>
            <circle cx="256" cy="256" r="100" fill="#fff" opacity="0.95"/>
            <path d="M 228 190 L 228 322 L 330 256 Z" fill="url(#titlebar-gradient)"/>
            <circle cx="136" cy="160" r="10" fill="#fff" opacity="0.7"/>
            <circle cx="376" cy="160" r="10" fill="#fff" opacity="0.7"/>
            <circle cx="136" cy="352" r="10" fill="#fff" opacity="0.7"/>
            <circle cx="376" cy="352" r="10" fill="#fff" opacity="0.7"/>
          </svg>
          <span class="logo-text">多平台媒体管理系统</span>
        </div>
      </div>
      <div class="window-controls">
        <button class="window-btn minimize" @click="handleMinimize" title="最小化">
          <svg viewBox="0 0 12 12"><rect y="5" width="12" height="2" fill="currentColor"/></svg>
        </button>
        <button class="window-btn maximize" @click="handleMaximize" :title="isMaximized ? '还原' : '最大化'">
          <svg v-if="isMaximized" viewBox="0 0 12 12">
            <rect x="1.5" y="3" width="7" height="7" stroke="currentColor" stroke-width="1.5" fill="none"/>
            <path d="M3.5 3V1.5H11V9H9.5" stroke="currentColor" stroke-width="1.5" fill="none"/>
          </svg>
          <svg v-else viewBox="0 0 12 12">
            <rect x="1" y="1" width="10" height="10" stroke="currentColor" stroke-width="1.5" fill="none"/>
          </svg>
        </button>
        <button class="window-btn close" @click="handleClose" @contextmenu.prevent="showCloseMenu" title="关闭 (右键退出)">
          <svg viewBox="0 0 12 12">
            <path d="M1 1L11 11M1 11L11 1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
          </svg>
        </button>
        
        <!-- 关闭按钮右键菜单 -->
        <div v-if="closeMenuVisible" class="close-context-menu" :style="{ left: closeMenuX + 'px', top: closeMenuY + 'px' }">
          <div class="menu-item" @click="handleMinimizeToTray">
            <span>最小化到托盘</span>
          </div>
          <div class="menu-item danger" @click="handleQuitApp">
            <span>退出应用</span>
          </div>
        </div>
      </div>
    </div>
    
    <el-container class="main-layout">
      <!-- 侧边栏 -->
      <el-aside :width="isCollapsed ? '64px' : '200px'" class="sidebar" :class="{ 'is-collapsed': isCollapsed }">
        <div class="sidebar-header">
          <svg class="app-logo" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
            <defs>
              <linearGradient id="logo-gradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:#4f8cff"/>
                <stop offset="100%" style="stop-color:#6366f1"/>
              </linearGradient>
            </defs>
            <rect x="32" y="32" width="448" height="448" rx="96" fill="url(#logo-gradient)"/>
            <circle cx="256" cy="256" r="100" fill="#fff" opacity="0.95"/>
            <path d="M 228 190 L 228 322 L 330 256 Z" fill="url(#logo-gradient)"/>
            <circle cx="136" cy="160" r="10" fill="#fff" opacity="0.7"/>
            <circle cx="376" cy="160" r="10" fill="#fff" opacity="0.7"/>
            <circle cx="136" cy="352" r="10" fill="#fff" opacity="0.7"/>
            <circle cx="376" cy="352" r="10" fill="#fff" opacity="0.7"/>
          </svg>
          <span class="sidebar-title">媒体管理</span>
        </div>
      
      <el-menu
        :default-active="activeMenuPath"
        class="sidebar-menu"
        :collapse="isCollapsed"
        :collapse-transition="false"
        background-color="transparent"
        text-color="#64748b"
        active-text-color="#4f8cff"
        @select="handleMenuSelect"
      >
        <el-menu-item index="/">
          <el-icon><DataAnalysis /></el-icon>
          <span class="menu-title">数据看板</span>
        </el-menu-item>
        
        <el-menu-item index="/accounts">
          <el-icon><User /></el-icon>
          <span class="menu-title">账号管理</span>
        </el-menu-item>
        
        <el-menu-item index="/works">
          <el-icon><Film /></el-icon>
          <span class="menu-title">作品管理</span>
        </el-menu-item>
        
        <el-menu-item index="/publish">
          <el-icon><Upload /></el-icon>
          <span class="menu-title">发布管理</span>
        </el-menu-item>
        
        <el-menu-item index="/schedule">
          <el-icon><Clock /></el-icon>
          <span class="menu-title">定时任务</span>
        </el-menu-item>
        
        <el-sub-menu index="/analytics">
          <template #title>
            <el-icon><TrendCharts /></el-icon>
            <span class="menu-title">数据分析</span>
          </template>
          <el-menu-item index="/analytics/overview">
            <span class="sub-menu-title">数据总览</span>
          </el-menu-item>
          <el-menu-item index="/analytics/platform">
            <span class="sub-menu-title">平台数据</span>
          </el-menu-item>
          <el-menu-item index="/analytics/account">
            <span class="sub-menu-title">账号数据</span>
          </el-menu-item>
          <el-menu-item index="/analytics/work">
            <span class="sub-menu-title">作品数据</span>
          </el-menu-item>
        </el-sub-menu>
        
        <el-menu-item index="/settings" v-if="authStore.isAdmin">
          <el-icon><Setting /></el-icon>
          <span class="menu-title">系统设置</span>
        </el-menu-item>
      </el-menu>
    </el-aside>
    
    <el-container class="main-container">
      <!-- 合并的头部和标签页栏 -->
      <div class="header-tabs-bar">
        <!-- 左侧：折叠按钮 + 标签页 -->
        <div class="header-tabs-left">
          <span class="collapse-btn" @click="isCollapsed = !isCollapsed">
            <svg v-if="!isCollapsed" class="icon-svg" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
              <path fill="currentColor" d="M896 192H128a64 64 0 0 0-64 64v512a64 64 0 0 0 64 64h768a64 64 0 0 0 64-64V256a64 64 0 0 0-64-64zm-32 544H320V288h544v448z"/>
              <path fill="currentColor" d="M416 480 288 352v256l128-128z"/>
            </svg>
            <svg v-else class="icon-svg" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
              <path fill="currentColor" d="M128 192h768a64 64 0 0 1 64 64v512a64 64 0 0 1-64 64H128a64 64 0 0 1-64-64V256a64 64 0 0 1 64-64zm32 64v448h544V256H160z"/>
              <path fill="currentColor" d="M608 480 736 352v256L608 480z"/>
            </svg>
          </span>
          
          <!-- 标签页 -->
          <el-tabs 
            v-model="tabsStore.activeTabId" 
            type="card" 
            class="header-tabs"
            @tab-remove="handleTabRemove"
            @tab-click="handleTabClick"
            @contextmenu.prevent="handleContextMenu"
          >
            <el-tab-pane 
              v-for="tab in tabsStore.tabs" 
              :key="tab.id" 
              :name="tab.id"
              :closable="tab.closable !== false"
            >
              <template #label>
                <span class="tab-label" @contextmenu.prevent.stop="(e) => showTabContextMenu(e, tab)">
                  <el-icon class="tab-icon">
                    <Monitor v-if="tab.type === 'browser'" />
                    <component v-else :is="getTabIcon(tab.icon)" />
                  </el-icon>
                  <span class="tab-title">{{ tab.title }}</span>
                </span>
              </template>
            </el-tab-pane>
          </el-tabs>
        </div>
        
        <!-- 右侧：操作按钮和用户信息 -->
        <div class="header-tabs-right">
          <!-- 任务队列指示器 -->
          <el-badge 
            :value="taskStore.activeTaskCount" 
            :hidden="!taskStore.hasActiveTasks"
            class="icon-badge"
          >
            <span class="header-icon-btn" :class="{ 'is-running': taskStore.runningTasks.length > 0 }" @click="taskStore.openDialog">
              <!-- 加载中图标 -->
              <svg v-if="taskStore.runningTasks.length > 0" class="icon-svg spinning" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                <path fill="currentColor" d="M512 64a32 32 0 0 1 32 32v192a32 32 0 0 1-64 0V96a32 32 0 0 1 32-32zm0 640a32 32 0 0 1 32 32v192a32 32 0 1 1-64 0V736a32 32 0 0 1 32-32zm448-192a32 32 0 0 1-32 32H736a32 32 0 1 1 0-64h192a32 32 0 0 1 32 32zM192 512a32 32 0 0 1-32 32H96a32 32 0 0 1 0-64h64a32 32 0 0 1 32 32z"/>
              </svg>
              <!-- 任务列表图标 -->
              <svg v-else class="icon-svg" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                <path fill="currentColor" d="M128 320v576h576V320H128zm-32-64h640a32 32 0 0 1 32 32v640a32 32 0 0 1-32 32H96a32 32 0 0 1-32-32V288a32 32 0 0 1 32-32z"/>
                <path fill="currentColor" d="M960 128v576h-64V160H320v-64h608a32 32 0 0 1 32 32z"/>
                <path fill="currentColor" d="M256 672h320v64H256zm0-192h320v64H256z"/>
              </svg>
            </span>
          </el-badge>

          <!-- 评论管理 -->
          <el-badge :value="unreadComments" :hidden="!unreadComments" class="icon-badge">
            <span class="header-icon-btn" @click="openPage('/comments')">
              <!-- 消息图标 -->
              <svg class="icon-svg" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                <path fill="currentColor" d="M128 224v512a64 64 0 0 0 64 64h640a64 64 0 0 0 64-64V224a64 64 0 0 0-64-64H192a64 64 0 0 0-64 64zm0-64h768a128 128 0 0 1 128 128v512a128 128 0 0 1-128 128H192A128 128 0 0 1 64 800V288a128 128 0 0 1 128-128z"/>
                <path fill="currentColor" d="M789.504 199.04 511.616 450.944 233.728 199.04a32 32 0 1 0-43.456 46.912l307.2 279.04a32 32 0 0 0 43.136 0l307.2-279.04a32 32 0 0 0-43.456-46.912z"/>
              </svg>
            </span>
          </el-badge>
          
          <el-dropdown @command="handleCommand">
            <div class="user-info">
              <el-avatar :size="28" :src="authStore.user?.avatarUrl || undefined">
                {{ authStore.user?.nickname?.[0] || authStore.user?.username?.[0] }}
              </el-avatar>
              <span class="username">{{ authStore.user?.nickname || authStore.user?.username }}</span>
              <svg class="arrow-icon" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                <path fill="currentColor" d="M831.872 340.864 512 652.672 192.128 340.864a30.592 30.592 0 0 0-42.752 0 29.12 29.12 0 0 0 0 41.6L489.664 714.24a32 32 0 0 0 44.672 0l340.288-331.712a29.12 29.12 0 0 0 0-41.728 30.592 30.592 0 0 0-42.752 0z"/>
              </svg>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                <el-dropdown-item command="server">服务器设置</el-dropdown-item>
                <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      
      <!-- 主内容区域 - 标签页内容 -->
      <el-main class="main-content">
        <div class="tab-contents">
          <!-- 页面类型标签页 -->
          <template v-for="tab in tabsStore.tabs" :key="tab.id">
            <div 
              v-show="tabsStore.activeTabId === tab.id" 
              class="tab-content-item"
            >
              <!-- 浏览器标签页 -->
              <BrowserTab 
                v-if="tab.type === 'browser'" 
                :tab="tab"
                @account-saved="handleAccountSaved"
                @close="tabsStore.closeTab(tab.id)"
              />
              <!-- 页面标签页 -->
              <component 
                v-else-if="tab.type === 'page' && getPageComponent(tab.path || '')"
                :is="getPageComponent(tab.path || '')"
                :key="tab.path"
              />
            </div>
          </template>
          
          <!-- 空状态 -->
          <el-empty 
            v-if="tabsStore.tabs.length === 0" 
            description="请从左侧菜单选择页面"
            class="empty-content"
          />
        </div>
      </el-main>
    </el-container>

    <!-- 全局任务进度弹框 -->
    <TaskProgressDialog />
    
    <!-- 验证码输入弹框 -->
    <CaptchaDialog
      v-model="taskStore.showCaptchaDialog"
      :captcha-task-id="taskStore.captchaTaskId"
      :type="taskStore.captchaType"
      :phone="taskStore.captchaPhone"
      :image-base64="taskStore.captchaImageBase64"
      @submit="taskStore.submitCaptcha"
      @cancel="taskStore.cancelCaptcha"
    />
    
    <!-- 标签页右键菜单 -->
    <div 
      v-show="contextMenu.visible" 
      class="context-menu"
      :style="{ left: contextMenu.x + 'px', top: contextMenu.y + 'px' }"
    >
      <div class="context-menu-item" @click="handleRefreshTab">
        <el-icon><Refresh /></el-icon>
        刷新
      </div>
      <div 
        class="context-menu-item" 
        :class="{ disabled: !contextMenu.tab?.closable }"
        @click="handleCloseTab"
      >
        <el-icon><Close /></el-icon>
        关闭
      </div>
      <div class="context-menu-item" @click="handleCloseOtherTabs">
        <el-icon><FolderDelete /></el-icon>
        关闭其他
      </div>
      <div class="context-menu-item" @click="handleCloseRightTabs">
        <el-icon><Right /></el-icon>
        关闭右侧
      </div>
      <div class="context-menu-item" @click="handleCloseAllTabs">
        <el-icon><Delete /></el-icon>
        关闭所有
      </div>
    </div>
  </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch, defineAsyncComponent, shallowRef, markRaw } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { useTaskQueueStore } from '@/stores/taskQueue';
import { useTabsStore, type Tab } from '@/stores/tabs';
import { ElMessageBox } from 'element-plus';
// 图标由 main.ts 全局注册，这里只导入用于 iconComponents 映射的组件
import { 
  Loading, DocumentCopy, Close, Refresh, Delete, Right, FolderDelete,
  DataAnalysis, User, Film, Upload, Clock, Setting, Document, Monitor,
  TrendCharts, ChatDotRound, Message, Fold, Expand, ArrowDown,
} from '@element-plus/icons-vue';
import TaskProgressDialog from '@/components/TaskProgressDialog.vue';
import CaptchaDialog from '@/components/CaptchaDialog.vue';
import BrowserTab from '@/components/BrowserTab.vue';

// 动态导入页面组件
const pageComponents = shallowRef<Record<string, ReturnType<typeof defineAsyncComponent>>>({
  '/': defineAsyncComponent(() => import('@/views/Dashboard/index.vue')),
  '/accounts': defineAsyncComponent(() => import('@/views/Accounts/index.vue')),
  '/works': defineAsyncComponent(() => import('@/views/Works/index.vue')),
  '/publish': defineAsyncComponent(() => import('@/views/Publish/index.vue')),
  '/comments': defineAsyncComponent(() => import('@/views/Comments/index.vue')),
  '/schedule': defineAsyncComponent(() => import('@/views/Schedule/index.vue')),
  '/analytics/overview': defineAsyncComponent(() => import('@/views/Analytics/Overview/index.vue')),
  '/analytics/platform': defineAsyncComponent(() => import('@/views/Analytics/Platform/index.vue')),
  '/analytics/account': defineAsyncComponent(() => import('@/views/Analytics/Account/index.vue')),
  '/analytics/work': defineAsyncComponent(() => import('@/views/Analytics/Work/index.vue')),
  '/settings': defineAsyncComponent(() => import('@/views/Settings/index.vue')),
  '/profile': defineAsyncComponent(() => import('@/views/Profile/index.vue')),
});

// 图标映射 - 使用 markRaw 避免响应式警告
const iconComponents: Record<string, typeof DataAnalysis> = {
  DataAnalysis: markRaw(DataAnalysis),
  User: markRaw(User),
  Film: markRaw(Film),
  Upload: markRaw(Upload),
  Clock: markRaw(Clock),
  Setting: markRaw(Setting),
  Document: markRaw(Document),
  Monitor: markRaw(Monitor),
  ChatDotRound: markRaw(ChatDotRound),
  TrendCharts: markRaw(TrendCharts),
};

const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();
const taskStore = useTaskQueueStore();
const tabsStore = useTabsStore();

// 窗口状态
const isMaximized = ref(false);

// 关闭按钮右键菜单
const closeMenuVisible = ref(false);
const closeMenuX = ref(0);
const closeMenuY = ref(0);

// 窗口控制函数
function handleMinimize() {
  window.electronAPI?.minimizeWindow();
}

function handleMaximize() {
  window.electronAPI?.maximizeWindow();
}

function handleClose() {
  window.electronAPI?.closeWindow();
}

// 显示关闭按钮右键菜单
function showCloseMenu(e: MouseEvent) {
  closeMenuX.value = e.clientX;
  closeMenuY.value = e.clientY;
  closeMenuVisible.value = true;
}

// 最小化到托盘
function handleMinimizeToTray() {
  closeMenuVisible.value = false;
  window.electronAPI?.closeWindow();
}

// 真正退出应用
function handleQuitApp() {
  closeMenuVisible.value = false;
  window.electronAPI?.quitApp();
}

// 关闭右键菜单
function closeCloseMenu() {
  closeMenuVisible.value = false;
}

// 初始化任务队列 WebSocket
onMounted(async () => {
  taskStore.connectWebSocket();
  
  // 根据当前路由初始化标签页
  initTabsFromRoute();
  
  // 监听点击事件关闭右键菜单
  document.addEventListener('click', closeContextMenu);
  
  // 监听键盘快捷键
  document.addEventListener('keydown', handleKeydown);
  
  // 初始化窗口状态
  if (window.electronAPI?.isMaximized) {
    isMaximized.value = await window.electronAPI.isMaximized();
  }
  
  // 监听窗口最大化状态变化
  window.electronAPI?.onMaximizedChange?.((maximized: boolean) => {
    isMaximized.value = maximized;
  });
});

// 根据路由初始化标签页
function initTabsFromRoute() {
  const currentPath = route.path;
  
  // 如果没有标签页，打开首页
  if (tabsStore.tabs.length === 0) {
    tabsStore.openPageTab('/');
  }
  
  // 如果当前路由是有效的页面路由，打开对应标签页
  if (currentPath && currentPath !== '/') {
    // 检查精确匹配或动态路由匹配
    if (pageComponents.value[currentPath] || getPageComponent(currentPath)) {
      tabsStore.openPageTab(currentPath);
    }
  }
}

// 监听路由变化，同步标签页
watch(() => route.path, (newPath) => {
  if (newPath) {
    // 检查精确匹配或动态路由匹配
    if (pageComponents.value[newPath] || getPageComponent(newPath)) {
      tabsStore.openPageTab(newPath);
    }
  }
});

// 快捷键处理
function handleKeydown(e: KeyboardEvent) {
  // Ctrl+W 关闭当前标签页
  if (e.ctrlKey && e.key === 'w') {
    e.preventDefault(); // 阻止浏览器默认行为
    const activeTab = tabsStore.activeTab;
    if (activeTab && activeTab.closable !== false) {
      tabsStore.closeTab(activeTab.id);
    }
  }
}

onUnmounted(() => {
  taskStore.disconnectWebSocket();
  document.removeEventListener('click', closeContextMenu);
  document.removeEventListener('keydown', handleKeydown);
});

const isCollapsed = ref(false);
const unreadComments = ref(0);

// 当前激活的菜单路径
const activeMenuPath = computed(() => {
  const activeTab = tabsStore.activeTab;
  if (activeTab?.type === 'page') {
    return activeTab.path || '/';
  }
  return '/';
});

// 获取页面组件（支持动态路由）
function getPageComponent(path: string) {
  // 精确匹配
  if (pageComponents.value[path]) {
    return pageComponents.value[path];
  }
  
  // 动态路由匹配：/analytics/platform-detail/:platform
  if (path.startsWith('/analytics/platform-detail/')) {
    return pageComponents.value['/analytics/platform-detail'] || 
           defineAsyncComponent(() => import('@/views/Analytics/PlatformDetail/index.vue'));
  }
  
  return undefined;
}

// 获取标签页图标组件
function getTabIcon(iconName?: string) {
  if (!iconName) return Document;
  return iconComponents[iconName] || Document;
}

// 菜单选择处理
function handleMenuSelect(path: string) {
  openPage(path);
}

// 打开页面
function openPage(path: string) {
  tabsStore.openPageTab(path);
}

async function handleCommand(command: string) {
  switch (command) {
    case 'profile':
      openPage('/profile');
      break;
    case 'server':
      router.push('/server-config');
      break;
    case 'logout':
      try {
        await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        await authStore.logout();
        router.push('/login');
      } catch {
        // 取消
      }
      break;
  }
}

// 标签页操作
function handleTabRemove(tabId: string | number) {
  tabsStore.closeTab(String(tabId));
}

function handleTabClick() {
  // 标签页点击时的处理
}

function handleAccountSaved() {
  // 账号保存成功后触发账号列表刷新
  tabsStore.triggerAccountRefresh();
}

// 右键菜单
const contextMenu = ref({
  visible: false,
  x: 0,
  y: 0,
  tab: null as Tab | null,
});

function showTabContextMenu(e: MouseEvent, tab: Tab) {
  contextMenu.value = {
    visible: true,
    x: e.clientX,
    y: e.clientY,
    tab,
  };
}

function handleContextMenu(e: MouseEvent) {
  // 阻止默认右键菜单
  e.preventDefault();
}

function closeContextMenu() {
  contextMenu.value.visible = false;
  closeMenuVisible.value = false;
}

function handleRefreshTab() {
  // 刷新标签页（重新加载组件）
  const tab = contextMenu.value.tab;
  if (tab) {
    // 可以通过 key 变化来强制重新渲染
    // 这里简单处理，只是关闭菜单
  }
  closeContextMenu();
}

function handleCloseTab() {
  const tab = contextMenu.value.tab;
  if (tab && tab.closable) {
    tabsStore.closeTab(tab.id);
  }
  closeContextMenu();
}

function handleCloseOtherTabs() {
  const tab = contextMenu.value.tab;
  if (tab) {
    tabsStore.closeOtherTabs(tab.id);
  }
  closeContextMenu();
}

function handleCloseRightTabs() {
  const tab = contextMenu.value.tab;
  if (tab) {
    tabsStore.closeRightTabs(tab.id);
  }
  closeContextMenu();
}

function handleCloseAllTabs() {
  tabsStore.closeAllTabs();
  closeContextMenu();
}
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.app-wrapper {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: $bg-page;
}

// 自定义标题栏 - 浅色优雅风格
.title-bar {
  height: 36px;
  background: linear-gradient(180deg, #fafbfc 0%, #f3f4f6 100%);
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-shrink: 0;
  user-select: none;
  
  .title-bar-drag {
    flex: 1;
    height: 100%;
    display: flex;
    align-items: center;
    padding-left: 16px;
    -webkit-app-region: drag;
  }
  
  .title-bar-logo {
    display: flex;
    align-items: center;
    gap: 10px;
    
    .logo-icon {
      width: 20px;
      height: 20px;
      color: $primary-color;
    }
    
    .logo-text {
      font-size: 13px;
      font-weight: 600;
      color: $text-primary;
      letter-spacing: 0.3px;
    }
  }
  
  .window-controls {
    display: flex;
    height: 100%;
    -webkit-app-region: no-drag;
    gap: 1px;
    padding-right: 4px;
    
    .window-btn {
      width: 40px;
      height: 100%;
      border: none;
      background: transparent;
      color: #6b7280;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.15s ease;
      border-radius: 6px;
      margin: 4px 2px;
      height: calc(100% - 8px);
      
      svg {
        width: 10px;
        height: 10px;
      }
      
      &:hover {
        background: #e5e7eb;
        color: #374151;
      }
      
      &:active {
        background: #d1d5db;
      }
      
      &.close:hover {
        background: #fee2e2;
        color: #dc2626;
      }
      
      &.close:active {
        background: #fecaca;
      }
    }
    
    // 关闭按钮右键菜单
    .close-context-menu {
      position: fixed;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
      padding: 6px 0;
      min-width: 140px;
      z-index: 9999;
      
      .menu-item {
        padding: 8px 16px;
        font-size: 13px;
        color: #374151;
        cursor: pointer;
        transition: background 0.15s;
        
        &:hover {
          background: #f3f4f6;
        }
        
        &.danger {
          color: #dc2626;
          
          &:hover {
            background: #fef2f2;
          }
        }
      }
    }
  }
}

.main-layout {
  flex: 1;
  overflow: hidden;
}

// 侧边栏 - 浅色优雅风格
.sidebar {
  background: $sidebar-bg;
  border-right: 1px solid $border-light;
  transition: width 0.35s ease;
  overflow: hidden;
  box-shadow: $shadow-sm;
  
  .sidebar-header {
    height: 52px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-bottom: 1px solid $border-light;
    overflow: hidden;
    padding: 0 16px;
    transition: padding 0.35s ease;
    
    .app-logo {
      width: 32px;
      height: 32px;
      flex-shrink: 0;
    }
    
    .sidebar-title {
      font-size: 16px;
      font-weight: 700;
      color: $primary-color;
      letter-spacing: 0.5px;
      white-space: nowrap;
      overflow: hidden;
      margin-left: 8px;
      opacity: 1;
      max-width: 100px;
      transition: opacity 0.2s ease 0.1s, margin-left 0.35s ease, max-width 0.35s ease;
    }
  }
  
  .sidebar-menu {
    border-right: none;
    background: transparent !important;
    padding: 8px 8px;
    transition: padding 0.35s ease;
    
    :deep(.el-menu-item) {
      height: 44px;
      line-height: 44px;
      margin-bottom: 4px;
      border-radius: $radius-base;
      color: $sidebar-text-color;
      font-weight: 500;
      overflow: hidden;
      position: relative;
      display: flex;
      align-items: center;
      padding: 0 16px !important;
      transition: padding 0.35s ease, background 0.2s ease, color 0.2s ease;
      
      .el-icon {
        font-size: 18px;
        width: 18px;
        height: 18px;
        min-width: 18px;
        flex-shrink: 0;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      
      .menu-title {
        white-space: nowrap;
        overflow: hidden;
        margin-left: 12px;
        opacity: 1;
        display: inline-block;
        max-width: 150px;
        transition: opacity 0.2s ease 0.1s, margin-left 0.35s ease, max-width 0.35s ease;
      }
      
      &:hover {
        background: $bg-base !important;
        color: $primary-color;
      }
      
      &.is-active {
        background: $primary-color-light !important;
        color: $primary-color !important;
        
        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 3px;
          height: 20px;
          background: $primary-color;
          border-radius: 0 3px 3px 0;
        }
      }
    }
    
    // 子菜单样式
    :deep(.el-sub-menu) {
      .el-sub-menu__title {
        height: 44px;
        line-height: 44px;
        margin-bottom: 4px;
        border-radius: $radius-base;
        color: $sidebar-text-color;
        font-weight: 500;
        overflow: hidden;
        position: relative;
        display: flex;
        align-items: center;
        padding: 0 16px !important;
        transition: padding 0.35s ease, background 0.2s ease, color 0.2s ease;
        
        .el-icon {
          font-size: 18px;
          width: 18px;
          height: 18px;
          min-width: 18px;
          flex-shrink: 0;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        
        .menu-title {
          white-space: nowrap;
          overflow: hidden;
          margin-left: 12px;
          opacity: 1;
          display: inline-block;
          max-width: 150px;
          transition: opacity 0.2s ease 0.1s, margin-left 0.35s ease, max-width 0.35s ease;
        }
        
        &:hover {
          background: $bg-base !important;
          color: $primary-color;
        }
      }
      
      &.is-active > .el-sub-menu__title {
        color: $primary-color !important;
      }
      
      .el-menu {
        background: transparent !important;
        
        .el-menu-item {
          height: 40px;
          line-height: 40px;
          padding-left: 48px !important;
          margin-bottom: 2px;
          
          .sub-menu-title {
            font-size: 13px;
          }
          
          &.is-active {
            background: $primary-color-light !important;
            color: $primary-color !important;
            
            &::before {
              display: none;
            }
          }
        }
      }
    }
  }
  
  // 折叠状态
  &.is-collapsed {
    .sidebar-header {
      padding: 0;
      
      .sidebar-title {
        opacity: 0;
        margin-left: 0;
        max-width: 0;
        transition: opacity 0.15s ease, margin-left 0.35s ease, max-width 0.35s ease;
      }
    }
    
    .sidebar-menu {
      padding: 8px 4px;
      
      :deep(.el-menu-item) {
        padding: 0 15px !important;
        justify-content: center;
        
        .menu-title {
          opacity: 0;
          margin-left: 0;
          max-width: 0;
          transition: opacity 0.15s ease, margin-left 0.35s ease, max-width 0.35s ease;
        }
      }
      
      :deep(.el-sub-menu) {
        .el-sub-menu__title {
          padding: 0 15px !important;
          justify-content: center;
          
          .menu-title {
            opacity: 0;
            margin-left: 0;
            max-width: 0;
            transition: opacity 0.15s ease, margin-left 0.35s ease, max-width 0.35s ease;
          }
          
          .el-sub-menu__icon-arrow {
            display: none;
          }
        }
      }
    }
  }
}

.main-container {
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: $bg-page;
}

// 合并的头部和标签页栏 - 与侧边栏 header 高度一致
.header-tabs-bar {
  background: $header-bg;
  border-bottom: 1px solid $border-light;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 12px 0 0;
  flex-shrink: 0;
  height: 52px; // 与侧边栏 header 高度一致
  
  .header-tabs-left {
    display: flex;
    align-items: center;
    flex: 1;
    min-width: 0;
    height: 100%;
    
    .collapse-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      color: $text-secondary;
      padding: 10px 14px;
      margin-left: 8px;
      border-radius: $radius-base;
      transition: all 0.2s;
      flex-shrink: 0;
      
      .icon-svg {
        width: 18px;
        height: 18px;
      }
      
      &:hover {
        color: $primary-color;
        background: $primary-color-light;
      }
    }
    
    // 内联标签页样式
    .header-tabs {
      flex: 1;
      min-width: 0;
      height: 100%;
      
      :deep(.el-tabs__header) {
        margin: 0;
        border: none;
        height: 100%;
      }
      
      :deep(.el-tabs__nav-wrap) {
        height: 100%;
        position: relative;
        
        &::after {
          display: none;
        }
        
        &.is-scrollable {
          padding: 0 24px;
        }
      }
      
      :deep(.el-tabs__nav-scroll) {
        height: 100%;
      }
      
      :deep(.el-tabs__nav) {
        border: none !important;
        display: flex;
        align-items: center;
        height: 100%;
        gap: 4px;
      }
      
      :deep(.el-tabs__item) {
        height: 32px !important;
        line-height: 32px !important;
        padding: 0 12px !important;
        border-radius: $radius-sm;
        background: transparent;
        border: none !important;
        box-shadow: none !important;
        outline: none !important;
        color: $text-secondary;
        font-size: 13px;
        font-weight: 500;
        position: relative;
        transition: all 0.15s ease;
        
        &, &:hover, &:focus, &:active, &.is-active {
          transform: none !important;
          top: 0 !important;
          margin-top: 0 !important;
          margin-bottom: 0 !important;
        }
        
        &:hover {
          color: $text-primary;
          background: $bg-base;
        }
        
        &.is-active {
          background: $primary-color-light;
          color: $primary-color;
          
          .tab-icon {
            color: $primary-color;
          }
        }
        
        .is-icon-close {
          width: 14px !important;
          height: 14px !important;
          margin-left: 6px !important;
          margin-right: 0 !important;
          border-radius: 4px;
          font-size: 10px;
          color: $text-placeholder;
          transition: all 0.15s;
          
          &:hover {
            background: $danger-color;
            color: #fff;
          }
        }
      }
      
      :deep(.el-tabs__nav-prev),
      :deep(.el-tabs__nav-next) {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        display: flex;
        align-items: center;
        justify-content: center;
        width: 20px;
        height: 28px;
        color: $text-secondary;
        cursor: pointer;
        transition: all 0.2s;
        border-radius: 4px;
        z-index: 2;
        
        .el-icon {
          font-size: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        
        &:hover {
          color: $primary-color;
          background: $primary-color-light;
        }
        
        &.is-disabled {
          color: $text-placeholder;
          cursor: not-allowed;
          opacity: 0.5;
          
          &:hover {
            background: transparent;
            color: $text-placeholder;
          }
        }
      }
      
      :deep(.el-tabs__nav-prev) {
        left: 0;
      }
      
      :deep(.el-tabs__nav-next) {
        right: 0;
      }
    }
  }
  
  .header-tabs-right {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-shrink: 0;
    margin-left: 16px;
    
    .icon-badge {
      :deep(.el-badge__content) {
        top: 2px;
        right: 4px;
      }
    }
    
    .header-icon-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 34px;
      height: 34px;
      color: $text-secondary;
      cursor: pointer;
      border-radius: $radius-sm;
      transition: all 0.2s;
      background: transparent;
      
      .icon-svg {
        width: 18px;
        height: 18px;
        
        &.spinning {
          animation: spin 1s linear infinite;
        }
      }
      
      &:hover {
        color: $primary-color;
        background: $primary-color-light;
      }

      &.is-running {
        color: $primary-color;
      }
    }
    
    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      padding: 4px 10px;
      border-radius: $radius-base;
      transition: all 0.2s;
      
      &:hover {
        background: $bg-base;
      }
      
      .username {
        color: $text-primary;
        font-weight: 500;
        font-size: 13px;
      }
      
      .arrow-icon {
        width: 12px;
        height: 12px;
        color: $text-secondary;
        transition: transform 0.2s;
      }
      
      &:hover .arrow-icon {
        transform: translateY(2px);
      }
    }
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.tab-label {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  white-space: nowrap;
  
  .tab-icon {
    font-size: 14px;
    flex-shrink: 0;
    color: $text-secondary;
    transition: color 0.15s;
  }
  
  .tab-title {
    font-size: 13px;
    max-width: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

// 主内容区
.main-content {
  flex: 1;
  background: $bg-page;
  padding: 0;
  overflow: hidden;
}

.tab-contents {
  height: 100%;
  overflow: hidden;
}

.tab-content-item {
  height: 100%;
  overflow: auto;
  padding: $content-padding;
  
  // 美化滚动条
  &::-webkit-scrollbar {
    width: 6px;
  }
  
  &::-webkit-scrollbar-track {
    background: transparent;
  }
  
  &::-webkit-scrollbar-thumb {
    background: #d1d5db;
    border-radius: 3px;
    
    &:hover {
      background: #9ca3af;
    }
  }
}

.empty-content {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

// 右键菜单 - 精致风格
.context-menu {
  position: fixed;
  z-index: 3000;
  background: rgba(255, 255, 255, 0.98);
  border-radius: $radius-lg;
  box-shadow: $shadow-lg;
  padding: 6px;
  min-width: 150px;
  backdrop-filter: blur(20px);
  border: 1px solid $border-light;
  
  .context-menu-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 14px;
    cursor: pointer;
    font-size: 13px;
    color: $text-regular;
    border-radius: $radius-base;
    transition: all 0.15s ease;
    
    .el-icon {
      font-size: 15px;
      color: $text-secondary;
      transition: color 0.15s;
    }
    
    &:hover {
      background: $primary-color-light;
      color: $primary-color;
      
      .el-icon {
        color: $primary-color;
      }
    }
    
    &.disabled {
      color: $text-placeholder;
      cursor: not-allowed;
      
      .el-icon {
        color: $text-placeholder;
      }
      
      &:hover {
        background: transparent;
        color: $text-placeholder;
        
        .el-icon {
          color: $text-placeholder;
        }
      }
    }
  }
}
</style>
