<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { RouterView, RouterLink, useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '../stores/auth';
import { useAdminLocale } from '../composables/useAdminLocale';
import { useSmokeTestsAllowed } from '../composables/useSmokeTestsAllowed';
import { usePermissions } from '../composables/usePermissions';
import { AdminPerm } from '../constants/permissions';
import AdminLocaleSwitcher from '../components/AdminLocaleSwitcher.vue';
import AdminNavIcon from '../components/AdminNavIcon.vue';
import { resolveAdminBreadcrumb } from '../utils/admin-breadcrumb';
import { useDepositPendingCount } from '../composables/useDepositPendingCount';
import { prefetchRouteChunks } from '../utils/route-prefetch';

const route = useRoute();
const router = useRouter();
const auth = useAuthStore();
const { t } = useAdminLocale();
const { allowed: smokeTestsAllowed, ensureLoaded: ensureSmokeTestsAllowed } = useSmokeTestsAllowed();
const { hasPermission, role: adminRole } = usePermissions();
const { pendingCount: depositPendingCount, startDepositPendingPolling, stopDepositPendingPolling } =
  useDepositPendingCount();

/**
 * 列表页 KeepAlive 白名单（与各页面 defineOptions({ name }) 保持一致）。
 * 不含 Settlement/MatchEventEditor/MatchMarketsPage 等带参数的详情页，避免缓存污染。
 */
const keepAliveIncludes = [
  'AdminBets',
  'AdminCashback',
  'AdminMatches',
  'AdminMatchesOutrights',
  'AdminDepositManage',
  'AdminStaffManage',
  'AdminFinanceLogs',
  'AdminAgentManager',
  'AdminContents',
  'AdminMediaLibrary',
  'AdminAudit',
  'AgentPlayers',
  'AgentBets',
];

const canSeeDepositPending = computed(
  () => auth.isAdmin.value && hasPermission(AdminPerm.depositReview, AdminPerm.depositManage),
);

const sidebarOpen = ref(false);
const isMobileNav = ref(false);

type AdminMenuItem = {
  key: string;
  path: string;
  label: string;
  icon: string;
  matchPrefix?: boolean;
  permissions: string[];
  /** Hide for these admin role codes (SUPER_ADMIN is never excluded). */
  excludeRoles?: string[];
};

function menuVisible(item: AdminMenuItem): boolean {
  const code = adminRole.value;
  if (item.path === '/smoke-tests' && smokeTestsAllowed.value === false) return false;
  if (code && code !== 'SUPER_ADMIN' && item.excludeRoles?.includes(code)) return false;
  if (!hasPermission(...item.permissions)) return false;

  const visible = auth.user.value?.visibleMenus;
  if (visible) {
    const list = visible.split(',');
    return list.includes(item.key);
  }
  return true;
}

const adminMenus = computed(() => {
  const items: AdminMenuItem[] = [
    { key: 'dashboard', path: '/', label: t('nav.dashboard'), icon: 'dashboard', matchPrefix: true, permissions: [AdminPerm.reports], excludeRoles: ['SUPPORT'] },
    { key: 'matches', path: '/matches', label: t('nav.matches'), icon: 'matches', matchPrefix: true, permissions: [AdminPerm.matches] },
    { key: 'users', path: '/users', label: t('nav.agents_players'), icon: 'users', matchPrefix: true, permissions: [AdminPerm.usersView, AdminPerm.agentsView] },
    { key: 'finance-logs', path: '/finance-logs', label: t('nav.finance_logs'), icon: 'finance', permissions: [AdminPerm.reports], excludeRoles: ['MATCH_ADMIN'] },
    { key: 'deposit', path: '/deposit', label: t('nav.deposit_manage'), icon: 'deposit', matchPrefix: true, permissions: [AdminPerm.depositManage, AdminPerm.depositReview] },
    { key: 'cashback', path: '/cashback', label: t('nav.cashback'), icon: 'cashback', permissions: [AdminPerm.cashback], excludeRoles: ['MATCH_ADMIN', 'SUPPORT'] },
    { key: 'bets', path: '/bets', label: t('nav.bets'), icon: 'bets', permissions: [AdminPerm.bets] },
    { key: 'contents', path: '/contents', label: t('nav.contents'), icon: 'contents', permissions: [AdminPerm.content] },
    { key: 'media', path: '/media', label: t('nav.media'), icon: 'media', permissions: [AdminPerm.content, AdminPerm.matches] },
    { key: 'audit', path: '/audit', label: t('nav.audit'), icon: 'audit', permissions: [AdminPerm.audit], excludeRoles: ['MATCH_ADMIN'] },
    { key: 'staff', path: '/staff', label: t('nav.staff'), icon: 'users', permissions: [AdminPerm.settings] },
    { key: 'smoke-tests', path: '/smoke-tests', label: t('nav.smoke_tests'), icon: 'smoke-tests', permissions: [AdminPerm.settings] },
  ];
  return items.filter(menuVisible);
});

const agentMenus = computed(() => [
  { path: '/', label: t('nav.dashboard'), icon: 'dashboard' },
  { path: '/my-players', label: t('nav.agents_players'), icon: 'users' },
  { path: '/finance-logs', label: t('nav.finance_logs'), icon: 'finance' },
  { path: '/my-bets', label: t('nav.myBets'), icon: 'bets' },
]);

const menus = computed(() => (auth.isAdmin.value ? adminMenus.value : agentMenus.value));

function isMatchesSectionPath(path: string) {
  return (
    path === '/matches' ||
    path.startsWith('/matches/') ||
    path.startsWith('/outrights/') ||
    path.startsWith('/settlement/')
  );
}

function isDashboardSectionPath(path: string) {
  return path === '/' || path === '/dashboard/players';
}

function isDepositSectionPath(path: string) {
  return path === '/deposit' || path === '/deposit-orders' || path === '/payment-methods';
}

function isMenuActive(menu: { path: string; matchPrefix?: boolean }, path: string) {
  if (path === menu.path) return true;
  if (!menu.matchPrefix) return false;
  if (menu.path === '/') return isDashboardSectionPath(path);
  if (menu.path === '/deposit') return isDepositSectionPath(path);
  if (menu.path === '/matches') return isMatchesSectionPath(path);
  return path.startsWith(`${menu.path}/`);
}

const currentLabel = computed(() => {
  const hit = menus.value.find((m) => isMenuActive(m, route.path));
  return hit?.label ?? '';
});

const topbarCrumbs = computed(() => resolveAdminBreadcrumb(route.path, t, route.query));

const roleLabel = computed(() => {
  if (auth.isAdmin.value) {
    const code = adminRole.value;
    if (code === 'MATCH_ADMIN') return t('role.match_admin');
    if (code === 'FINANCE_ADMIN') return t('role.finance_admin');
    if (code === 'SUPPORT') return t('role.support');
    if (code === 'SUPER_ADMIN') return t('role.super_admin');
    return t('role.admin');
  }
  const level = auth.user.value?.agentLevel;
  if (auth.isAgent.value && level != null && level > 0) {
    return t('role.agent_level', { n: level });
  }
  return t('role.agent');
});

const currentUser = computed(() => auth.user.value);
const isAdminPortal = computed(() => auth.isAdmin.value);

const userInitial = computed(() =>
  (currentUser.value?.username ?? '').charAt(0).toUpperCase()
);

function syncMobileNav() {
  isMobileNav.value = window.matchMedia('(max-width: 1023px)').matches;
  if (!isMobileNav.value) {
    sidebarOpen.value = false;
  }
}

function toggleSidebar() {
  sidebarOpen.value = !sidebarOpen.value;
}

function closeSidebar() {
  sidebarOpen.value = false;
}

function onNavClick() {
  if (isMobileNav.value) {
    closeSidebar();
  }
}

function prefetchNavRoute(path: string) {
  prefetchRouteChunks(router, path);
}

function logout() {
  auth.logout();
  router.push('/login');
}

onMounted(() => {
  syncMobileNav();
  window.addEventListener('resize', syncMobileNav);
  if (auth.isAdmin.value) {
    void ensureSmokeTestsAllowed();
    if (canSeeDepositPending.value) startDepositPendingPolling();
  }
});

onUnmounted(() => {
  window.removeEventListener('resize', syncMobileNav);
  stopDepositPendingPolling();
});

watch(() => route.path, () => {
  if (isMobileNav.value) {
    closeSidebar();
  }
});
</script>

<template>
  <div class="shell" :class="{ 'shell--nav-open': sidebarOpen && isMobileNav }">
    <button
      v-if="isMobileNav && sidebarOpen"
      type="button"
      class="sidebar-backdrop"
      :aria-label="t('nav.close_menu')"
      @click="closeSidebar"
    />

    <!-- ── Sidebar ── -->
    <aside class="sidebar" :class="{ open: sidebarOpen }">
      <div class="brand">
        <img src="/logo.png" alt="TheBet365" class="brand-logo" />
        <span class="brand-title">{{ isAdminPortal ? t('portal.admin') : t('portal.agent') }}</span>
      </div>

      <nav class="nav">
        <RouterLink
          v-for="m in menus" :key="m.path" :to="m.path"
          class="nav-item"
          :class="{ active: isMenuActive(m, route.path) }"
          @click="onNavClick"
          @mouseenter="prefetchNavRoute(m.path)"
          @focus="prefetchNavRoute(m.path)"
        >
          <AdminNavIcon :name="m.icon" />
          <span class="nav-label">
            {{ m.label }}
            <span
              v-if="'path' in m && m.path === '/deposit' && depositPendingCount > 0"
              class="nav-pending-badge"
              :title="t('deposit.pending_badge', { n: depositPendingCount })"
            >
              {{ depositPendingCount > 99 ? '99+' : depositPendingCount }}
            </span>
          </span>
        </RouterLink>
      </nav>

      <div class="sidebar-foot">TheBet365 &copy; 2026</div>
    </aside>

    <!-- ── Main ── -->
    <div class="main">
      <header class="topbar">
        <div class="topbar-left">
          <button
            v-if="isMobileNav"
            type="button"
            class="btn-menu"
            :aria-label="sidebarOpen ? t('nav.close_menu') : t('nav.open_menu')"
            @click="toggleSidebar"
          >
            <span class="menu-icon" aria-hidden="true" />
          </button>
          <div class="topbar-title">
            <span v-if="!topbarCrumbs" class="topbar-accent" />
            <nav v-if="topbarCrumbs" class="topbar-crumbs" aria-label="Breadcrumb">
              <template v-for="(item, i) in topbarCrumbs" :key="`${item.label}-${i}`">
                <RouterLink
                  v-if="item.to && i < topbarCrumbs.length - 1"
                  :to="item.to"
                  class="crumb-link"
                >
                  {{ item.label }}
                </RouterLink>
                <span v-else class="crumb-current">{{ item.label }}</span>
                <span v-if="i < topbarCrumbs.length - 1" class="crumb-sep" aria-hidden="true">/</span>
              </template>
            </nav>
            <span v-else class="topbar-page-label">{{ currentLabel }}</span>
          </div>
          <div id="topbar-page-actions" class="topbar-page-actions" />
        </div>
        <div class="topbar-right">
          <div class="user-chip">
            <div class="avatar">{{ userInitial }}</div>
            <div class="user-info">
              <span class="user-name">{{ currentUser?.username }}</span>
              <span class="user-role">{{ roleLabel }}</span>
            </div>
          </div>
          <AdminLocaleSwitcher />
          <button class="btn-logout" @click="logout">{{ t('logout') }}</button>
        </div>
      </header>
      <main class="page-main">
        <RouterView v-slot="{ Component, route: layoutRoute }">
          <KeepAlive :max="10" :include="keepAliveIncludes">
            <component :is="Component" :key="layoutRoute.matched[1]?.path ?? layoutRoute.path" />
          </KeepAlive>
        </RouterView>
      </main>
    </div>
  </div>
</template>

<style scoped>
.shell {
  --sidebar-width: 176px;
  display: flex;
  height: 100vh;
  overflow: hidden;
}

/* ── Sidebar ── */
.sidebar {
  width: var(--sidebar-width);
  flex-shrink: 0;
  position: fixed;
  top: 0; left: 0; bottom: 0;
  background: #0a0a0a;
  border-right: 1px solid rgba(255, 255, 255, 0.06);
  display: flex;
  flex-direction: column;
  z-index: 100;
  transition: transform 0.2s ease;
}

.brand {
  height: 56px;
  min-height: 56px;
  padding: 0 10px;
  border-bottom: 1px solid #1a1a1a;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 8px;
  flex-shrink: 0;
  box-sizing: border-box;
}
.brand-logo {
  max-width: 52px;
  max-height: 32px;
  width: auto;
  height: auto;
  object-fit: contain;
  display: block;
  flex-shrink: 0;
}
.brand-title {
  font-size: 12px;
  font-weight: 700;
  line-height: 1.25;
  color: #f0f0f0;
  letter-spacing: 0.02em;
}

.nav {
  flex: 1;
  padding: 8px 6px;
  display: flex;
  flex-direction: column;
  gap: 2px;
  overflow-y: auto;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 10px;
  border-radius: 6px;
  color: #737373;
  font-size: 13px;
  font-weight: 450;
  transition: color 0.15s, background 0.15s;
  letter-spacing: 0;
}
.nav-item :deep(.admin-nav-icon) {
  opacity: 0.72;
  transition: opacity 0.15s;
}
.nav-label {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
  line-height: 1.25;
  flex: 1;
}
.nav-pending-badge {
  flex-shrink: 0;
  min-width: 18px;
  height: 18px;
  padding: 0 5px;
  border-radius: 9px;
  background: #f56c6c;
  color: #fff;
  font-size: 11px;
  font-weight: 700;
  line-height: 18px;
  text-align: center;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.25);
}
.nav-item:hover {
  background: rgba(255, 255, 255, 0.04);
  color: #d4d4d4;
}
.nav-item:hover :deep(.admin-nav-icon) {
  opacity: 0.92;
}
.nav-item.active {
  background: rgba(255, 255, 255, 0.06);
  color: #f5f5f5;
  font-weight: 500;
}
.nav-item.active :deep(.admin-nav-icon) {
  opacity: 1;
}

