<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'
import { usePermissionStore, type MenuItem } from '@/stores/permission'

const route = useRoute()
const router = useRouter()
const appStore = useAppStore()
const userStore = useUserStore()
const permStore = usePermissionStore()

const collapsed = computed(() => appStore.collapsed)

const menus = computed(() => permStore.menus)

const activeMenu = ref(route.path)

watch(() => route.path, (val) => {
  activeMenu.value = val
})

function handleSelect(path: string) {
  router.push(path)
}
</script>

<template>
  <div class="sidebar-container" :class="{ collapsed }">
    <div class="logo">
      <span v-if="!collapsed" class="logo-text">CUIT Gym</span>
      <span v-else class="logo-text-mini">CG</span>
    </div>
    <el-menu
      :default-active="activeMenu"
      :collapse="collapsed"
      background-color="#001529"
      text-color="#ffffffb3"
      active-text-color="#fff"
      @select="handleSelect"
    >
      <template v-for="menu in menus" :key="menu.path">
        <el-sub-menu v-if="menu.children?.length" :index="menu.path">
          <template #title>
            <el-icon><component :is="menu.meta.icon" /></el-icon>
            <span>{{ menu.meta.title }}</span>
          </template>
          <el-menu-item
            v-for="child in menu.children"
            :key="child.path"
            :index="child.path"
          >
            <el-icon><component :is="child.meta.icon" /></el-icon>
            <span>{{ child.meta.title }}</span>
          </el-menu-item>
        </el-sub-menu>
        <el-menu-item v-else :index="menu.path">
          <el-icon><component :is="menu.meta.icon" /></el-icon>
          <span>{{ menu.meta.title }}</span>
        </el-menu-item>
      </template>
    </el-menu>
  </div>
</template>

<style scoped>
.sidebar-container {
  width: var(--sidebar-width, 220px);
  height: 100vh;
  background: #001529;
  overflow-y: auto;
  overflow-x: hidden;
  transition: width 0.3s;
}
.sidebar-container.collapsed {
  width: 64px;
}
.logo {
  height: 64px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #002140;
}
.logo-text {
  color: #fff;
  font-size: 18px;
  font-weight: 700;
  white-space: nowrap;
}
.logo-text-mini {
  color: #fff;
  font-size: 18px;
  font-weight: 700;
}
:deep(.el-menu) {
  border-right: none;
}
:deep(.el-menu-item.is-active) {
  background-color: var(--color-primary, #1890ff) !important;
}
</style>
