<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useGroupStore } from '@/stores/group'
import { useTeamStore } from '@/stores/team'
import { useNotificationStore } from '@/stores/notification'
import StatusToggle from '@/components/team/StatusToggle.vue'
import WorkScheduleModal from '@/components/team/WorkScheduleModal.vue'
import NotificationPanel from '@/components/common/NotificationPanel.vue'
import CreateGroupDialog from '@/components/group/CreateGroupDialog.vue'
import JoinGroupDialog from '@/components/group/JoinGroupDialog.vue'
import { Monitor, HomeFilled, Grid, Plus, Search, Bell, AlarmClock, SwitchButton, Document } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const groupStore = useGroupStore()
const teamStore = useTeamStore()
const notificationStore = useNotificationStore()

const showScheduleModal = ref(false)
const showCreateGroup = ref(false)
const showJoinGroup = ref(false)
const sidebarOpen = ref(false)

let refreshTimer: ReturnType<typeof setInterval> | null = null

onMounted(async () => {
  await userStore.initUser()
  await groupStore.loadGroups()
  await teamStore.loadActiveSession()
  await notificationStore.loadPendingInvitations()
  await notificationStore.startListening()

  refreshTimer = setInterval(async () => {
    await groupStore.loadGroups()
    await teamStore.loadActiveSession()
  }, 30000)
})

onUnmounted(() => {
  notificationStore.stopListening()
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
})

function handleLogout() {
  userStore.logout()
  router.push({ name: 'Login' })
}

function selectGroup(groupId: string) {
  groupStore.setCurrentGroup(groupId)
  router.push({ name: 'GroupView', params: { id: groupId } })
  sidebarOpen.value = false
}

function goHome() {
  router.push({ name: 'Home' })
  sidebarOpen.value = false
}

const pageTitle = computed(() => {
  if (route.name === 'GroupView') return groupStore.currentGroup?.name
  if (route.name === 'GamesLibrary') return '游戏库'
  if (route.name === 'Profile') return '个人中心'
  if (route.name === 'Settings') return '设置'
  if (route.name === 'Changelog') return '更新日志'
  return '首页'
})
</script>

<template>
  <div class="app-layout">
    <!-- 移动端遮罩 -->
    <div v-if="sidebarOpen" class="sidebar-overlay" @click="sidebarOpen = false" />

    <!-- 侧边栏 -->
    <aside class="sidebar" :class="{ 'sidebar--open': sidebarOpen }">
      <div class="sidebar-top">
        <div class="logo" @click="goHome">
          <el-icon class="logo-icon"><Monitor /></el-icon>
          <span class="logo-text">Game Group</span>
        </div>
      </div>

      <nav class="sidebar-nav">
        <router-link to="/" class="nav-item" active-class="nav-item--active">
          <el-icon class="nav-icon"><HomeFilled /></el-icon>
          <span>首页</span>
        </router-link>
        <router-link to="/games" class="nav-item" active-class="nav-item--active">
          <el-icon class="nav-icon"><Grid /></el-icon>
          <span>游戏库</span>
        </router-link>
        <router-link to="/changelog" class="nav-item" active-class="nav-item--active">
          <el-icon class="nav-icon"><Document /></el-icon>
          <span>更新日志</span>
        </router-link>
      </nav>

      <div class="sidebar-divider" />

      <!-- 群组操作区 -->
      <div class="sidebar-group-actions">
        <button class="group-action-btn group-action-btn--create" @click="showCreateGroup = true">
          <el-icon><Plus /></el-icon>
          <span>创建群组</span>
        </button>
        <button class="group-action-btn group-action-btn--join" @click="showJoinGroup = true">
          <el-icon><Search /></el-icon>
          <span>加入群组</span>
        </button>
      </div>

      <!-- 群组列表 -->
      <div class="sidebar-groups">
        <div class="section-header">
          <span class="section-title">我的群组</span>
        </div>
        <div v-if="groupStore.groups.length === 0" class="empty-groups">
          <p>还没有群组</p>
          <p class="empty-hint">点击上方按钮创建或加入</p>
        </div>
        <div
          v-for="group in groupStore.groups"
          :key="group.id"
          class="group-item"
          :class="{ 'group-item--active': route.params.id === group.id }"
          @click="selectGroup(group.id)"
        >
          <span class="group-name">{{ group.name }}</span>
          <span class="group-count">{{ group.members?.length || 0 }}</span>
        </div>
      </div>

      <div class="sidebar-bottom">
        <div class="sidebar-divider" />
        <div class="user-section">
          <StatusToggle />
          <button class="schedule-btn" @click="showScheduleModal = true" title="设置工作时间">
            <el-icon><AlarmClock /></el-icon>
          </button>
        </div>
        <div class="user-info">
          <img
            :src="userStore.user?.avatar || '/default-avatar.svg'"
            class="user-avatar"
            alt=""
          />
          <span class="user-name">{{ userStore.user?.username }}</span>
          <button class="logout-btn" @click="handleLogout" title="退出登录">
            <el-icon><SwitchButton /></el-icon>
          </button>
        </div>
      </div>
    </aside>

    <!-- 右侧 -->
    <div class="main-wrapper">
      <header class="top-header">
        <!-- 移动端汉堡按钮 -->
        <button class="hamburger-btn" @click="sidebarOpen = !sidebarOpen">
          <span class="hamburger-line" />
          <span class="hamburger-line" />
          <span class="hamburger-line" />
        </button>

        <h2 class="page-title">{{ pageTitle }}</h2>

        <div class="header-actions">
          <button class="header-action-btn" @click="showCreateGroup = true" title="创建群组">
            <el-icon><Plus /></el-icon>
            <span class="header-action-label">创建群组</span>
          </button>
          <button class="header-action-btn" @click="showJoinGroup = true" title="加入群组">
            <el-icon><Search /></el-icon>
            <span class="header-action-label">加入群组</span>
          </button>
          <button class="icon-btn" @click="notificationStore.togglePanel()">
            <span v-if="notificationStore.unreadCount > 0" class="badge">
              {{ notificationStore.unreadCount }}
            </span>
            <el-icon><Bell /></el-icon>
          </button>
        </div>
      </header>

      <main class="main-content">
        <router-view />
      </main>
    </div>

    <!-- 弹窗 -->
    <WorkScheduleModal v-model="showScheduleModal" />
    <NotificationPanel />
    <CreateGroupDialog v-model="showCreateGroup" />
    <JoinGroupDialog v-model="showJoinGroup" />
  </div>
