<script setup lang="ts">
import { computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { NButton, NLayout, NLayoutHeader, NLayoutContent, NDropdown, NAvatar } from 'naive-ui'
import { useAuthStore } from '../../stores/auth'
import { useUiStore } from '../../stores/ui'
import { useGlobalLoading } from '../../composables/useGlobalLoading'
import NotificationBell from '../../components/common/NotificationBell.vue'

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 auth = useAuthStore()
const ui = useUiStore()
const { showBar } = useGlobalLoading()

const avatarStyle = computed(() => ({
  background: ui.isDark ? '#1a3a5c' : '#e6f4ff',
  color: 'var(--text-primary)',
}))
const userOptions = computed(() => [
  { label: '📱 进入应用', key: 'app' },
  { label: auth.user?.platform_role ? '🏛 管理后台' : '⚙️ 帐户设置', key: auth.user?.platform_role ? 'admin' : 'settings' },
  { type: 'divider' as const, key: 'd1' },
  { label: ui.isDark ? '☀️ 亮色模式' : '🌙 暗色模式', key: 'toggleDark' },
  { type: 'divider' as const, key: 'd2' },
  { label: '退出登录', key: 'logout' },
])

function handleUserSelect(key: string) {
  if (key === 'logout') auth.logout()
  if (key === 'app') router.push('/app/feed')
  if (key === 'admin') router.push('/admin/dashboard')
  if (key === 'settings') router.push('/app/settings')
  if (key === 'toggleDark') ui.toggleDark()
}

function goHome() {
  router.push({ path: '/' })
}

// ICP / 公安备案号（从 env 读取，为空则不显示）
const icp = import.meta.env.VITE_ICP_BEIAN ?? ''
const gaba = import.meta.env.VITE_GA_BEIAN ?? ''
const currentYear = new Date().getFullYear()

// ── 路由元信息 ──
const SITE_URL = 'https://oncolit.gonsun.com'
const routeMeta: Record<string, { title: string; description: string; ogType?: string }> = {
  '/': { title: 'OncoLit 肿瘤科研文献速递，每日更新', description: '全球肿瘤学进展，每日自动更新。基于 PubMed 的肿瘤文献管理平台，AI 摘要、精准推送、团队协作。' },
  '/pricing': { title: '定价 - OncoLit', description: '选择适合您的方案：免费版、专业版(¥35/月)、团队版(¥70/人/月)。7天免费试用。' },
  '/about': { title: '关于 - OncoLit', description: 'OncoLit 肿瘤科研文献速递，每日更新，致力于解决肿瘤领域科研人员的信息过载问题。' },
  '/help': { title: '帮助中心 - OncoLit', description: 'OncoLit 使用指南：关注领域设置、文献推送、导出引用、团队协作等常见问题。' },
  '/journals': { title: '肿瘤学期刊导航 - OncoLit', description: '浏览肿瘤学核心期刊列表，按分区筛选，查看各期刊最新文献。涵盖 NEJM、Lancet、JCO 等顶刊。' },
  '/cancers': { title: '癌种浏览 - OncoLit', description: '按肿瘤部位/类型浏览文献，覆盖肺癌、乳腺癌、结直肠癌、胃癌、肝癌等主要癌种的最新研究进展。' },
  '/drugs': { title: '肿瘤新药审批追踪 - OncoLit', description: '追踪 FDA/NMPA 肿瘤新药审批动态，查看获批适应症、临床试验信息和作用机制。' },
  '/guidelines': { title: '临床指南更新 - OncoLit', description: '肿瘤临床实践指南更新汇总，支持 NCCN、CSCO、ESMO 等权威指南版本对比。' },
  '/guidelines/compare': { title: '指南变更对比 - OncoLit', description: '对比不同版本肿瘤临床指南的变更内容，快速掌握诊疗标准更新要点。' },
}

// ── 工具：设置或更新 <head> 中的 meta ──
function setMeta(attr: string, value: string, attrType: 'name'|'property' = 'name') {
  const sel = attrType === 'property' ? `meta[property="${attr}"]` : `meta[name="${attr}"]`
  let el = document.querySelector(sel) as HTMLMetaElement | null
  if (!el) {
    el = document.createElement('meta')
    el.setAttribute(attrType, attr)
    document.head.appendChild(el)
  }
  el.setAttribute('content', value)
}

// ── Schema.org JSON-LD（只注入一次） ──
function injectJsonLd(id: string, data: Record<string, unknown>) {
  const existing = document.getElementById(id)
  if (existing) existing.remove()
  const script = document.createElement('script')
  script.id = id
  script.type = 'application/ld+json'
  script.textContent = JSON.stringify(data)
  document.head.appendChild(script)
}

onMounted(() => {
  // WebApplication — 主要结构化数据
  injectJsonLd('schema-org', {
    '@context': 'https://schema.org',
    '@type': 'WebApplication',
    name: 'OncoLit 肿瘤科研文献速递，每日更新',
    description: '全球肿瘤学文献自动追踪与 AI 分析平台，每日更新 PubMed 文献、AI 摘要、Meta 分析工具与团队协作功能。',
    url: SITE_URL,
    applicationCategory: 'MedicalApplication',
    operatingSystem: 'Web',
    offers: {
      '@type': 'AggregateOffer',
      offer: [
        { '@type': 'Offer', name: '免费版', price: '0', priceCurrency: 'CNY' },
        { '@type': 'Offer', name: '专业版', price: '35', priceCurrency: 'CNY' },
      ],
    },
  })
  // Organization
  injectJsonLd('schema-org-org', {
    '@context': 'https://schema.org',
    '@type': 'Organization',
    name: 'OncoLit 肿瘤科研文献速递，每日更新',
    url: SITE_URL,
    description: '全球肿瘤学文献自动追踪与 AI 分析平台',
  })
})

// ── 路由切换时更新 meta / OG / Twitter / canonical ──
watch(() => router.currentRoute.value.fullPath, (fullPath) => {
  const path = router.currentRoute.value.path
  const m = routeMeta[path] ?? routeMeta['/']
  if (!m) return

  // title + description
  if (document.title !== m.title) document.title = m.title
  setMeta('description', m.description)

  // Open Graph
  setMeta('og:title', m.title, 'property')
  setMeta('og:description', m.description, 'property')
  setMeta('og:type', m.ogType || 'website', 'property')
  setMeta('og:url', SITE_URL + fullPath, 'property')
  setMeta('og:site_name', 'OncoLit 肿瘤科研文献速递', 'property')

  // Twitter Card
  setMeta('twitter:card', 'summary_large_image')
  setMeta('twitter:title', m.title)
  setMeta('twitter:description', m.description)

  // Canonical URL
  let link = document.querySelector('link[rel="canonical"]') as HTMLLinkElement | null
  if (!link) {
    link = document.createElement('link')
    link.setAttribute('rel', 'canonical')
    document.head.appendChild(link)
  }
  link.setAttribute('href', SITE_URL + path)

  // BreadcrumbList JSON-LD
  const parts = path.split('/').filter(Boolean)
  const breadcrumbItems: { '@type': string; position: number; name: string; item: string }[] = [{ '@type': 'ListItem', position: 1, name: '首页', item: SITE_URL + '/' }]
  parts.forEach((p: string, i: number) => {
    const lookup = '/' + parts.slice(0, i + 1).join('/')
    breadcrumbItems.push({ '@type': 'ListItem', position: i + 2, name: routeMeta[lookup]?.title.split(' - ')[0] ?? p, item: SITE_URL + lookup })
  })
  injectJsonLd('schema-breadcrumb', {
    '@context': 'https://schema.org',
    '@type': 'BreadcrumbList',
    itemListElement: breadcrumbItems,
  })
}, { immediate: true })
</script>

<template>
  <NLayout class="public-layout">
    <NLayoutHeader bordered class="public-header">
      <div class="header-inner">
        <!-- Row 1: Logo icon + Nav + User -->
        <div class="header-row header-top">
          <span class="logo-wrapper" @click="goHome" title="OncoLit 肿瘤科研文献，每日更新">
            <img :src="ui.isDark ? logoDark : logoLight" class="logo-full" alt="OncoLit" loading="eager">
          </span>
          <div class="header-nav">
            <NButton text @click="router.push('/app/domains')">趋势</NButton>
            <!-- <NButton text @click="router.push('/pricing')">定价</NButton> -->
            <NButton text @click="router.push('/journals')">期刊</NButton>
            <NButton text @click="router.push('/cancers')">癌种</NButton>
            <NButton text @click="router.push('/drugs')">新药</NButton>
            <NButton text @click="router.push('/guidelines')">指南</NButton>
          </div>
          <div class="header-right">
            <NButton text style="font-size:14px;display:inline-flex;align-items:center;margin-right:8px" @click="ui.toggleDark()" :title="ui.isDark ? '亮色模式' : '暗色模式'">
              <template v-if="ui.isDark">
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/><line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/></svg>
              </template>
              <template v-else>
                <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="transform:translateY(1px)"><path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/></svg>
              </template>
            </NButton>
            <template v-if="auth.isAuthenticated">
              <NotificationBell />
              <NDropdown trigger="hover" :options="userOptions" @select="handleUserSelect">
                <NButton text style="padding:0 8px">
                  <NAvatar size="small" :style="avatarStyle">{{ (auth.user?.display_name||'U')[0] }}</NAvatar>
                </NButton>
              </NDropdown>
            </template>
            <template v-else>
              <span class="login-btn" @click="router.push('/auth/login')">登录</span>
            </template>
          </div>
        </div>
        <!-- Row 2: empty for now -->
      </div>
    </NLayoutHeader>

    <div v-if="showBar" class="global-loading-bar"></div>

    <NLayoutContent>
      <RouterView />
    </NLayoutContent>
    <footer class="pub-footer">
      <div class="footer-main">
        <span>© 2025-{{ currentYear }} OncoLit</span>
        <span class="sep">·</span>
        <router-link to="/help">帮助</router-link>
        <span class="sep">·</span>
        <router-link to="/about">关于</router-link>
      </div>
      <div class="footer-beian" v-if="icp || gaba">
        <template v-if="gaba">
          <svg class="police-badge" viewBox="0 0 20 20" width="14" height="14" fill="currentColor"><path d="M10 1.5L3 4.5v5.5c0 4.5 7 8.5 7 8.5s7-4 7-8.5V4.5l-7-3zM10 3l5 2.2v4.8c0 3.2-5 6.1-5 6.1s-5-2.9-5-6.1V5.2L10 3z"/><path d="M9 12l-3-3 1.5-1.5L9 9l4.5-4.5L15 6l-6 6z"/></svg>
          <span>{{ gaba }}</span>
        </template>
        <template v-if="icp">
          <span v-if="icp && gaba" class="sep">·</span>
          <a href="https://beian.miit.gov.cn/" target="_blank" rel="noopener">{{ icp }}</a>
        </template>
      </div>
    </footer>
  </NLayout>
</template>

<style scoped>
.pub-footer { text-align: center; padding: 16px 24px; font-size: 12px; color: var(--text-muted, #999); background: var(--bg-card, #fff); border-top: 1px solid var(--border-color, #eee); }
.pub-footer a { color: var(--text-muted, #999); text-decoration: none; }
.pub-footer a:hover { color: var(--kw-pill-color); }
html.dark .pub-footer a:hover { color: #6ab0e0; }
.footer-beian { margin-top: 4px; display: flex; align-items: center; justify-content: center; gap: 4px; }
.police-badge { vertical-align: middle; flex-shrink: 0; }
.sep { color: var(--border-color, #ddd); margin: 0 6px; }
.public-layout { min-height: 100vh; background: var(--bg-page, #f5f7fa); }
.public-header { padding: 0 24px; background: var(--bg-card, rgba(255,255,255,0.95)); backdrop-filter: blur(8px); }
.header-inner { max-width: 1200px; margin: 0 auto; display: flex; flex-direction: column; gap: 0; }
.header-top { display: flex; align-items: center; gap: 16px; padding: 14px 0 0; }
.logo-wrapper { display: flex; align-items: center; cursor: pointer; margin-top: -8px; }
.logo-full { height: 45px; }.header-nav { display: flex; align-items: center; gap: 4px; flex: 1; }
.header-nav :deep(.n-button) { font-size: 14px; color: var(--text-secondary); }
.header-nav :deep(.n-button:hover) { color: var(--kw-pill-color); }
html.dark .header-nav :deep(.n-button:hover) { color: #6ab0e0; }
.header-right { display: flex; align-items: center; }
.login-btn { cursor: pointer; color: var(--kw-pill-color); user-select: none; }
.login-btn:hover { opacity: .8; }
html.dark .login-btn { color: #6ab0e0; }

@media (max-width: 768px) {
  .public-layout { overflow-x: hidden; max-width: 100vw; }
  .public-header { padding: 0 8px; overflow: hidden; }
  .header-inner { max-width: 100%; }
  .header-top { gap: 8px; padding: 10px 0 0; flex-wrap: wrap; max-width: 100%; }
  .header-nav { gap: 2px; }
  .logo-full { height: 37px; max-width: 100%; }
  .pub-footer { padding: 12px 8px; }
}</style>
