<script setup>
import { ref, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import logo from '@/assets/icon/logo.svg'
import { navMenus as importedNavMenus } from './_nav-menus.js'

// Components
import UserProfile from './_user-profile.vue'
import Footer from './_footer.vue'

// 接收父组件传递的 themeCustomizerRef
const props = defineProps({
  themeCustomizerRef: {
    type: Object,
    default: null,
  },
})

const tititleName = import.meta.env.VITE_APP_NAME

const route = useRoute()

// 打开主题定制器
const openThemeCustomizer = () => {
  if (props.themeCustomizerRef?.openDrawer) {
    props.themeCustomizerRef.openDrawer()
  }
}

// 导航菜单配置（使用统一的菜单数据）
const navMenus = ref(importedNavMenus)

// 移动端抽屉
const mobileDrawer = ref(false)

// 当前激活的菜单索引
const activeMenuIndex = ref(0)

// 菜单打开状态控制
const menuOpenStates = ref({})

// 记录哪些菜单刚被点击关闭（防止 hover 立即重新打开）
const recentlyClosedMenus = ref({})

// 根据当前路由判断激活的菜单
const updateActiveMenu = () => {
  const currentPath = route.path

  // 遍历所有菜单，查找匹配的路由
  for (let i = 0; i < navMenus.value.length; i++) {
    const menu = navMenus.value[i]

    // 检查是否是直接路由
    if (menu.to && currentPath === menu.to) {
      activeMenuIndex.value = i

      return
    }

    // 检查子菜单
    if (menu.children) {
      for (const child of menu.children) {
        if (child.to && currentPath === child.to) {
          activeMenuIndex.value = i

          return
        }
      }
    }
  }
}

// 计算是否激活
const isMenuActive = computed(() => {
  return index => index === activeMenuIndex.value
})

// 监听路由变化
watch(() => route.path, () => {
  updateActiveMenu()

  // 关闭所有下拉菜单
  menuOpenStates.value = {}
}, { immediate: true })

// 处理菜单项点击
const handleMenuClick = index => {
  activeMenuIndex.value = index

  // 点击后关闭下拉菜单
  menuOpenStates.value[index] = false

  // 标记为最近关闭，防止 hover 立即重新打开
  recentlyClosedMenus.value[index] = true

  // 300ms 后允许 hover 重新打开
  setTimeout(() => {
    recentlyClosedMenus.value[index] = false
  }, 300)
}
</script>

<template>
  <v-layout class="layout-wrapper">
    <!-- 顶部导航栏 -->
    <v-app-bar elevation="0" height="64" class="horizontal-nav-bar border-b">
      <v-container fluid class="px-6">
        <div class="d-flex align-center w-100">
          <!-- Logo 和品牌名 -->
          <RouterLink to="/" class="app-logo d-flex align-center text-decoration-none">
            <v-img class="logo-icon" :src="logo" alt="Logo" />
            <h1 class="logo-title text-uppercase mb-0 ms-2">
              {{ tititleName }}
            </h1>
          </RouterLink>

          <!-- 水平导航菜单 - 桌面端 -->
          <div class="horizontal-nav-menu d-none d-lg-flex align-center flex-grow-1 ms-8">
            <template v-for="(menu, index) in navMenus" :key="index">
              <!-- 有子菜单的导航项 -->
              <v-menu v-if="menu.children" v-model="menuOpenStates[index]" :close-on-content-click="true" offset="12"
                transition="slide-y-transition" open-on-hover>
                <template #activator="{ props }">
                  <v-btn v-bind="props" variant="text" class="nav-menu-btn px-3"
                    :class="{ 'nav-menu-btn--active': isMenuActive(index) }" height="40"
                    @mouseenter="!recentlyClosedMenus[index] && (menuOpenStates[index] = true)"
                    @mouseleave="menuOpenStates[index] = false">
                    <v-icon :icon="menu.icon" size="20" start />
                    <span>{{ menu.title }}</span>
                    <v-badge v-if="menu.badge" :content="menu.badge" color="error" inline class="ms-1" />
                    <v-icon icon="ri-arrow-down-s-line" size="18" end />
                  </v-btn>
                </template>

                <v-list class="nav-dropdown-menu" min-width="220" @mouseenter="menuOpenStates[index] = true"
                  @mouseleave="menuOpenStates[index] = false">
                  <v-list-item v-for="(child, childIndex) in menu.children" :key="childIndex" :to="child.to"
                    :href="child.href" :target="child.target" class="nav-dropdown-item" @click="handleMenuClick(index)">
                    <template #prepend>
                      <v-icon :icon="child.icon" size="20" />
                    </template>
                    <v-list-item-title>{{ child.title }}</v-list-item-title>
                  </v-list-item>
                </v-list>
              </v-menu>

              <!-- 无子菜单的导航项 -->
              <v-btn v-else :to="menu.to" variant="text" class="nav-menu-btn px-3"
                :class="{ 'nav-menu-btn--active': isMenuActive(index) }" height="40" @click="handleMenuClick(index)">
                <v-icon :icon="menu.icon" size="20" start />
                <span>{{ menu.title }}</span>
              </v-btn>
            </template>
          </div>

          <v-spacer />

          <!-- 右侧工具栏 -->
          <div class="d-flex align-center toolbar-actions">
            <!-- 搜索按钮 -->
            <v-btn color="primary"  icon variant="text" size="small">
              <v-icon icon="mdi-magnify" size="22" />
            </v-btn>

            <!-- 通知 -->
            <v-btn color="primary"  icon variant="text" size="small">
              <v-badge dot color="error" offset-x="2" offset-y="2">
                  <v-icon icon="mdi-bell-outline" size="22" />
              </v-badge>
            </v-btn>

            <!-- 设置按钮 -->
            <v-btn color="primary"  icon variant="text" size="small" @click="openThemeCustomizer">
              <v-icon icon="mdi-cog-outline" size="22" />
            </v-btn>

            <!-- 用户头像 -->
            <UserProfile />

            <!-- 移动端菜单按钮 -->
            <v-btn icon variant="text" class="d-lg-none ms-2" @click="mobileDrawer = true">
              <v-icon icon="ri-menu-line" size="24" />
            </v-btn>
          </div>
        </div>
      </v-container>
    </v-app-bar>

    <!-- 主要内容区域 -->
    <v-main class="main-content">
      <v-container fluid class="px-6 py-6">
        <slot />
      </v-container>
    </v-main>

    <!-- 移动端导航抽屉 -->
    <v-navigation-drawer v-model="mobileDrawer" temporary location="end" width="280" class="mobile-drawer">
      <v-list class="pa-4">
        <template v-for="(menu, index) in navMenus" :key="index">
          <!-- 有子菜单 -->
          <v-list-group v-if="menu.children">
            <template #activator="{ props }">
              <v-list-item v-bind="props">
                <template #prepend>
                  <v-icon :icon="menu.icon" size="20" />
                </template>
                <v-list-item-title>{{ menu.title }}</v-list-item-title>
              </v-list-item>
            </template>

            <v-list-item v-for="(child, childIndex) in menu.children" :key="childIndex" :to="child.to" :href="child.href"
              :target="child.target" @click="mobileDrawer = false">
              <template #prepend>
                <v-icon :icon="child.icon" size="18" class="ms-4" />
              </template>
              <v-list-item-title>{{ child.title }}</v-list-item-title>
            </v-list-item>
          </v-list-group>

          <!-- 无子菜单 -->
          <v-list-item v-else :to="menu.to" @click="mobileDrawer = false">
            <template #prepend>
              <v-icon :icon="menu.icon" size="20" />
            </template>
            <v-list-item-title>{{ menu.title }}</v-list-item-title>
          </v-list-item>
        </template>
      </v-list>
    </v-navigation-drawer>

    <!-- 页脚 -->
    <Footer />

  </v-layout>
</template>

<style lang="scss" scoped>
// 整体布局
.layout-wrapper {
  min-block-size: 100vh;
  background-color: rgb(var(--v-theme-background));
}

// 顶部导航栏
.horizontal-nav-bar {

  position: fixed !important;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  /* 确保在其他元素之上 */
  box-shadow: 0 4px 8px -4px rgba(var(--v-shadow-key-umbra-color), 42%) !important;

  background-color: rgb(var(--v-theme-surface)) !important;
  border-block-end: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));

  :deep(.v-toolbar__content) {
    padding: 0;
  }
}

