import { createRouter, createWebHistory } from 'vue-router'
import { useAuth } from './composables/useAuth'
import { getPublicSettings } from './services/api'

// 缓存网站配置，避免重复获取
let cachedSiteTitle: string | null = null
let settingsLoaded = false

// 加载网站配置
const loadSiteTitle = async (): Promise<string> => {
  if (cachedSiteTitle !== null) {
    return cachedSiteTitle
  }
  
  if (!settingsLoaded) {
    settingsLoaded = true
    try {
      const settings = await getPublicSettings()
      cachedSiteTitle = settings.site_title || '年糕崽崽.Dev'
    } catch (error) {
      console.error('Failed to load site settings:', error)
      cachedSiteTitle = '年糕崽崽.Dev'
    }
  }
  
  return cachedSiteTitle || '年糕崽崽.Dev'
}

/** 供详情页等组件复用，避免重复请求 /settings */
export const getCachedSiteTitle = (): string => {
  return cachedSiteTitle || document.title.split(' | ')[0] || '年糕崽崽.Dev'
}

/** 清除网站标题缓存（配置更新后调用） */
export const invalidateSiteTitleCache = () => {
  cachedSiteTitle = null
  settingsLoaded = false
}

if (typeof window !== 'undefined') {
  window.addEventListener('public-settings-changed', invalidateSiteTitleCache)
}

// 设置页面标题
const setPageTitle = async (to: any) => {
  const siteTitle = await loadSiteTitle()
  const routeMeta = to.matched.find((record: any) => record.meta?.title !== undefined)
  
  // 如果是动态标题页面（如文章详情），先设置默认标题
  if (routeMeta?.meta?.dynamic) {
    // 动态标题会在组件中更新，这里先设置基础标题
    document.title = siteTitle
    return
  }
  
  // 获取页面标题
  const pageTitle = routeMeta?.meta?.title || ''
  
  // 设置完整标题
  if (pageTitle) {
    document.title = `${siteTitle} | ${pageTitle}`
  } else {
    // 首页只显示网站标题
    document.title = siteTitle
  }
}

