<template>
  <el-container class="layout-container">
    <el-aside v-if="!isMobile" width="220px" class="sidebar">
      <div class="logo">
        <span>XuqmGroup</span>
      </div>
      <el-menu
        :default-active="$route.path"
        :default-openeds="openedMenus"
        router
        background-color="#1d2129"
        text-color="#c9d1d9"
        active-text-color="#409eff"
        class="nav-menu"
      >
        <el-menu-item index="/dashboard"><el-icon><Odometer /></el-icon><span>控制台</span></el-menu-item>
        <el-menu-item index="/apps"><el-icon><Grid /></el-icon><span>我的应用</span></el-menu-item>
        <el-sub-menu index="services">
          <template #title><el-icon><List /></el-icon><span>服务管理</span></template>
          <el-menu-item index="/services/im"><el-icon><ChatDotRound /></el-icon><span>即时通讯</span></el-menu-item>
          <el-menu-item index="/services/push"><el-icon><Bell /></el-icon><span>离线推送</span></el-menu-item>
          <el-menu-item index="/services/update"><el-icon><Upload /></el-icon><span>版本管理</span></el-menu-item>
          <el-sub-menu index="services-bugcollect">
            <template #title><el-icon><DataLine /></el-icon><span>崩溃收集</span></template>
            <el-menu-item index="/bugcollect/overview"><el-icon><Odometer /></el-icon><span>概览</span></el-menu-item>
            <el-menu-item index="/bugcollect/issues"><el-icon><Warning /></el-icon><span>错误列表</span></el-menu-item>
            <el-menu-item index="/bugcollect/events"><el-icon><List /></el-icon><span>事件流水</span></el-menu-item>
            <el-menu-item index="/bugcollect/funnels"><el-icon><Filter /></el-icon><span>漏斗分析</span></el-menu-item>
            <el-menu-item index="/bugcollect/rank/freq"><el-icon><Sort /></el-icon><span>高频排行</span></el-menu-item>
            <el-menu-item index="/bugcollect/rank/risk"><el-icon><Warning /></el-icon><span>高危排行</span></el-menu-item>
            <el-menu-item index="/bugcollect/webhooks"><el-icon><Link /></el-icon><span>Webhook</span></el-menu-item>
            <el-menu-item index="/bugcollect/sourcemaps"><el-icon><Document /></el-icon><span>Sourcemap</span></el-menu-item>
          </el-sub-menu>
        </el-sub-menu>
        <el-menu-item index="/security"><el-icon><Lock /></el-icon><span>安全中心</span></el-menu-item>
        <el-sub-menu index="ops">
          <template #title><el-icon><Setting /></el-icon><span>运维管理</span></template>
          <el-menu-item v-if="isPrivateDeploy" index="/system-logs"><el-icon><Monitor /></el-icon><span>服务日志</span></el-menu-item>
          <el-menu-item v-if="isPrivateDeploy" index="/database"><el-icon><Coin /></el-icon><span>数据库管理</span></el-menu-item>
          <el-menu-item index="/operation-logs"><el-icon><Document /></el-icon><span>操作日志</span></el-menu-item>
        </el-sub-menu>
        <el-menu-item v-if="auth.user?.type === 'MAIN'" index="/accounts"><el-icon><User /></el-icon><span>子账号管理</span></el-menu-item>
      </el-menu>
    </el-aside>

    <el-drawer
      v-model="drawerVisible"
      direction="ltr"
      :with-header="false"
      size="250px"
      class="mobile-drawer"
    >
      <div class="drawer-brand">
        <span>XuqmGroup</span>
      </div>
      <el-menu
        :default-active="$route.path"
        :default-openeds="openedMenus"
        router
        background-color="#1d2129"
        text-color="#c9d1d9"
        active-text-color="#409eff"
        class="nav-menu"
        @select="handleNavSelect"
      >
        <el-menu-item index="/dashboard"><el-icon><Odometer /></el-icon><span>控制台</span></el-menu-item>
        <el-menu-item index="/apps"><el-icon><Grid /></el-icon><span>我的应用</span></el-menu-item>
        <el-sub-menu index="services">
          <template #title><el-icon><List /></el-icon><span>服务管理</span></template>
          <el-menu-item index="/services/im"><el-icon><ChatDotRound /></el-icon><span>即时通讯</span></el-menu-item>
          <el-menu-item index="/services/push"><el-icon><Bell /></el-icon><span>离线推送</span></el-menu-item>
          <el-menu-item index="/services/update"><el-icon><Upload /></el-icon><span>版本管理</span></el-menu-item>
          <el-sub-menu index="services-bugcollect">
            <template #title><el-icon><DataLine /></el-icon><span>崩溃收集</span></template>
            <el-menu-item index="/bugcollect/overview"><el-icon><Odometer /></el-icon><span>概览</span></el-menu-item>
            <el-menu-item index="/bugcollect/issues"><el-icon><Warning /></el-icon><span>错误列表</span></el-menu-item>
            <el-menu-item index="/bugcollect/events"><el-icon><List /></el-icon><span>事件流水</span></el-menu-item>
            <el-menu-item index="/bugcollect/funnels"><el-icon><Filter /></el-icon><span>漏斗分析</span></el-menu-item>
            <el-menu-item index="/bugcollect/rank/freq"><el-icon><Sort /></el-icon><span>高频排行</span></el-menu-item>
            <el-menu-item index="/bugcollect/rank/risk"><el-icon><Warning /></el-icon><span>高危排行</span></el-menu-item>
            <el-menu-item index="/bugcollect/webhooks"><el-icon><Link /></el-icon><span>Webhook</span></el-menu-item>
            <el-menu-item index="/bugcollect/sourcemaps"><el-icon><Document /></el-icon><span>Sourcemap</span></el-menu-item>
          </el-sub-menu>
        </el-sub-menu>
        <el-menu-item index="/security"><el-icon><Lock /></el-icon><span>安全中心</span></el-menu-item>
        <el-sub-menu index="ops">
          <template #title><el-icon><Setting /></el-icon><span>运维管理</span></template>
          <el-menu-item v-if="isPrivateDeploy" index="/system-logs"><el-icon><Monitor /></el-icon><span>服务日志</span></el-menu-item>
          <el-menu-item v-if="isPrivateDeploy" index="/database"><el-icon><Coin /></el-icon><span>数据库管理</span></el-menu-item>
          <el-menu-item index="/operation-logs"><el-icon><Document /></el-icon><span>操作日志</span></el-menu-item>
        </el-sub-menu>
        <el-menu-item v-if="auth.user?.type === 'MAIN'" index="/accounts"><el-icon><User /></el-icon><span>子账号管理</span></el-menu-item>
      </el-menu>
    </el-drawer>

    <el-container class="content-shell">
      <el-header class="header">
        <div v-if="isMobile" class="mobile-header-left">
          <el-button text circle class="menu-button" @click="drawerVisible = true">
            <el-icon><Menu /></el-icon>
          </el-button>
          <span class="mobile-title">XuqmGroup</span>
        </div>
        <div v-else class="header-spacer" />
        <div class="header-right">
          <el-tooltip content="开发者文档" placement="bottom">
            <a href="/docs/" target="_blank" class="docs-link">
              <el-icon :size="18"><Document /></el-icon>
              <span>文档</span>
            </a>
          </el-tooltip>
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-avatar :size="32" style="background:#409eff">
                {{ auth.user?.nickname?.charAt(0) ?? 'U' }}
              </el-avatar>
              <span class="nickname">{{ auth.user?.nickname }}</span>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-main class="main-content">
        <router-view :key="$route.path" />
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useRoute, useRouter } from 'vue-router'
import { Bell, ChatDotRound, Coin, DataLine, Document, Filter, Grid, Key, Link, List, Lock, Menu, Monitor, Odometer, Setting, Sort, Upload, User, Warning } from '@element-plus/icons-vue'
import { getDeploymentStatus } from '@/api/system'

