<template>
  <div class="admin-shell admin-shell-v2" :class="[`is-${layoutMode}`, { 'is-sidebar-open': sidebarOpen }]">
    <AdminSidebar
      :menus="menus"
      :layout-mode="layoutMode"
      :loading="loadingMenus"
      @close-mobile="sidebarOpen = false"
    />
    <main class="admin-main">
      <AdminTopbar
        :title="route.meta.title || '后台管理'"
        :layout-mode="layoutMode"
        :menu-count="menuCount"
        @toggle-layout="toggleLayout"
        @toggle-sidebar="sidebarOpen = !sidebarOpen"
      />
      <section class="admin-page-surface">
        <router-view />
      </section>
    </main>
    <button v-if="sidebarOpen" class="admin-mobile-mask" type="button" @click="sidebarOpen = false" aria-label="关闭菜单"></button>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import AdminSidebar from './AdminSidebar.vue'
import AdminTopbar from './AdminTopbar.vue'
import { getAdminMenus, getMenuLayout, updateMenuLayout } from '@/api/request/admin'

const route = useRoute()
const menus = ref([])
const layoutMode = ref('double')
const sidebarOpen = ref(false)
const loadingMenus = ref(true)

// 初始化后台菜单和布局偏好，接口失败时使用最小菜单兜底，保证后台可进入。
onMounted(async () => {
  loadingMenus.value = true
  menus.value = await getAdminMenus().catch(() => [{ id: 1, title: '控制台', path: '/dashboard', icon: 'dashboard' }])
  const layout = await getMenuLayout().catch(() => ({ final_layout: 'double' }))
  layoutMode.value = layout.final_layout || 'double'
  loadingMenus.value = false
})

const menuCount = computed(() => menus.value.reduce((total, item) => total + 1 + (item.children?.length || 0), 0))

const toggleLayout = async () => {
  layoutMode.value = layoutMode.value === 'double' ? 'single' : 'double'
  await updateMenuLayout(layoutMode.value).catch(() => null)
}
</script>