const routes = [
  { path: '/', name: 'home', component: () => import('./pages/Home.vue'), meta: { title: '' } },
  { path: '/blog', name: 'blog', component: () => import('./pages/Blog.vue'), meta: { title: '思考' } },
  { path: '/blog/:id/ppt', name: 'blog-ppt-preview', component: () => import('./pages/BlogPptPreview.vue'), meta: { title: 'PPT 预览', dynamic: true, presentation: true } },
  { path: '/blog/:id', name: 'blog-detail', component: () => import('./pages/BlogDetail.vue'), meta: { title: '', dynamic: true } },
  { path: '/columns', name: 'columns', component: () => import('./pages/Columns.vue'), meta: { title: '专栏' } },
  { path: '/columns/:id', name: 'column-detail', component: () => import('./pages/ColumnDetail.vue'), meta: { title: '', dynamic: true } },
  { path: '/works', name: 'works', component: () => import('./pages/Works.vue'), meta: { title: '作品' } },
  { path: '/works/:id', name: 'work-detail', component: () => import('./pages/WorkDetail.vue'), meta: { title: '', dynamic: true } },
  { path: '/videos', name: 'videos', component: () => import('./pages/Videos.vue'), meta: { title: '视频' } },
  { path: '/videos/albums/:id', name: 'video-album-detail', component: () => import('./pages/VideoAlbumDetail.vue'), meta: { title: '', dynamic: true } },
  { path: '/videos/:id', name: 'video-detail', component: () => import('./pages/VideoDetail.vue'), meta: { title: '', dynamic: true } },
  { path: '/snippets', name: 'snippets', component: () => import('./pages/Snippets.vue'), meta: { title: '代码' } },
  { path: '/services', name: 'services', component: () => import('./pages/Services.vue'), meta: { title: '合作' } },
  { path: '/about', name: 'about', component: () => import('./pages/About.vue'), meta: { title: '关于' } },
  // 登录路由
  { path: '/login', name: 'login', component: () => import('./pages/Login.vue') },
  
  // 管理员路由 - 使用 AdminLayout 组件
  {
    path: '/admin',
    name: 'admin',
    component: () => import('./components/admin/AdminLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      // 仪表盘
      { path: '', redirect: '/admin/dashboard' },
      { path: 'dashboard', name: 'admin-dashboard', component: () => import('./pages/admin/dashboard/Overview.vue') },
      { path: 'analytics', name: 'admin-analytics', component: () => import('./pages/admin/dashboard/Analytics.vue') },
      
      // 用户管理
      { path: 'users', name: 'admin-users', component: () => import('./pages/admin/Users.vue') },
      { path: 'users/create', name: 'admin-users-create', component: () => import('./pages/admin/UserForm.vue') },
      { path: 'users/:id/edit', name: 'admin-users-edit', component: () => import('./pages/admin/UserForm.vue') },
      { path: 'profile', name: 'admin-profile', component: () => import('./pages/admin/Profile.vue'), meta: { title: '个人中心' } },
      
      // 角色管理
      { path: 'roles', name: 'admin-roles', component: () => import('./pages/admin/Roles.vue') },
      { path: 'roles/create', name: 'admin-roles-create', component: () => import('./pages/admin/RoleForm.vue') },
      { path: 'roles/:id/edit', name: 'admin-roles-edit', component: () => import('./pages/admin/RoleForm.vue') },
      
      // 文章管理
      { path: 'posts', name: 'admin-posts', component: () => import('./pages/admin/Posts.vue') },
      { path: 'posts/create', name: 'admin-posts-create', component: () => import('./pages/admin/PostForm.vue') },
      { path: 'posts/:id/edit', name: 'admin-posts-edit', component: () => import('./pages/admin/PostForm.vue') },
      
      // 分类管理
      { path: 'categories', name: 'admin-categories', component: () => import('./pages/admin/Categories.vue') },
      { path: 'categories/create', name: 'admin-categories-create', component: () => import('./pages/admin/CategoryForm.vue') },
      { path: 'categories/:id/edit', name: 'admin-categories-edit', component: () => import('./pages/admin/CategoryForm.vue') },

      // 专栏管理
      { path: 'columns', name: 'admin-columns', component: () => import('./pages/admin/Columns.vue') },
      { path: 'columns/create', name: 'admin-columns-create', component: () => import('./pages/admin/ColumnForm.vue') },
      { path: 'columns/:id/edit', name: 'admin-columns-edit', component: () => import('./pages/admin/ColumnForm.vue') },

      // 作品管理
      { path: 'works', name: 'admin-works', component: () => import('./pages/admin/Works.vue') },
      { path: 'works/create', name: 'admin-works-create', component: () => import('./pages/admin/WorkForm.vue') },
      { path: 'works/:id/edit', name: 'admin-works-edit', component: () => import('./pages/admin/WorkForm.vue') },

      // 视频管理
      { path: 'video-categories', name: 'admin-video-categories', component: () => import('./pages/admin/VideoCategories.vue') },
      { path: 'video-categories/create', name: 'admin-video-categories-create', component: () => import('./pages/admin/VideoCategoryForm.vue') },
      { path: 'video-categories/:id/edit', name: 'admin-video-categories-edit', component: () => import('./pages/admin/VideoCategoryForm.vue') },
      { path: 'video-albums', name: 'admin-video-albums', component: () => import('./pages/admin/VideoAlbums.vue') },
      { path: 'video-albums/create', name: 'admin-video-albums-create', component: () => import('./pages/admin/VideoAlbumForm.vue') },
      { path: 'video-albums/:id/edit', name: 'admin-video-albums-edit', component: () => import('./pages/admin/VideoAlbumForm.vue') },
      { path: 'videos', name: 'admin-videos', component: () => import('./pages/admin/Videos.vue') },
      { path: 'videos/create', name: 'admin-videos-create', component: () => import('./pages/admin/VideoForm.vue') },
      { path: 'videos/:id/edit', name: 'admin-videos-edit', component: () => import('./pages/admin/VideoForm.vue') },
      
      // 代码片段管理
      { path: 'snippets', name: 'admin-snippets', component: () => import('./pages/admin/Snippets.vue') },
      { path: 'snippets/create', name: 'admin-snippets-create', component: () => import('./pages/admin/SnippetForm.vue') },
      { path: 'snippets/:id/edit', name: 'admin-snippets-edit', component: () => import('./pages/admin/SnippetForm.vue') },
      { path: 'code-types', name: 'admin-code-types', component: () => import('./pages/admin/CodeTypes.vue') },
      { path: 'code-types/create', name: 'admin-code-types-create', component: () => import('./pages/admin/CodeTypeForm.vue') },
      { path: 'code-types/:id/edit', name: 'admin-code-types-edit', component: () => import('./pages/admin/CodeTypeForm.vue') },
      
      // 标签管理
      { path: 'tags', name: 'admin-tags', component: () => import('./pages/admin/Tags.vue') },
      { path: 'tags/create', name: 'admin-tags-create', component: () => import('./pages/admin/TagForm.vue') },
      { path: 'tags/:id/edit', name: 'admin-tags-edit', component: () => import('./pages/admin/TagForm.vue') },
      
      // 关于页面管理
      { path: 'about', name: 'admin-about', component: () => import('./pages/admin/About.vue') },

      // 合作咨询管理
      { path: 'inquiries', name: 'admin-inquiries', component: () => import('./pages/admin/Inquiries.vue') },

      // 客户评价管理
      { path: 'testimonials', name: 'admin-testimonials', component: () => import('./pages/admin/Testimonials.vue') },
      { path: 'testimonials/create', name: 'admin-testimonials-create', component: () => import('./pages/admin/TestimonialForm.vue') },
      { path: 'testimonials/:id/edit', name: 'admin-testimonials-edit', component: () => import('./pages/admin/TestimonialForm.vue') },

      // 合作伙伴管理
      { path: 'partners', name: 'admin-partners', component: () => import('./pages/admin/Partners.vue') },
      { path: 'partners/create', name: 'admin-partners-create', component: () => import('./pages/admin/PartnerForm.vue') },
      { path: 'partners/:id/edit', name: 'admin-partners-edit', component: () => import('./pages/admin/PartnerForm.vue') },

      // 邮箱后缀配置
      { path: 'email-suffixes', name: 'admin-email-suffixes', component: () => import('./pages/admin/EmailSuffixes.vue') },

      // 系统配置
      { path: 'settings', name: 'admin-settings', component: () => import('./pages/admin/Settings.vue') },

      { path: 'ppt-templates', name: 'admin-ppt-templates', component: () => import('./pages/admin/PptTemplates.vue') },
      { path: 'ppt-templates/create', name: 'admin-ppt-templates-create', component: () => import('./pages/admin/PptTemplateForm.vue') },
      { path: 'ppt-templates/:id/edit', name: 'admin-ppt-templates-edit', component: () => import('./pages/admin/PptTemplateForm.vue') },

      // 操作日志
      { path: 'logs', name: 'admin-logs', component: () => import('./pages/admin/Logs.vue') },
      
      // 访问日志
      { path: 'access-logs', name: 'admin-access-logs', component: () => import('./pages/admin/AccessLogs.vue') },
      
      // 附件管理
      { path: 'attachments', name: 'admin-attachments', component: () => import('./pages/admin/Attachments.vue') },
      
      // 附件分类管理
      { path: 'attachment-categories', name: 'admin-attachment-categories', component: () => import('./pages/admin/AttachmentCategories.vue') },
      { path: 'attachment-categories/create', name: 'admin-attachment-categories-create', component: () => import('./pages/admin/AttachmentCategoryForm.vue') },
      { path: 'attachment-categories/:id/edit', name: 'admin-attachment-categories-edit', component: () => import('./pages/admin/AttachmentCategoryForm.vue') },
      
      // OSS配置管理
      { path: 'oss-configs', name: 'admin-oss-configs', component: () => import('./pages/admin/OSSConfigs.vue') }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫，用于保护需要认证的路由和设置页面标题
router.beforeEach(async (to, _from, next) => {
  // 检查路由是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    const { isAuthenticated } = useAuth()
    if (!isAuthenticated()) {
      next({ name: 'login' })
      return
    }
  }
  
  // 设置页面标题（非管理页面）
  if (!to.path.startsWith('/admin') && to.path !== '/login') {
    await setPageTitle(to)
  }
  
  // 继续路由导航
  next()
})

export default router