.sidebar-foot {
  padding: 10px 10px;
  font-size: 10px;
  color: #282828;
  border-top: 1px solid #161616;
  letter-spacing: 0.04em;
}

.sidebar-backdrop {
  position: fixed;
  inset: 0;
  z-index: 90;
  border: none;
  padding: 0;
  margin: 0;
  background: rgba(0, 0, 0, 0.55);
  cursor: pointer;
}

/* ── Main ── */
.main {
  margin-left: var(--sidebar-width);
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.topbar {
  position: sticky; top: 0; z-index: 80;
  height: 56px;
  min-height: 56px;
  box-sizing: border-box;
  display: flex; align-items: center; justify-content: space-between;
  padding: 0 28px;
  background: #0a0a0a;
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}

.topbar-left {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 0;
}

.btn-menu {
  display: none;
  width: 40px;
  height: 40px;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  border: 1px solid #2a2a2a;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.03);
  color: #ccc;
  transition: border-color 0.15s, background 0.15s;
}
.btn-menu:hover {
  border-color: #444;
  background: rgba(255, 255, 255, 0.06);
}
.menu-icon {
  display: block;
  width: 16px;
  height: 2px;
  background: currentColor;
  border-radius: 1px;
  box-shadow: 0 -5px 0 currentColor, 0 5px 0 currentColor;
}

.topbar-title {
  display: flex; align-items: center; gap: 10px;
  font-size: 14px; font-weight: 500;
  color: #f5f5f5;
  letter-spacing: 0;
  min-width: 0;
}
.topbar-page-label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.topbar-crumbs {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 2px 8px;
  font-size: 14px;
  font-weight: 600;
  min-width: 0;
}
.crumb-link {
  color: #737373;
  transition: color 0.15s;
}
.crumb-link:hover {
  color: #f5f5f5;
}
.crumb-current {
  color: #f5f5f5;
}
.crumb-sep {
  color: #525252;
  font-weight: 400;
  user-select: none;
}
.topbar-accent {
  width: 1px; height: 14px;
  background: rgba(255, 255, 255, 0.12);
  flex-shrink: 0;
}

.topbar-page-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
  margin-left: 8px;
}
.topbar-page-actions:empty {
  display: none;
}

