<template>
  <el-container class="app-container">
    <!-- Sidebar -->
    <el-aside :width="sidebarCollapsed ? '64px' : '240px'" class="sidebar">
      <div class="sidebar-header">
        <div class="logo-icon" v-show="!sidebarCollapsed">
          <svg viewBox="0 0 32 32" fill="none"><rect width="32" height="32" rx="8" fill="rgba(255,255,255,0.1)"/><path d="M16 5L27 11V21L16 27L5 21V11L16 5Z" stroke="rgba(255,255,255,0.6)" stroke-width="1.5" fill="rgba(255,255,255,0.05)"/><circle cx="16" cy="16" r="4" fill="rgba(255,255,255,0.7)"/></svg>
        </div>
        <h2 v-show="!sidebarCollapsed">CSM</h2>
        <div class="collapse-btn" @click="sidebarCollapsed = !sidebarCollapsed">
          <el-icon :size="18"><component :is="sidebarCollapsed ? Expand : Fold" /></el-icon>
        </div>
      </div>

      <el-menu
        :default-active="currentRoute"
        :collapse="sidebarCollapsed"
        :collapse-transition="false"
        router
        background-color="transparent"
        text-color="var(--csm-sidebar-text)"
        active-text-color="var(--csm-sidebar-text-active)"
      >
        <el-menu-item index="/dashboard">
          <el-icon><Monitor /></el-icon>
          <template #title><span>仪表盘</span></template>
        </el-menu-item>
        <el-menu-item index="/devices">
          <el-icon><Platform /></el-icon>
          <template #title><span>设备管理</span></template>
        </el-menu-item>
        <el-menu-item index="/usb">
          <el-icon><Connection /></el-icon>
          <template #title><span>U盘管控</span></template>
        </el-menu-item>
        <el-menu-item index="/alerts">
          <el-icon><Bell /></el-icon>
          <template #title>
            <span>告警中心</span>
            <el-badge v-if="unreadAlerts > 0" :value="unreadAlerts" :max="99" class="menu-badge" />
          </template>
        </el-menu-item>

        <el-sub-menu index="plugins">
          <template #title>
            <el-icon><Grid /></el-icon>
            <span>安全插件</span>
          </template>
          <el-menu-item index="/plugins/web-filter">
            <template #title><span>上网拦截</span></template>
          </el-menu-item>
          <el-menu-item index="/plugins/usage-timer">
            <template #title><span>时长记录</span></template>
          </el-menu-item>
          <el-menu-item index="/plugins/software-blocker">
            <template #title><span>软件管控</span></template>
          </el-menu-item>
          <el-menu-item index="/plugins/popup-blocker">
            <template #title><span>弹窗拦截</span></template>
          </el-menu-item>
          <el-menu-item index="/plugins/usb-file-audit">
            <template #title><span>U盘审计</span></template>
          </el-menu-item>
          <el-menu-item index="/plugins/watermark">
            <template #title><span>水印管理</span></template>
          </el-menu-item>
        </el-sub-menu>

        <el-menu-item index="/settings">
          <el-icon><Setting /></el-icon>
          <template #title><span>系统设置</span></template>
        </el-menu-item>
      </el-menu>

      <div class="sidebar-footer" v-show="!sidebarCollapsed">
        <span class="version">v0.1.0</span>
      </div>
    </el-aside>

    <!-- Main content -->
    <el-container>
      <el-header class="app-header" height="60px">
        <div class="header-left">
          <div class="breadcrumb">
            <span class="breadcrumb-home" @click="$router.push('/dashboard')">首页</span>
            <span class="breadcrumb-sep" v-if="pageTitle !== '仪表盘'">/</span>
            <span class="breadcrumb-current" v-if="pageTitle !== '仪表盘'">{{ pageTitle }}</span>
          </div>
        </div>
        <div class="header-right">
          <el-tooltip content="告警中心" placement="bottom">
            <div class="header-action" @click="$router.push('/alerts')">
              <el-badge :value="unreadAlerts" :hidden="unreadAlerts === 0" :max="99">
                <el-icon :size="20"><Bell /></el-icon>
              </el-badge>
            </div>
          </el-tooltip>
          <el-dropdown>
            <div class="user-info">
              <div class="user-avatar">{{ username.charAt(0).toUpperCase() }}</div>
              <span class="user-name">{{ username }}</span>
              <el-icon class="user-arrow"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="$router.push('/settings')">
                  <el-icon><Setting /></el-icon>系统设置
                </el-dropdown-item>
                <el-dropdown-item divided @click="handleLogout">
                  <el-icon><SwitchButton /></el-icon>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-main class="app-main">
        <router-view v-slot="{ Component }">
          <transition name="page" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  Monitor, Platform, Connection, Bell, Setting,
  ArrowDown, Grid, Expand, Fold, SwitchButton
} from '@element-plus/icons-vue'
import { api } from '@/lib/api'

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

const sidebarCollapsed = ref(false)
const currentRoute = computed(() => route.path)
const unreadAlerts = ref(0)
const username = ref('')

function decodeUsername(): string {
  try {
    const token = localStorage.getItem('token')
    if (!token) return ''
    const payload = JSON.parse(atob(token.split('.')[1]))
    return payload.username || ''
  } catch {
    return ''
  }
}

