<script setup lang="ts">
import UserAction from '@/components/admin/UserAction.vue'
import type { MenuOption } from 'naive-ui'
import { computed, onMounted, ref, useTemplateRef } from 'vue'
import { useRouter } from 'vue-router'
import { useNowUser } from '@/stores/now-user.js'
import { useHead } from '@unhead/vue'

useHead({
  titleTemplate: '%s | 管理面板 | NayHome',
})

const ROUTER = useRouter()
const NOWUSER = useNowUser()

const menu = useTemplateRef('menu')

const selectOption = ref('')
const options = computed<MenuOption[]>(() => [
  {
    label: '总览',
    key: '',
  },
  {
    label: '用户',
    key: 'user-basic',
    children: [
      {
        label: '资料',
        key: 'user-info',
      },
      {
        label: '安全',
        key: 'user-security',
      },
    ],
  },
  {
    label: '内容',
    key: 'user-creation',
    children: [
      {
        label: '上传',
        key: 'user-upload',
      },
      {
        label: '剧本',
        key: 'user-script',
      },
    ],
  },
  {
    label: 'NyaHome 管理后台',
    key: 'nyahome',
    show: NOWUSER.is_admin,
  },
])

function handleMenuClick(key: string) {
  ROUTER.push(`/admin/${key}`)
}

onMounted(() => {
  const key = ROUTER.currentRoute.value.fullPath.replace('/admin/', '')
  if (key.endsWith('/admin')) {
    selectOption.value = ''
  } else if (key) {
    selectOption.value = key
    menu.value?.showOption(key)
  } else {
    selectOption.value = ''
  }
})
</script>

<template>
  <div id="user-page">
    <div id="user-page-sidebar">
      <user-action />
      <div class="nyahome-card">
        <n-menu ref="menu" v-model:value="selectOption" :options @update:value="handleMenuClick" />
      </div>
    </div>

    <router-view v-slot="{ Component }">
      <div id="user-page-content">
        <keep-alive>
          <component :is="Component" />
        </keep-alive>
      </div>
    </router-view>
  </div>
</template>

<style scoped lang="scss">
div#user-page {
  min-width: min(1200px, 90%);
  width: min(1200px, 90%);
  min-height: 0;
  padding: 6px 20px;
  display: flex;
  flex-direction: row;
  gap: 10px;

  div#user-page-sidebar {
    flex: 0;
    flex-basis: 350px;
    min-height: 0;
    overflow: auto;

    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  div#user-page-content {
    flex: 1;
    min-height: 0;
    overflow: auto;

    display: flex;
    flex-direction: column;
    gap: 10px;
  }
}
</style>
