<script setup>
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { Calendar, Camera, User } from '@element-plus/icons-vue'

import { useUserStore } from '../stores/user'

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

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

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

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

  userStore.refreshVipInfo().catch(() => {
    window.location.href = '/login'
  })
})

onBeforeUnmount(() => {
  mediaQuery?.removeEventListener?.('change', syncIsMobile)
})

const menuItems = [
  { path: '/app/accounts', label: '账号管理', icon: User },
  { path: '/app/schedules', label: '定时任务', icon: Calendar },
  { path: '/app/screenshots', label: '截图管理', icon: Camera },
]

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

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

async function logout() {
  try {
    await ElMessageBox.confirm('确定退出登录吗？', '退出登录', {
      confirmButtonText: '退出',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }

  await userStore.logout()
  window.location.href = '/login'
}
</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>
          <span>{{ 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="user-meta">
            <el-tag v-if="userStore.isVip" type="success" size="small" effect="light">VIP</el-tag>
            <el-tag v-else type="info" size="small" effect="light">普通</el-tag>
            <span class="user-name">{{ userStore.username || '用户' }}</span>
            <span v-if="userStore.isVip && userStore.vipDaysLeft <= 7 && userStore.vipDaysLeft > 0" class="vip-warn">
              ({{ userStore.vipDaysLeft }}天后到期)
            </span>
          </div>
          <el-button type="primary" plain @click="logout">退出</el-button>
        </div>
      </el-header>

      <el-main class="layout-main">
        <RouterView />
      </el-main>
    </el-container>

    <el-drawer v-model="drawerOpen" size="240px" :with-header="false">
      <div class="drawer-brand">
        <div class="brand-title">知识管理平台</div>
        <div class="brand-sub app-muted">用户中心</div>
      </div>
      <div class="drawer-user">
        <el-tag v-if="userStore.isVip" type="success" size="small" effect="light">VIP</el-tag>
        <el-tag v-else type="info" size="small" effect="light">普通</el-tag>
        <span class="user-name">{{ userStore.username || '用户' }}</span>
      </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>
          <span>{{ item.label }}</span>
        </el-menu-item>
      </el-menu>
      <div class="drawer-actions">
        <el-button type="primary" plain style="width: 100%" @click="logout">退出登录</el-button>
      </div>
    </el-drawer>
  </el-container>
</template>

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

.layout-aside {
  background: #ffffff;
  border-right: 1px solid var(--app-border);
}

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

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

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

.aside-menu {
  border-right: none;
}

.layout-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  background: rgba(246, 247, 251, 0.6);
  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: 14px;
  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;
}

.user-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.user-name {
  font-size: 13px;
  font-weight: 700;
  max-width: 180px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.vip-warn {
  font-size: 12px;
  color: var(--app-muted);
  white-space: nowrap;
}

.layout-main {
  padding: 16px;
}

.drawer-user {
  padding: 0 16px 10px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.drawer-actions {
  padding: 12px 16px 4px;
  border-top: 1px solid var(--app-border);
}

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

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

  .layout-main {
    padding: 12px;
  }

  .user-name {
    max-width: 120px;
  }
}
</style>