.topbar-right {
  display: flex; align-items: center; gap: 12px;
  flex-shrink: 0;
}

.user-chip {
  display: flex; align-items: center; gap: 8px;
}
.avatar {
  width: 28px; height: 28px; border-radius: 50%;
  background: rgba(255, 255, 255, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.1);
  display: flex; align-items: center; justify-content: center;
  font-size: 11px; font-weight: 500; color: #d4d4d4;
  flex-shrink: 0;
}
.user-info {
  display: flex; flex-direction: column; gap: 1px;
}
.user-name {
  font-size: 13px; font-weight: 600; color: #e0e0e0;
  line-height: 1;
}
.user-role {
  font-size: 10px; color: #555;
  line-height: 1;
}

.portal-tag {
  padding: 2px 7px;
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 4px;
  font-size: 11px;
  color: #737373;
  background: transparent;
  font-weight: 500;
  letter-spacing: 0;
}

.btn-logout {
  padding: 5px 14px;
  background: transparent;
  border: 1px solid #2a2a2a;
  border-radius: 6px;
  color: #888;
  font-size: 12px;
  font-family: inherit;
  transition: all 0.15s;
}
.btn-logout:hover { border-color: #444; color: #ccc; }

.page-main {
  flex: 1;
  min-height: 0;
  padding: 20px 28px 28px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}
.page-main > * {
  flex: 1;
  min-height: 0;
}

@media (max-width: 1023px) {
  .sidebar {
    transform: translateX(-100%);
    box-shadow: none;
  }
  .sidebar.open {
    transform: translateX(0);
    box-shadow: 8px 0 32px rgba(0, 0, 0, 0.45);
  }
  .main {
    margin-left: 0;
  }
  .btn-menu {
    display: inline-flex;
  }
  .page-main {
    padding: 16px;
  }
  .topbar {
    padding: 0 14px;
  }
  .user-info,
  .portal-tag {
    display: none;
  }
}

@media (max-width: 640px) {
  .topbar-right {
    gap: 8px;
  }
}

/* Light management shell */
.shell {
  --sidebar-width: 204px;
  height: 100dvh;
  background: var(--bg-body);
  color: var(--text);
}

.sidebar {
  background: #ffffff;
  border-right: 1px solid var(--border);
  box-shadow: 10px 0 28px rgba(56, 49, 37, 0.04);
}

.brand {
  height: 64px;
  min-height: 64px;
  padding: 0 12px;
  border-bottom: 1px solid var(--border-soft);
  justify-content: flex-start;
  gap: 10px;
}

.brand-logo {
  max-width: 56px;
  max-height: 34px;
}

.brand-title {
  font-size: 13px;
  font-weight: 700;
  line-height: 1.25;
  color: #2a2824;
  letter-spacing: 0.02em;
}

.nav {
  padding: 12px 10px;
  gap: 4px;
}

.nav-item {
  gap: 10px;
  min-height: 38px;
  padding: 9px 11px;
  border: 1px solid transparent;
  border-radius: 8px;
  color: #67635c;
  font-size: 13px;
  font-weight: 650;
}

.nav-item :deep(.admin-nav-icon) {
  opacity: 0.86;
}

.nav-item:hover {
  border-color: var(--border-soft);
  background: var(--accent-hover);
  color: var(--text);
}

.nav-item.active {
  border-color: var(--primary);
  background: var(--primary);
  color: #ffffff;
  font-weight: 750;
}

.nav-item.active :deep(.admin-nav-icon),
.nav-item:hover :deep(.admin-nav-icon) {
  opacity: 1;
}

.sidebar-foot {
  padding: 12px 14px;
  border-top: 1px solid var(--border-soft);
  color: #aaa49a;
  letter-spacing: 0;
}

.sidebar-backdrop {
  background: rgba(31, 35, 32, 0.28);
  backdrop-filter: blur(2px);
}

.main {
  background: var(--bg-body);
}

.topbar {
  height: 64px;
  min-height: 64px;
  padding: 0 28px;
  background: rgba(255, 255, 255, 0.92);
  border-bottom: 1px solid var(--border);
  backdrop-filter: blur(14px);
}

.topbar-left {
  gap: 12px;
}

.btn-menu {
  width: 38px;
  height: 38px;
  border-color: var(--border);
  background: #ffffff;
  color: var(--text);
}

.btn-menu:hover {
  border-color: #d5cfc3;
  background: var(--accent-hover);
}

.topbar-title {
  color: var(--text);
  font-size: 15px;
  font-weight: 750;
}

.topbar-crumbs {
  gap: 2px 7px;
  font-size: 14px;
  font-weight: 700;
}

.crumb-link {
  color: var(--text-muted);
}

.crumb-link:hover,
.crumb-current {
  color: var(--text);
}

.crumb-sep {
  color: #b6afa3;
}

.topbar-accent {
  width: 3px;
  height: 18px;
  border-radius: 999px;
  background: var(--primary);
}

.topbar-page-actions {
  margin-left: 10px;
}

.user-chip {
  padding: 4px 8px 4px 4px;
  border: 1px solid var(--border-soft);
  border-radius: 999px;
  background: #fbfaf7;
}

.avatar {
  width: 30px;
  height: 30px;
  border: 1px solid #d6ddd4;
  background: var(--success-bg);
  color: var(--success-text);
  font-weight: 750;
}

.user-name {
  color: var(--text);
  font-weight: 750;
}

.user-role {
  color: var(--text-muted);
  font-weight: 650;
}

.portal-tag {
  padding: 4px 8px;
  border-color: var(--border);
  border-radius: 999px;
  background: #ffffff;
  color: var(--text-muted);
  font-weight: 750;
}

.btn-logout {
  min-height: 32px;
  padding: 0 14px;
  border-color: var(--border);
  border-radius: 7px;
  background: #ffffff;
  color: var(--text);
  font-weight: 700;
}

.btn-logout:hover {
  border-color: var(--danger-border);
  background: var(--danger-bg);
  color: var(--danger-text);
}

.page-main {
  padding: 22px 28px 30px;
  background: var(--bg-body);
}

@media (max-width: 1023px) {
  .sidebar.open {
    box-shadow: 18px 0 46px rgba(56, 49, 37, 0.16);
  }

  .topbar {
    height: auto;
    min-height: 60px;
    padding: 10px 14px;
    align-items: flex-start;
    gap: 10px;
  }

  .topbar-left {
    flex: 1;
    min-width: 0;
  }

  .topbar-title {
    min-width: 0;
  }

  .topbar-crumbs,
  .topbar-page-label {
    max-width: 42vw;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .page-main {
    padding: 14px;
  }
}

@media (max-width: 640px) {
  .topbar {
    flex-wrap: wrap;
  }

  .topbar-right {
    width: 100%;
    justify-content: flex-end;
    gap: 8px;
  }

  .user-chip {
    padding: 0;
    border: none;
    background: transparent;
  }

  .avatar {
    width: 32px;
    height: 32px;
  }

  .btn-logout {
    padding: 0 10px;
  }
}
</style>
