<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { NAvatar, NBreadcrumb, NBreadcrumbItem, NButton, NDrawer, NDrawerContent, NIcon, NLayout, NLayoutHeader, NLayoutSider, NMenu, NSpace } from 'naive-ui'
import { useAuthStore } from '../../stores/auth'
import { useUiStore } from '../../stores/ui'
import { AddOutline } from '@vicons/ionicons5'

const logoLight = new URL('../../assets/logo-light.png', import.meta.url).href
const logoDark = new URL('../../assets/logo-dark.png', import.meta.url).href
const router = useRouter()
const route = useRoute()
const auth = useAuthStore()
const ui = useUiStore()

const baseMenu = [
  { label: '📊 看板', key: 'dashboard' },
  { label: '🏢 租户', key: 'tenants' },
  { label: '👤 用户', key: 'users' },
  { label: '📡 管道', key: 'pipeline' },
  { label: '🏷️ 标签', key: 'tags' },
  { label: '📰 期刊', key: 'journals' },
  { label: '📋 指南', key: 'guidelines' },
  { label: '💊 审批', key: 'drug-approvals' },
  { label: '🔔 公告', key: 'notifications' },
  { label: '🌐 访问记录', key: 'page-views' },
  { label: '💬 反馈', key: 'feedback' },
  { label: '📈 运营', key: 'analytics' },
  { label: '⚙️ 配置', key: 'config' },
]

const menuOptions = computed(() => {
  const isOwner = auth.user?.platform_role === 'platform_owner'
  const rolesItem = { label: '🛡️ 平台角色', key: 'roles' }
  return isOwner ? [...baseMenu.slice(0, 3), rolesItem, ...baseMenu.slice(3)] : baseMenu
})

const activeKey = computed(() => {
  const p = route.path.split('/admin/')[1] || 'dashboard'
  return p
})

function handleMenu(k: string) { router.push(`/admin/${k}`) }

onMounted(() => {
  // 阻止搜索引擎索引管理后台
  let el = document.querySelector('meta[name="robots"]') as HTMLMetaElement | null
  if (!el) {
    el = document.createElement('meta')
    el.setAttribute('name', 'robots')
    document.head.appendChild(el)
  }
  el.setAttribute('content', 'noindex, nofollow')
})
</script>

<template>
  <NLayout has-sider style="min-height:100vh">
    <NLayoutSider v-if="!ui.isMobile" bordered width="200" collapse-mode="transform" :collapsed="ui.sidebarCollapsed">
      <div style="height:64px;display:flex;align-items:center;justify-content:center;border-bottom:1px solid var(--border-color);cursor:pointer;padding:0 12px" @click="router.push('/')" title="OncoLit 肿瘤科研文献，每日更新">
        <img :src="ui.isDark ? logoDark : logoLight" style="height:40px;max-width:100%;object-fit:contain" alt="OncoLit" loading="lazy">
      </div>
      <NMenu :value="activeKey" :options="menuOptions" @update:value="handleMenu" />
    </NLayoutSider>
    <NLayout>
      <NLayoutHeader bordered style="height:56px;display:flex;align-items:center;justify-content:space-between;padding:0 12px 0 24px;background:var(--bg-card)">
        <div style="display:flex;align-items:center;gap:8px">
          <NButton v-if="ui.isMobile" size="small" @click="ui.toggleSidebar()" class="sky-btn">☰</NButton>
          <NBreadcrumb>
            <NBreadcrumbItem @click="router.push('/admin')">管理后台</NBreadcrumbItem>
            <NBreadcrumbItem>{{ menuOptions.find(m=>m.key===activeKey)?.label||'' }}</NBreadcrumbItem>
          </NBreadcrumb>
        </div>
        <NSpace>
          <NButton size="small" class="sky-btn" @click="router.push('/')" title="首页"><template #icon><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg></template></NButton>
          <NButton size="small" class="sky-btn" @click="router.push('/app/feed')">📱 用户端</NButton>
          <NButton size="small" class="sky-btn" @click="ui.toggleDark()"><template #icon><NIcon size="14"><AddOutline /></NIcon></template>{{ ui.isDark ? '☀️' : '🌙' }}</NButton>
          <NAvatar size="small">{{ auth.user?.display_name?.[0]||'A' }}</NAvatar>
        </NSpace>
      </NLayoutHeader>
      <!-- Mobile 抽屉菜单 -->
      <NDrawer v-if="ui.isMobile" :show="!ui.sidebarCollapsed" placement="left" :width="200" @update:show="v => !v && ui.toggleSidebar()">
        <NDrawerContent title="管理后台" closable>
          <NMenu :value="activeKey" :options="menuOptions" @update:value="k => { handleMenu(k); ui.toggleSidebar() }" />
        </NDrawerContent>
      </NDrawer>
      <div style="padding:16px;max-width:1400px">
        <RouterView />
      </div>
    </NLayout>
  </NLayout>
</template>
