<script setup lang="ts">
import { h, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { NLayout, NLayoutHeader, NLayoutContent, NLayoutSider, NMenu, NButton, NAvatar, NDropdown } from 'naive-ui'
import { useAuthStore } from '../../stores/auth'
import { useUiStore } from '../../stores/ui'
import { useGlobalLoading } from '../../composables/useGlobalLoading'
import { RouterLink } from 'vue-router'

import NotificationBell from '../../components/common/NotificationBell.vue'

// 用 new URL 让 Vite 处理图片 hash 防缓存
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 logoMini = new URL('../../assets/logo-icon.png', import.meta.url).href

const router = useRouter()
const route = useRoute()
const auth = useAuthStore()
const ui = useUiStore()
const { showBar } = useGlobalLoading()

// SVG icon renderer (no NIcon wrapper - renders SVG directly in the icon slot)
function mkIcon(path: string) {
  return () => h('svg', { viewBox: '0 0 24 24', width: '20', height: '20', fill: 'currentColor' }, [h('path', { d: path })])
}

// Material Design SVG paths
const menuOptions = [
  { label: () => h(RouterLink, { to: '/app/feed' }, { default: () => '文献速览' }), key: 'feed', icon: mkIcon('M19 4h-1V2h-2v2H8V2H6v2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 16H5V8h14v10z') },
  { label: () => h(RouterLink, { to: '/app/profile' }, { default: () => '学术画像' }), key: 'profile', icon: mkIcon('M5 19h14v2H5zM6 17h3v-7H6v7zm5 0h3V5h-3v12zm5 0h3V9h-3v8z') },

  { label: () => h(RouterLink, { to: '/app/activity' }, { default: () => '浏览历史' }), key: 'activity', icon: mkIcon('M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-14h2v6h-2zm0 8h2v2h-2z') },
  { label: () => h(RouterLink, { to: '/app/domains' }, { default: () => '领域中心' }), key: 'domains', icon: mkIcon('M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm0 10c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z') },
  { label: () => h(RouterLink, { to: '/journals' }, { default: () => '期刊导航' }), key: 'journals', icon: mkIcon('M19 4h-1V2h-2v2H8V2H6v2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 16H5V8h14v10z') },
  { label: () => h(RouterLink, { to: '/app/search' }, { default: () => '搜索' }), key: 'search', icon: mkIcon('M15.5 14h-.79l-.28-.27A6.471 6.471 0 0016 9.5 6.5 6.5 0 109.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z') },
  { label: () => h(RouterLink, { to: '/app/library' }, { default: () => '我的收藏' }), key: 'library', icon: mkIcon('M20 6h-8l-2-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V8h16v10z') },
  { label: () => h(RouterLink, { to: '/app/journal-club' }, { default: () => 'Journal Club' }), key: 'journal-club', icon: mkIcon('M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z') },
  { label: () => h(RouterLink, { to: '/app/mdt' }, { default: () => 'MDT 协作' }), key: 'mdt', icon: mkIcon('M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z') },
  { label: () => h(RouterLink, { to: '/app/team' }, { default: () => '科室团队' }), key: 'team', icon: mkIcon('M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z') },
  { label: () => h(RouterLink, { to: '/app/notifications' }, { default: () => '通知' }), key: 'notifications', icon: mkIcon('M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z') },
  { label: () => h(RouterLink, { to: '/app/notes' }, { default: () => '我的笔记' }), key: 'notes', icon: mkIcon('M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z') },
  { label: () => h(RouterLink, { to: '/app/reviews' }, { default: () => '系统评价' }), key: 'reviews', icon: mkIcon('M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2 14H7v-2h7v2zm3-4H7v-2h10v2zm0-4H7V7h10v2z') },
  { label: () => h(RouterLink, { to: '/app/settings' }, { default: () => '设置' }), key: 'settings', icon: mkIcon('M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 00.12-.61l-1.92-3.32a.488.488 0 00-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.484.484 0 00-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.07.61-.07.94s.02.64.07.94l-2.03 1.58a.49.49 0 00-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6A3.6 3.6 0 1115.6 12 3.611 3.611 0 0112 15.6z') },
]

// 移动端 tab：主 tab + 更多下拉
const primaryTabKeys = ['feed', 'search', 'library', 'notes']
const moreTabKeys = ['profile', 'activity', 'domains', 'journals', 'journal-club', 'mdt', 'team', 'reviews', 'notifications', 'settings']
const tabLabels: Record<string, string> = {feed:'文献', search:'搜索', library:'收藏', profile:'画像', activity:'浏览历史', journals:'期刊', 'journal-club':'Journal Club', mdt:'MDT', team:'团队', reviews:'系统评价', notifications:'通知', notes:'笔记', settings:'设置', domains:'领域'}
const moreDropdownOptions = computed(() =>
  moreTabKeys.map(k => ({ label: tabLabels[k] || k, key: k }))
)
function handleMoreSelect(k: string) {
  router.push(`/app/${k}`)
}

const activeKey = computed(() => {
  const p = route.path.split('/app/')[1]?.split('/')[0]
  return p || 'feed'
})

const avatarStyle = computed(() => ({
  background: ui.isDark ? '#1a3a5c' : '#e6f4ff',
  color: 'var(--text-primary)',
}))
const userDropdownOptions = computed(() => [
  { label: '📊 学术画像', key: 'profile' },
  { label: '编辑关注领域', key: 'interests' },
  { label: ui.isDark ? '☀️ 亮色模式' : '🌙 暗色模式', key: 'toggleDark' },
  { type: 'divider' as const, key: 'd1' },
  { label: '退出登录', key: 'logout' },
])

function handleUserSelect(key: string) {
  if (key === 'logout') auth.logout()
  if (key === 'profile') router.push('/app/profile')
  if (key === 'interests') router.push('/app/settings/interests')
  if (key === 'stats') router.push('/app/profile')
  if (key === 'toggleDark') ui.toggleDark()
}
</script>

<template>
  <NLayout class="app-layout" has-sider>
    <NLayoutSider v-if="!ui.isMobile" bordered :collapsed="ui.sidebarCollapsed" collapse-mode="width" :width="200" :collapsed-width="72" :class="{ 'sider-collapsed': ui.sidebarCollapsed }">
      <div class="sider-logo" @click="router.push('/app/feed')" title="OncoLit 肿瘤科研文献，每日更新">
        <img v-if="!ui.sidebarCollapsed" :src="ui.isDark ? logoDark : logoLight" class="sider-logo-img-full" alt="OncoLit" loading="lazy">
        <img v-else :src="logoMini" class="sider-logo-img" alt="OncoLit" loading="lazy">
      </div>
      <NMenu :value="activeKey" :options="menuOptions" :collapsed="ui.sidebarCollapsed" :collapsed-width="72" :collapsed-icon-size="22" />
    </NLayoutSider>

    <NLayout>
      <NLayoutHeader bordered class="app-header">
        <div class="header-left">
          <NButton v-if="!ui.isMobile" text @click="ui.toggleSidebar()" style="font-size:18px;line-height:1;padding:4px;color:inherit">
            <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12h18M3 6h18M3 18h18"/></svg>
          </NButton>
        </div>
        <div class="header-right">
          <NButton text size="small" @click="router.push('/')" style="color:inherit" title="首页">
            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" style="transform:translateY(-1px);display:block"><path d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1"/></svg>
          </NButton>
          <NotificationBell />
          <NDropdown trigger="hover" :options="userDropdownOptions" @select="handleUserSelect">
            <NButton text style="padding:0 8px">
              <NAvatar size="small" :style="avatarStyle">{{ (auth.user?.display_name||'U')[0] }}</NAvatar>
            </NButton>
          </NDropdown>
        </div>
      </NLayoutHeader>

      <!-- 全局请求加载指示条 -->
      <div v-if="showBar" class="global-loading-bar"></div>

      <NLayoutContent class="app-content">
        <RouterView :key="route.fullPath" />
      </NLayoutContent>
    </NLayout>
  </NLayout>

  <!-- 移动端底部 -->
  <div v-if="ui.isMobile" class="mobile-tabs">
    <div v-for="k in primaryTabKeys" :key="k" class="tab-item" :class="{ active: activeKey === k }" @click="router.push(`/app/${k}`)">
      {{ tabLabels[k] }}
    </div>
    <NDropdown trigger="click" :options="moreDropdownOptions" @select="handleMoreSelect" placement="top-end">
      <div class="tab-item more-btn">更多 ▾</div>
    </NDropdown>
  </div>
</template>

<style scoped>
.app-layout { min-height: 100vh; }
.sider-logo { height: 64px; display: flex; align-items: center; justify-content: center; gap: 6px; cursor: pointer; border-bottom: 1px solid var(--border-color); }
.sider-logo-text { font-weight: 700; font-size: 22px; color: var(--text-primary); white-space: nowrap; }
.sider-logo-img-full { height: 40px; max-width: 180px; object-fit: contain; }
.sider-logo-img { height: 36px; }
.sider-collapsed .sider-logo-img { height: 48px; }
.sider-collapsed .sider-logo { gap: 0; }
.app-layout :deep(.n-menu-item) { font-size: 14px; }
.app-layout :deep(.n-menu-item-content) { font-size: 14px; }
.app-layout :deep(.n-menu-item-content--collapsed) { justify-content: center; }
.app-layout :deep(.n-menu-item-content--collapsed .n-menu-item-content__icon) { margin: 0 auto !important; color: inherit !important; }
/** 选中菜单项文字加亮 */
.app-layout :deep(.n-menu-item-content--selected) { --n-item-text-color: #1a5276 !important; font-weight: 600; }
html.dark .app-layout :deep(.n-menu-item-content--selected) { --n-item-text-color: #6ab0e0 !important; font-weight: 600; }
.sider-collapsed :deep(.n-layout-sider-scroll-container) {
  display: flex !important;
  flex-direction: column !important;
  justify-content: flex-start !important;
  align-items: center !important;
}
.sider-collapsed .sider-logo { flex-shrink: 0; }
.app-header { display: flex; align-items: center; justify-content: space-between; padding: 0 16px; height: 56px; color: var(--text-secondary); }
.header-left, .header-right { display: flex; align-items: center; gap: 8px; }
.app-content { background: var(--bg-page); min-height: calc(100vh - 56px); }
.mobile-tabs { position: fixed; bottom: 0; left: 0; right: 0; height: 56px; background: var(--bg-card); border-top: 1px solid var(--border-color); display: flex; align-items: center; z-index: 100; overflow-x: auto; -webkit-overflow-scrolling: touch; }
.mobile-tabs::-webkit-scrollbar { display: none; }
.tab-item { font-size: 11px; text-align: center; padding: 4px 12px; color: var(--text-muted); cursor: pointer; white-space: nowrap; flex-shrink: 0; }
.tab-item.active { color: #1a5276; font-weight: 600; }

.global-loading-bar {
  position: sticky;
  top: 0;
  z-index: 999;
  height: 2px;
  background: linear-gradient(90deg, transparent 0%, #409eff 50%, transparent 100%);
  background-size: 200% 100%;
  animation: bar-slide 1.2s ease-in-out infinite;
}
@keyframes bar-slide {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}


</style>
