<script setup>
import { computed, onBeforeUnmount, onMounted, provide, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import {
  Bell,
  ChatLineSquare,
  Document,
  List,
  Lock,
  Message,
  Setting,
  Tools,
  User,
} from '@element-plus/icons-vue'

import { api } from '../api/client'
import { fetchFeedbackStats } from '../api/feedbacks'
import { fetchSystemStats } from '../api/stats'
import { clearCachedKdocsStatus, preloadKdocsStatus } from '../utils/kdocsStatusCache'

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

const stats = ref({})

const adminUsername = computed(() => stats.value?.admin_username || '')

async function refreshStats(options = {}) {
  stats.value = await fetchSystemStats(options)
}

const loadingBadges = ref(false)
const pendingFeedbackCount = ref(0)

const BADGE_POLL_ACTIVE_MS = 60_000
const BADGE_POLL_HIDDEN_MS = 180_000

let badgeTimer = null

async function refreshNavBadges(partial = null) {
  if (partial && typeof partial === 'object') {
    if (Object.prototype.hasOwnProperty.call(partial, 'pendingFeedbacks')) {
      pendingFeedbackCount.value = Number(partial.pendingFeedbacks || 0)
    }
    return
  }

  if (loadingBadges.value) return
  loadingBadges.value = true

  try {
    const feedbackResult = await fetchFeedbackStats()
    pendingFeedbackCount.value = Number(feedbackResult?.pending || 0)
  } finally {
    loadingBadges.value = false
  }
}

function isPageHidden() {
  if (typeof document === 'undefined') return false
  return document.visibilityState === 'hidden'
}

function currentBadgePollDelay() {
  return isPageHidden() ? BADGE_POLL_HIDDEN_MS : BADGE_POLL_ACTIVE_MS
}

function stopBadgePolling() {
  if (!badgeTimer) return
  window.clearTimeout(badgeTimer)
  badgeTimer = null
}

function scheduleBadgePolling() {
  stopBadgePolling()
  badgeTimer = window.setTimeout(async () => {
    badgeTimer = null
    await refreshNavBadges().catch(() => {})
    scheduleBadgePolling()
  }, currentBadgePollDelay())
}

function onVisibilityChange() {
  scheduleBadgePolling()
}

provide('refreshStats', refreshStats)
provide('adminStats', stats)
provide('refreshNavBadges', refreshNavBadges)

const isMobile = ref(false)
const drawerOpen = ref(false)
let mediaQuery

function syncIsMobile() {
  isMobile.value = Boolean(mediaQuery?.matches)
  if (!isMobile.value) drawerOpen.value = false
}

onMounted(async () => {
  mediaQuery = window.matchMedia('(max-width: 768px)')
  mediaQuery.addEventListener?.('change', syncIsMobile)
  syncIsMobile()

  // 后台登录后预加载金山文档登录状态，系统配置页可直接复用缓存。
  void preloadKdocsStatus({ maxAgeMs: 60_000, silent: true }).catch(() => {})

  await refreshStats()
  await refreshNavBadges()
  scheduleBadgePolling()
  window.addEventListener('visibilitychange', onVisibilityChange)
})

onBeforeUnmount(() => {
  mediaQuery?.removeEventListener?.('change', syncIsMobile)
  stopBadgePolling()
  window.removeEventListener('visibilitychange', onVisibilityChange)
})

const menuItems = [
  { path: '/reports', label: '报表', icon: Document },
  { path: '/users', label: '用户', icon: User },
  { path: '/feedbacks', label: '反馈', icon: ChatLineSquare, badgeKey: 'feedbacks' },
  { path: '/logs', label: '任务日志', icon: List },
  { path: '/announcements', label: '公告', icon: Bell },
  { path: '/email', label: '邮件', icon: Message },
  { path: '/security', label: '安全防护', icon: Lock },
  { path: '/system', label: '系统配置', icon: Tools },
  { path: '/settings', label: '设置', icon: Setting },
]

const activeMenu = computed(() => route.path)

function badgeFor(item) {
  if (!item?.badgeKey) return 0
  if (item.badgeKey === 'feedbacks') {
    return Number(pendingFeedbackCount.value || 0)
  }
  return 0
}

async function logout() {
  let confirmed = false
  try {
    await ElMessageBox.confirm('确定退出管理员登录吗？', '退出登录', {
      confirmButtonText: '退出',
      cancelButtonText: '取消',
      type: 'warning',
    })
    confirmed = true
  } catch (error) {
    const reason = String(error || '').toLowerCase()
    if (reason === 'cancel' || reason === 'close') return
    try {
      confirmed = window.confirm('确定退出管理员登录吗？')
    } catch {
      confirmed = false
    }
  }

  if (!confirmed) return

  try {
    await api.post('/logout')
  } finally {
    clearCachedKdocsStatus()
    window.location.href = '/yuyx'
  }
}

async function go(path) {
  await router.push(path)
  drawerOpen.value = false
}
</script>

<template>
  <el-container class="layout-root">
    <el-aside v-if="!isMobile" width="220px" class="layout-aside">
      <div class="brand">
        <div class="brand-title">后台管理</div>
        <div class="brand-sub app-muted">知识管理平台</div>
      </div>

      <el-menu :default-active="activeMenu" class="aside-menu" router @select="go">
        <el-menu-item v-for="item in menuItems" :key="item.path" :index="item.path">
          <el-icon><component :is="item.icon" /></el-icon>
          <el-badge v-if="badgeFor(item) > 0" :value="badgeFor(item)" :max="99" class="menu-badge">
            <span class="menu-label">{{ item.label }}</span>
          </el-badge>
          <span v-else class="menu-label">{{ item.label }}</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <el-container>
      <el-header class="layout-header">
        <div class="header-left">
          <el-button v-if="isMobile" text class="header-menu-btn" @click="drawerOpen = true">
            菜单
          </el-button>
          <div class="header-title">后台管理系统</div>
        </div>

        <div class="header-right">
          <div class="admin-name">
            <span class="app-muted">管理员</span>
            <strong>{{ adminUsername || '-' }}</strong>
          </div>
          <el-button type="primary" plain class="logout-btn" @click="logout">退出</el-button>
        </div>
      </el-header>

      <el-main class="layout-main">
        <div class="main-shell">
          <Suspense>
            <template #default>
              <RouterView />
            </template>
            <template #fallback>
              <el-card shadow="never" :body-style="{ padding: '16px' }" class="fallback-card">
                <el-skeleton :rows="5" animated />
              </el-card>
            </template>
          </Suspense>
        </div>
      </el-main>
    </el-container>

    <el-drawer v-model="drawerOpen" size="min(82vw, 280px)" direction="ltr" :with-header="false">
      <div class="drawer-brand">
        <div class="brand-title">后台管理</div>
        <div class="brand-sub app-muted">知识管理平台</div>
      </div>
      <el-menu :default-active="activeMenu" class="aside-menu" router @select="go">
        <el-menu-item v-for="item in menuItems" :key="item.path" :index="item.path">
          <el-icon><component :is="item.icon" /></el-icon>
          <el-badge v-if="badgeFor(item) > 0" :value="badgeFor(item)" :max="99" class="menu-badge">
            <span class="menu-label">{{ item.label }}</span>
          </el-badge>
          <span v-else class="menu-label">{{ item.label }}</span>
        </el-menu-item>
      </el-menu>
    </el-drawer>
  </el-container>
</template>

<style scoped>
.layout-root {
  height: 100%;
}

.layout-aside {
  background: linear-gradient(180deg, rgba(255, 255, 255, 0.98), rgba(248, 250, 252, 0.94));
  border-right: 1px solid var(--app-border);
  box-shadow: 4px 0 16px rgba(15, 23, 42, 0.04);
}

.brand,
.drawer-brand {
  padding: 18px 16px 14px;
}

.brand {
  border-bottom: 1px solid rgba(15, 23, 42, 0.06);
}

.brand-title {
  font-size: 16px;
  font-weight: 800;
  letter-spacing: 0.2px;
}

.brand-sub {
  margin-top: 4px;
  font-size: 12px;
}

.aside-menu {
  border-right: none;
  padding: 8px;
  background: transparent;
}

.aside-menu :deep(.el-menu-item) {
  height: 42px;
  line-height: 42px;
  margin: 3px 0;
  border-radius: 10px;
  color: #334155;
  font-weight: 600;
}

.aside-menu :deep(.el-menu-item .el-icon) {
  margin-right: 10px;
}

.aside-menu :deep(.el-menu-item:hover) {
  background: rgba(59, 130, 246, 0.08);
  color: #1d4ed8;
}

.aside-menu :deep(.el-menu-item.is-active) {
  background: linear-gradient(135deg, rgba(37, 99, 235, 0.12), rgba(124, 58, 237, 0.1));
  color: #1e40af;
}

.menu-label {
  display: inline-flex;
  align-items: center;
  min-width: 0;
}

.menu-badge {
  display: inline-flex;
  align-items: center;
}

.fallback-card {
  min-height: 160px;
  border-radius: var(--app-radius-lg);
  border: 1px solid var(--app-border);
}

.layout-header {
  position: sticky;
  top: 0;
  z-index: 20;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  height: 58px;
  padding: 0 18px;
  background: rgba(255, 255, 255, 0.78);
  backdrop-filter: saturate(180%) blur(10px);
  border-bottom: 1px solid var(--app-border);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
}

.header-title {
  font-size: 15px;
  font-weight: 800;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.header-menu-btn {
  padding-left: 0;
  padding-right: 0;
}

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

.admin-name {
  display: flex;
  align-items: baseline;
  gap: 8px;
  font-size: 13px;
  color: #334155;
}

.admin-name strong {
  color: #0f172a;
  font-weight: 800;
}

.logout-btn {
  min-width: 74px;
}

.layout-main {
  padding: 18px;
}

.main-shell {
  width: 100%;
  max-width: 1600px;
  margin: 0 auto;
}

@media (max-width: 768px) {
  .layout-header {
    flex-wrap: wrap;
    height: auto;
    padding: 10px 12px;
  }

  .header-right {
    width: 100%;
    justify-content: flex-end;
  }

  .admin-name .app-muted {
    display: none;
  }

  .admin-name strong {
    display: none;
  }

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