const auth = useAuthStore()
const route = useRoute()
const router = useRouter()
const isMobile = ref(false)
const drawerVisible = ref(false)
const isPrivateDeploy = ref(false)

const openedMenus = computed(() => {
  const menus: string[] = []
  if (route.path.startsWith('/services/')) menus.push('services')
  if (['/system-logs', '/database', '/operation-logs'].includes(route.path)) menus.push('ops')
  if (route.path.startsWith('/bugcollect/')) menus.push('services', 'services-bugcollect')
  return menus
})

function updateViewport() {
  isMobile.value = window.innerWidth < 768
  if (!isMobile.value) {
    drawerVisible.value = false
  }
}

function handleNavSelect() {
  drawerVisible.value = false
}

function handleCommand(cmd: string) {
  if (cmd === 'logout') {
    auth.logout()
    router.push('/login')
  }
}

watch(
  () => route.path,
  () => {
    drawerVisible.value = false
  },
)

onMounted(async () => {
  updateViewport()
  window.addEventListener('resize', updateViewport)
  try {
    const status = await getDeploymentStatus()
    isPrivateDeploy.value = status.mode === 'PRIVATE'
  } catch {
    isPrivateDeploy.value = false
  }
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', updateViewport)
})
</script>

<style scoped>
.layout-container {
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(180deg, #f7f9fc 0%, #eef2f7 100%);
}
.sidebar {
  background: #1d2129;
  flex: 0 0 220px;
  box-shadow: 8px 0 24px rgba(15, 23, 42, 0.08);
  overflow: hidden;
}
.logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  border-bottom: 1px solid #2d3142;
}
.nav-menu {
  border-right: none;
}
.content-shell {
  min-width: 0;
}
.header {
  background: #fff;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  gap: 16px;
  box-shadow: 0 1px 0 rgba(15, 23, 42, 0.03);
  position: sticky;
  top: 0;
  z-index: 9;
}
.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}
.header-spacer {
  flex: 1;
}
.mobile-header-left {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
}
.mobile-title {
  font-size: 16px;
  font-weight: 700;
  color: #111827;
}
.menu-button {
  color: #111827;
}
.docs-link {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #555;
  font-size: 13px;
  text-decoration: none;
  padding: 4px 8px;
  border-radius: 6px;
  transition: background 0.15s;
}
.docs-link:hover {
  background: #f5f5f5;
  color: #409eff;
}
.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}
.nickname {
  font-size: 14px;
  color: #333;
}
.main-content {
  padding: 16px;
  overflow: auto;
}
.drawer-brand {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  border-bottom: 1px solid #2d3142;
  background: #1d2129;
}
.mobile-drawer :deep(.el-drawer__body) {
  padding: 0;
  background: #1d2129;
}

@media (max-width: 767px) {
  .layout-container {
    display: block;
    height: auto;
    min-height: 100vh;
  }

  .header {
    padding: 0 12px;
  }

  .header-right {
    gap: 10px;
  }

  .docs-link span,
  .nickname {
    display: none;
  }

  .main-content {
    padding: 12px;
  }
}
</style>
