<template>
  <el-container class="layout-container">
    <!-- Sidebar for desktop / Drawer for mobile -->
    <el-aside
      v-if="!isMobile"
      width="220px"
      class="layout-aside"
    >
      <div class="logo">
        <el-icon size="28" color="#fff"><Collection /></el-icon>
        <span class="logo-text">DataPointer</span>
      </div>
      <el-menu
        :default-active="activeRoute"
        router
        class="layout-menu"
      >
        <el-menu-item
          v-for="route in menuRoutes"
          :key="route.path"
          :index="route.path"
        >
          <el-icon>
            <component :is="route.meta?.icon" />
          </el-icon>
          <span>{{ route.meta?.title }}</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <el-container direction="vertical">
      <!-- Header -->
      <el-header class="layout-header" height="56px">
        <div class="header-left">
          <el-button
            v-if="isMobile"
            type="primary"
            text
            @click="drawerVisible = true"
          >
            <el-icon size="22"><Expand /></el-icon>
          </el-button>
          <span class="header-title">{{ pageTitle }}</span>
        </div>
        <div class="header-right">
          <el-button text circle @click="toggleTheme" :icon="isDark ? Sunny : Moon" class="theme-btn" />
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-avatar :size="32" :icon="UserFilled" />
              <span class="username">{{ userStore.userInfo?.real_name || userStore.userInfo?.username }}</span>
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- Main Content -->
      <el-main class="layout-main">
        <router-view v-slot="{ Component }">
          <keep-alive>
            <component :is="Component" v-if="route.meta?.keepAlive" :key="route.path" />
          </keep-alive>
          <component :is="Component" v-if="!route.meta?.keepAlive" :key="route.path" />
        </router-view>
      </el-main>
    </el-container>

    <!-- Mobile Drawer -->
    <el-drawer
      v-model="drawerVisible"
      direction="ltr"
      size="220px"
      :with-header="false"
      class="mobile-drawer"
    >
      <div class="logo">
        <el-icon size="28" color="#fff"><Collection /></el-icon>
        <span class="logo-text">DataPointer</span>
      </div>
      <el-menu
        :default-active="activeRoute"
        router
        class="layout-menu"
        @select="drawerVisible = false"
      >
        <el-menu-item
          v-for="route in menuRoutes"
          :key="route.path"
          :index="route.path"
        >
          <el-icon>
            <component :is="route.meta?.icon" />
          </el-icon>
          <span>{{ route.meta?.title }}</span>
        </el-menu-item>
      </el-menu>
    </el-drawer>
  </el-container>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { UserFilled, Expand, Collection, ArrowDown, Moon, Sunny } from '@element-plus/icons-vue'

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

const drawerVisible = ref(false)
const windowWidth = ref(window.innerWidth)
const isDark = ref(false)

function toggleTheme() {
  isDark.value = !isDark.value
  const html = document.documentElement
  if (isDark.value) {
    html.classList.add('dark')
    localStorage.setItem('theme', 'dark')
  } else {
    html.classList.remove('dark')
    localStorage.setItem('theme', 'light')
  }
}

onMounted(() => {
  const saved = localStorage.getItem('theme')
  if (saved === 'dark') {
    isDark.value = true
    document.documentElement.classList.add('dark')
  }
  window.addEventListener('resize', onResize)
  if (!userStore.userInfo && userStore.token) {
    userStore.fetchUserInfo()
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', onResize)
})

const isMobile = computed(() => windowWidth.value < 768)
const activeRoute = computed(() => route.path)
const pageTitle = computed(() => (route.meta?.title as string) || 'DataPointer')

const menuRoutes = computed(() => {
  const layout = router.getRoutes().find((r) => r.name === 'Layout')
  const routes = layout?.children.filter((r) => r.meta?.title) || []
  // Filter by role permissions
  return routes.filter((r) => {
    const allowedRoles = r.meta?.roles as string[] | undefined
    if (!allowedRoles || allowedRoles.length === 0) return true
    return userStore.hasAnyRole(allowedRoles)
  })
})

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

function onResize() {
  windowWidth.value = window.innerWidth
}

onUnmounted(() => {
  window.removeEventListener('resize', onResize)
})
</script>

<style scoped lang="scss">
.layout-container {
  height: 100vh;
}

.layout-aside {
  background-color: #1a2b4a;
  display: flex;
  flex-direction: column;
}

.logo {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  background-color: #13203a;
  flex-shrink: 0;

  .logo-text {
    color: #fff;
    font-size: 16px;
    font-weight: 600;
    letter-spacing: 1px;
  }
}

.layout-menu {
  border-right: none;
  flex: 1;
  --el-menu-bg-color: #1a2b4a;
  --el-menu-text-color: #b0c4de;
  --el-menu-hover-text-color: #fff;
  --el-menu-active-color: #fff;
}
html.dark .layout-menu {
  --el-menu-bg-color: #141414;
  --el-menu-text-color: #b0b0b0;
  --el-menu-hover-text-color: #fff;
  --el-menu-active-color: #409eff;
}

.layout-header {
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  padding: 0 16px;

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

  .header-title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

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

    .theme-btn {
      color: #606266;
    }
    html.dark .theme-btn {
      color: #b0b0b0;
    }

    .user-info {
      display: flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      color: #606266;

      .username {
        font-size: 14px;
        max-width: 100px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}

.layout-main {
  background-color: #f5f7fa;
  padding: 0;
  overflow-y: auto;
}

html.dark .layout-aside {
  background-color: #141414;
}
html.dark .logo {
  background-color: #0a0a0a;
}
html.dark .layout-header {
  background-color: #1d1e1f;
  box-shadow: 0 1px 4px rgba(0,0,0,0.3);
}
html.dark .header-title {
  color: #e0e0e0;
}
html.dark .user-info {
  color: #b0b0b0;
}
html.dark .layout-main {
  background-color: #0a0a0a;
}
html.dark :deep(.mobile-drawer) .el-drawer__body {
  background-color: #141414;
}

:deep(.mobile-drawer) {
  .el-drawer__body {
    padding: 0;
    background-color: #1a2b4a;
    display: flex;
    flex-direction: column;
  }
}
</style>