async function fetchUnreadAlerts() {
  try {
    const data = await api.get<any>('/api/alerts/records?handled=0&page_size=1')
    unreadAlerts.value = data.records?.length || 0
  } catch {
    // Silently fail
  }
}

const pageTitles: Record<string, string> = {
  '/dashboard': '仪表盘',
  '/devices': '设备管理',
  '/usb': 'U盘管控',
  '/alerts': '告警中心',
  '/settings': '系统设置',
  '/plugins/web-filter': '上网拦截',
  '/plugins/usage-timer': '时长记录',
  '/plugins/software-blocker': '软件管控',
  '/plugins/popup-blocker': '弹窗拦截',
  '/plugins/usb-file-audit': 'U盘审计',
  '/plugins/watermark': '水印管理',
}

const pageTitle = computed(() => pageTitles[route.path] || '仪表盘')

onMounted(() => {
  username.value = decodeUsername()
  fetchUnreadAlerts()
})

function handleLogout() {
  localStorage.removeItem('token')
  localStorage.removeItem('refresh_token')
  router.push('/login')
}
</script>

<style scoped>
.app-container {
  height: 100vh;
  overflow: hidden;
}

/* ---- Sidebar ---- */
.sidebar {
  background: var(--csm-sidebar-bg);
  overflow-y: auto;
  overflow-x: hidden;
  border-right: none;
  display: flex;
  flex-direction: column;
  transition: width var(--csm-transition);
}

.sidebar::-webkit-scrollbar {
  width: 0;
}

.sidebar-header {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 20px 16px 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
  min-height: 60px;
}

.logo-icon svg {
  width: 32px;
  height: 32px;
  flex-shrink: 0;
}

.sidebar-header h2 {
  font-size: 22px;
  font-weight: 700;
  color: #fff;
  letter-spacing: -0.02em;
  white-space: nowrap;
}

.collapse-btn {
  margin-left: auto;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  color: var(--csm-sidebar-text);
  cursor: pointer;
  transition: all var(--csm-transition-fast);
  flex-shrink: 0;
}

.collapse-btn:hover {
  background: rgba(255, 255, 255, 0.08);
  color: #fff;
}

/* Menu overrides */
.sidebar :deep(.el-menu) {
  border-right: none;
  padding: 8px;
}

.sidebar :deep(.el-menu-item),
.sidebar :deep(.el-sub-menu__title) {
  height: 42px;
  line-height: 42px;
  border-radius: 8px;
  margin: 2px 0;
  font-size: 13px;
  font-weight: 500;
  transition: all var(--csm-transition-fast);
}

.sidebar :deep(.el-menu-item:hover),
.sidebar :deep(.el-sub-menu__title:hover) {
  background: var(--csm-sidebar-hover) !important;
}

.sidebar :deep(.el-menu-item.is-active) {
  background: var(--csm-sidebar-active) !important;
  color: var(--csm-sidebar-text-active) !important;
}

.sidebar :deep(.el-sub-menu .el-menu-item) {
  padding-left: 48px !important;
  height: 38px;
  line-height: 38px;
  font-size: 13px;
}

.sidebar :deep(.el-menu--collapse .el-menu-item),
.sidebar :deep(.el-menu--collapse .el-sub-menu__title) {
  padding: 0 !important;
  justify-content: center;
}

.menu-badge {
  margin-left: 8px;
}

.menu-badge :deep(.el-badge__content) {
  font-size: 10px;
  height: 16px;
  line-height: 16px;
  padding: 0 4px;
}

.sidebar-footer {
  margin-top: auto;
  padding: 16px;
  border-top: 1px solid rgba(255, 255, 255, 0.06);
  text-align: center;
}

.sidebar-footer .version {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.25);
}

/* ---- Header ---- */
.app-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: var(--csm-bg-header);
  border-bottom: 1px solid var(--csm-border-color);
  padding: 0 24px;
  z-index: 10;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.breadcrumb-home {
  color: var(--csm-text-secondary);
  cursor: pointer;
  transition: color var(--csm-transition-fast);
}

.breadcrumb-home:hover {
  color: var(--csm-primary);
}

.breadcrumb-sep {
  color: var(--csm-text-tertiary);
}

.breadcrumb-current {
  color: var(--csm-text-primary);
  font-weight: 600;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-action {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  color: var(--csm-text-secondary);
  cursor: pointer;
  transition: all var(--csm-transition-fast);
}

.header-action:hover {
  background: var(--csm-bg-page);
  color: var(--csm-text-primary);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 8px;
  transition: background var(--csm-transition-fast);
}

.user-info:hover {
  background: var(--csm-bg-page);
}

.user-avatar {
  width: 30px;
  height: 30px;
  border-radius: 8px;
  background: var(--csm-primary);
  color: #fff;
  font-size: 13px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-name {
  font-size: 13px;
  font-weight: 500;
  color: var(--csm-text-primary);
}

.user-arrow {
  color: var(--csm-text-tertiary);
  font-size: 12px;
}

/* ---- Main ---- */
.app-main {
  background: var(--csm-bg-page);
  padding: 0;
  overflow-y: auto;
}
</style>
