<script setup lang="ts">
import { shallowRef, onBeforeMount, type Component } from 'vue';
import { RouterView, RouterLink, useRoute, useRouter } from 'vue-router';
import { useAdminLocale } from '../composables/useAdminLocale';
import { useAuthStore } from '../stores/auth';
import DashboardSubNav from '../components/DashboardSubNav.vue';
import { usePermissions } from '../composables/usePermissions';
import { AdminPerm } from '../constants/permissions';

const auth = useAuthStore();
const route = useRoute();
const router = useRouter();
const { t } = useAdminLocale();
const { hasPermission, role } = usePermissions();
const agentDashboard = shallowRef<Component | null>(null);

const showSupportShortcuts = shallowRef(false);

onBeforeMount(async () => {
  // router beforeEach 已执行过 ensureStaffSession，此处仅做菜单路由重定向逻辑，不再重复远程请求
  if (auth.isAdmin.value) {
    const code = role.value;
    if (code === 'FINANCE_ADMIN' && route.path === '/') {
      await router.replace('/dashboard/players');
    } else if (code === 'SUPPORT') {
      showSupportShortcuts.value = true;
      if (route.path === '/' || route.path === '/dashboard/players') {
        if (hasPermission(AdminPerm.usersView, AdminPerm.agentsView)) {
          await router.replace('/users');
        } else if (hasPermission(AdminPerm.bets)) {
          await router.replace('/bets');
        }
      }
    }
  } else {
    agentDashboard.value = (await import('./agent/Dashboard.vue')).default;
  }
});
</script>

<template>
  <template v-if="auth.isAdmin.value">
    <div v-if="showSupportShortcuts" class="support-shortcuts">
      <RouterLink v-if="hasPermission(AdminPerm.usersView, AdminPerm.agentsView)" to="/users" class="support-link">
        {{ t('nav.agents_players') }}
      </RouterLink>
      <RouterLink v-if="hasPermission(AdminPerm.bets)" to="/bets" class="support-link">
        {{ t('nav.bets') }}
      </RouterLink>
      <RouterLink v-if="hasPermission(AdminPerm.reports)" to="/finance-logs" class="support-link">
        {{ t('nav.finance_logs') }}
      </RouterLink>
    </div>
    <div class="dashboard-shell">
      <div class="list-chrome">
        <div class="list-chrome__row">
          <div class="list-chrome__left">
            <DashboardSubNav embedded />
          </div>
        </div>
      </div>
      <RouterView />
    </div>
  </template>
  <component v-else :is="agentDashboard" />
</template>

<style scoped>
.home-boot {
  min-height: 240px;
}

.support-shortcuts {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 12px;
}

.support-link {
  padding: 8px 14px;
  border-radius: 8px;
  border: 1px solid var(--border);
  background: #fff;
  font-size: 13px;
  font-weight: 650;
  color: var(--text);
}

.support-link:hover {
  border-color: var(--primary);
  color: var(--primary);
}

.dashboard-shell :deep(.list-chrome) {
  margin-bottom: 4px;
}
</style>
