<script setup>
import { computed, ref } from 'vue';
import { RouterLink, useRouter } from 'vue-router';
import { roleNavigation, routeFor } from '@/lib/navigation';
import { sessionStore } from '@/stores/session';

const props = defineProps({
  role: { type: String, required: true },
  page: { type: String, required: true },
  title: { type: String, required: true },
  description: { type: String, default: '' }
});

const router = useRouter();
const open = ref(false);
const user = computed(() => sessionStore.state.user || {});
const nav = computed(() => roleNavigation(props.role, user.value.adminLevel));
const groups = computed(() => [...new Set(nav.value.map(item => item.group))]);
const roleTitle = computed(() => props.role === 'candidate' ? '考生中心' : props.role === 'admission_school' ? '招生学校工作台' : '考试管理后台');
const scope = computed(() => props.role === 'candidate' ? '仅本人数据' : props.role === 'admission_school' ? '仅本校招生数据' : sessionStore.state.scopeLabel || '当前权限范围');

async function logout() {
  await sessionStore.logout();
  await router.replace('/auth/login');
}
</script>

<template>
  <div class="portal-shell">
    <aside :class="['portal-shell__sidebar', { 'is-open': open }]">
      <RouterLink class="portal-shell__brand" to="/"><span>衡</span><div><strong>衡准考试服务</strong><small>业务管理工作台</small></div></RouterLink>
      <button class="portal-shell__close" type="button" aria-label="关闭菜单" @click="open = false">×</button>
      <p class="portal-shell__role">{{ roleTitle }}</p>
      <nav aria-label="业务导航">
        <section v-for="group in groups" :key="group">
          <strong>{{ group }}</strong>
          <RouterLink v-for="item in nav.filter(row => row.group === group)" :key="item.page" :to="routeFor(role, item.page)" @click="open = false">
            <span>{{ item.label.slice(0, 1) }}</span>{{ item.label }}
          </RouterLink>
        </section>
      </nav>
      <div class="portal-shell__scope"><span>当前数据范围</span><strong>{{ scope }}</strong><small>权限由服务端同步校验</small></div>
    </aside>
    <div v-if="open" class="portal-shell__scrim" @click="open = false"></div>
    <main class="portal-shell__main">
      <header class="portal-shell__topbar">
        <button type="button" aria-label="打开菜单" @click="open = true">☰</button>
        <div><span>{{ roleTitle }}</span><b>/</b><strong>{{ title }}</strong></div>
        <div class="portal-shell__user"><i>{{ String(user.displayName || '用').slice(0, 1) }}</i><span><strong>{{ user.displayName || user.username }}</strong><small>{{ scope }}</small></span><button type="button" title="退出登录" @click="logout">退出</button></div>
      </header>
      <section class="portal-shell__content">
        <header class="portal-page-heading"><div><p>{{ role === 'candidate' ? '考生服务' : role === 'admission_school' ? '招生学校工作台' : '考试业务管理' }}</p><h1>{{ title }}</h1><span>{{ description }}</span></div><slot name="actions" /></header>
        <slot />
      </section>
    </main>
  </div>
</template>