// Logo 样式
.app-logo {
  .logo-icon {
    inline-size: 32px;
    block-size: 32px;
    display: flex;
    align-items: center;

    :deep(svg) {
      inline-size: 100%;
      block-size: 100%;
    }
  }

  .logo-title {
    font-size: 1.375rem;
    font-weight: 700;
    line-height: 1.5;
    color: rgb(var(--v-theme-primary));
    letter-spacing: 0.5px;
    transition: color 0.2s ease;
  }

  &:hover {
    .logo-title {
      color: rgb(var(--v-theme-primary));
      opacity: 0.9;
    }
  }
}

// 水平导航菜单
.horizontal-nav-menu {
  gap: 0.25rem;

  .nav-menu-btn {
    font-size: 0.9375rem;
    font-weight: 500;
    text-transform: none;
    letter-spacing: 0.15px;
    color: rgba(var(--v-theme-on-surface), var(--v-high-emphasis-opacity));
    border-radius: 20px;
    transition: color 0.2s ease, background 0.2s ease, box-shadow 0.2s ease;

    :deep(.v-btn__content) {
      gap: 0.5rem;
      font-weight: 600;
      color: rgba(var(--v-theme-on-surface), var(--v-high-emphasis-opacity));
      align-items: center;
      display: flex;
    }

    :deep(.v-icon) {
      color: rgba(var(--v-theme-on-surface), var(--v-high-emphasis-opacity));
    }

    :deep(span) {
      color: rgba(var(--v-theme-on-surface), var(--v-high-emphasis-opacity));
      line-height: 1;
    }

    // 未选中状态 - 悬停效果
    &:hover:not(.nav-menu-btn--active) {
      color: rgba(var(--v-theme-on-surface), 0.87) !important;
      background-color: rgba(var(--v-theme-on-surface), 0.04);

      :deep(.v-btn__content) {
        color: rgba(var(--v-theme-on-surface), 0.87) !important;
      }

      :deep(.v-icon) {
        color: rgba(var(--v-theme-on-surface), 0.87) !important;
      }

      :deep(span) {
        color: rgba(var(--v-theme-on-surface), 0.87) !important;
      }
    }

    // 选中状态（紫色背景 + 白色文字）
    &.nav-menu-btn--active {
      color: rgb(255, 255, 255) !important;
      background: linear-gradient(135deg, rgb(var(--v-theme-primary)) 0%, #7c3aed 100%);
      box-shadow: 0 2px 8px rgba(var(--v-theme-primary), 0.3);

      :deep(.v-btn__content) {
        color: rgb(255, 255, 255) !important;
      }

      :deep(.v-icon) {
        color: rgb(255, 255, 255) !important;
      }

      :deep(span) {
        color: rgb(255, 255, 255) !important;
      }

      &:hover {
        color: rgb(255, 255, 255) !important;
        background: linear-gradient(135deg, rgb(var(--v-theme-primary)) 0%, #7c3aed 100%);
        box-shadow: 0 4px 12px rgba(var(--v-theme-primary), 0.4);

        :deep(.v-btn__content) {
          color: rgb(255, 255, 255) !important;
        }

        :deep(.v-icon) {
          color: rgb(255, 255, 255) !important;
        }

        :deep(span) {
          color: rgb(255, 255, 255) !important;
        }
      }
    }

    // Badge 样式
    :deep(.v-badge) {
      .v-badge__badge {
        font-size: 0.6875rem;
        font-weight: 600;
        min-inline-size: 18px;
        block-size: 18px;
        padding: 0 4px;
      }
    }
  }
}

// 下拉菜单样式
.nav-dropdown-menu {
  border-radius: 10px;
  padding-block: 0.5rem;
  box-shadow: 0 4px 20px rgba(var(--v-shadow-key-umbra-opacity), 0.15);
  background-color: rgb(var(--v-theme-surface));

  .nav-dropdown-item {
    border-radius: 8px;
    margin-inline: 0.5rem;
    margin-block: 0.25rem;
    padding-inline: 1rem;
    min-block-size: 44px;
    transition: all 0.2s ease;

    &:hover {
      background-color: rgba(var(--v-theme-primary), 0.08);

      :deep(.v-list-item-title) {
        color: rgb(var(--v-theme-primary));
      }

      :deep(.v-icon) {
        color: rgb(var(--v-theme-primary));
      }
    }

    :deep(.v-list-item__prepend) {
      .v-icon {
        opacity: 0.8;
        transition: all 0.2s ease;
      }
    }

    :deep(.v-list-item-title) {
      font-size: 0.9375rem;
      font-weight: 500;
      transition: color 0.2s ease;
    }
  }
}

// 右侧工具栏
.toolbar-actions {
  gap: 0.25rem;

  .v-btn {
    transition: all 0.2s ease;

    &:hover {
      background-color: rgba(var(--v-theme-on-surface), 0.08);
      transform: translateY(-1px);
    }

    &:active {
      transform: translateY(0);
    }
  }
}

// 主内容区域
.main-content {
  background-color: rgb(var(--v-theme-background));
  min-height: calc(100vh - 64px);
  padding-bottom: 60px;
}

// 移动端抽屉
.mobile-drawer {
  :deep(.v-list) {
    .v-list-item {
      border-radius: 8px;
      margin-block: 0.25rem;
      transition: all 0.2s ease;

      &:hover {
        background-color: rgba(var(--v-theme-primary), 0.08);
      }

      &.v-list-item--active {
        background-color: rgba(var(--v-theme-primary), 0.12);
        color: rgb(var(--v-theme-primary));
      }
    }

    .v-list-group {
      .v-list-item {
        &:hover {
          background-color: rgba(var(--v-theme-primary), 0.06);
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1264px) {
  .horizontal-nav-menu {
    display: none !important;
  }
}

@media (max-width: 600px) {
  .app-logo {
    .logo-title {
      font-size: 1.125rem;
    }
  }

  .toolbar-actions {
    gap: 0;

    .v-btn {
      inline-size: 40px;
      block-size: 40px;
    }
  }

  .horizontal-nav-bar {
    :deep(.v-container) {
      padding-inline: 1rem;
    }
  }
}

// 暗黑模式优化
.v-theme--dark {
  .horizontal-nav-bar {
    border-block-end-color: rgba(var(--v-border-color), 0.2);
  }

  .nav-dropdown-menu {
    box-shadow: 0 4px 24px rgba(0, 0, 0, 0.4);
  }
}
</style>