</template>

<style scoped>
.app-layout {
  display: flex;
  min-height: 100vh;
  background: var(--gg-bg);
}

/* ── 侧边栏 ── */
.sidebar {
  width: 240px;
  background: var(--gg-bg-card);
  border-right: 1px solid var(--gg-border);
  display: flex;
  flex-direction: column;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  z-index: 100;
}

.sidebar-top {
  padding: 20px;
}

.logo {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  user-select: none;
}

.logo-icon {
  font-size: 24px;
}

.logo-text {
  font-size: 20px;
  font-weight: 700;
  background: var(--gg-gradient);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

/* ── 导航 ── */
.sidebar-nav {
  padding: 0 12px;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 14px;
  border-radius: var(--gg-radius-sm);
  color: var(--gg-text-secondary);
  text-decoration: none;
  font-size: 14px;
  transition: all 0.2s;
}

.nav-item:hover {
  background: var(--gg-bg-hover);
  color: var(--gg-text);
}

.nav-item--active {
  background: rgba(5, 150, 105, 0.1);
  color: var(--gg-primary);
}

.nav-icon {
  font-size: 16px;
}

/* ── 分割线 ── */
.sidebar-divider {
  height: 1px;
  background: var(--gg-border);
  margin: 12px 20px;
}

/* ── 群组操作按钮 ── */
.sidebar-group-actions {
  display: flex;
  gap: 8px;
  padding: 0 12px;
  margin-bottom: 4px;
}

.group-action-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 8px 10px;
  border-radius: var(--gg-radius-sm);
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.group-action-btn--create {
  background: var(--gg-gradient-green);
  color: white;
  border: none;
}

.group-action-btn--create:hover {
  opacity: 0.9;
  box-shadow: 0 2px 12px rgba(5, 150, 105, 0.3);
}

.group-action-btn--join {
  background: var(--gg-bg-card);
  border: 1px solid var(--gg-border);
  color: var(--gg-text-secondary);
}

.group-action-btn--join:hover {
  border-color: var(--gg-primary);
  color: var(--gg-primary);
}

/* ── 群组列表 ── */
.sidebar-groups {
  flex: 1;
  overflow-y: auto;
  padding: 0 12px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 14px 4px;
}

.section-title {
  font-size: 11px;
  font-weight: 600;
  color: var(--gg-text-muted);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.empty-groups {
  text-align: center;
  padding: 16px 14px;
}

.empty-groups p {
  font-size: 13px;
  color: var(--gg-text-muted);
  margin: 0;
}

.empty-hint {
  font-size: 12px !important;
  margin-top: 4px !important;
  opacity: 0.7;
}

.group-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 14px;
  border-radius: var(--gg-radius-sm);
  cursor: pointer;
  transition: all 0.2s;
}

.group-item:hover {
  background: var(--gg-bg-hover);
}

.group-item--active {
  background: rgba(5, 150, 105, 0.1);
  border-left: 3px solid var(--gg-primary);
}

.group-name {
  font-size: 14px;
  color: var(--gg-text);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.group-count {
  font-size: 12px;
  color: var(--gg-text-muted);
  background: var(--gg-bg-elevated);
  padding: 2px 8px;
  border-radius: 10px;
}

/* ── 底部用户区 ── */
.sidebar-bottom {
  padding: 0 12px 16px;
}

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

.schedule-btn {
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
  padding: 6px 10px;
  border-radius: var(--gg-radius-sm);
  transition: background-color 0.2s;
}

.schedule-btn:hover {
  background: var(--gg-bg-hover);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 14px;
  background: var(--gg-bg);
  border-radius: var(--gg-radius-sm);
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  object-fit: cover;
}

.user-name {
  flex: 1;
  font-size: 14px;
  color: var(--gg-text);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.logout-btn {
  background: none;
  border: none;
  font-size: 16px;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  opacity: 0.6;
  transition: opacity 0.2s;
}

.logout-btn:hover {
  opacity: 1;
}

/* ── 右侧主区域 ── */
.main-wrapper {
  flex: 1;
  margin-left: 240px;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.top-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 28px;
  background: var(--gg-bg-card);
  border-bottom: 1px solid var(--gg-border);
  position: sticky;
  top: 0;
  z-index: 50;
  gap: 12px;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--gg-text);
  margin: 0;
  flex: 1;
}

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

.header-action-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 7px 14px;
  border: 1px solid var(--gg-border);
  border-radius: var(--gg-radius-sm);
  background: var(--gg-bg-card);
  color: var(--gg-text-secondary);
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
}

.header-action-btn:first-child {
  background: var(--gg-gradient-green);
  color: white;
  border: none;
}

.header-action-btn:first-child:hover {
  opacity: 0.9;
  box-shadow: 0 2px 8px rgba(5, 150, 105, 0.3);
}

.header-action-btn:not(:first-child):hover {
  border-color: var(--gg-primary);
  color: var(--gg-primary);
}

.icon-btn {
  position: relative;
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  padding: 8px;
  border-radius: var(--gg-radius-sm);
  transition: background-color 0.2s;
}

.icon-btn:hover {
  background: var(--gg-bg-hover);
}

.badge {
  position: absolute;
  top: 2px;
  right: 2px;
  background: var(--gg-danger);
  color: white;
  font-size: 10px;
  font-weight: 700;
  min-width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  border-radius: 8px;
  padding: 0 4px;
}

.main-content {
  flex: 1;
  padding: 24px 28px;
}

/* ── 汉堡按钮 ── */
.hamburger-btn {
  display: none;
  flex-direction: column;
  justify-content: center;
  gap: 4px;
  width: 36px;
  height: 36px;
  padding: 8px 6px;
  background: none;
  border: 1px solid var(--gg-border);
  border-radius: var(--gg-radius-sm);
  cursor: pointer;
}

.hamburger-line {
  display: block;
  width: 100%;
  height: 2px;
  background: var(--gg-text);
  border-radius: 1px;
}

/* ── 移动端遮罩 ── */
.sidebar-overlay {
  display: none;
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.4);
  z-index: 90;
}

/* ── 移动端适配 ── */
@media (max-width: 768px) {
  .sidebar {
    transform: translateX(-100%);
    transition: transform 0.3s ease;
    box-shadow: none;
  }

  .sidebar--open {
    transform: translateX(0);
    box-shadow: 4px 0 24px rgba(0, 0, 0, 0.15);
  }

  .sidebar-overlay {
    display: block;
  }

  .main-wrapper {
    margin-left: 0;
  }

  .hamburger-btn {
    display: flex;
  }

  .header-action-label {
    display: none;
  }

  .header-action-btn {
    padding: 7px 10px;
  }

  .top-header {
    padding: 0 16px;
  }

  .main-content {
    padding: 16px;
  }
}

@media (min-width: 769px) and (max-width: 1024px) {
  .header-action-label {
    display: none;
  }
}
</style>
