import { createRouter, createWebHistory } from 'vue-router'
import { getSiteSettings } from '@/api/request/site'

let cachedSiteSettings = null

const routes = [
  { path: '/', meta: { title: '首页', page_code: 'home' }, name: 'Home', component: () => import('@/views/Home.vue') },
  { path: '/features', meta: { title: '产品能力', page_code: 'features' }, name: 'Features', component: () => import('@/views/Features.vue') },
  { path: '/solutions', meta: { title: '解决方案', page_code: 'solutions' }, name: 'Solutions', component: () => import('@/views/Solutions.vue') },
  { path: '/pricing', meta: { title: '价格方案', page_code: 'pricing' }, name: 'Pricing', component: () => import('@/views/Pricing.vue') },
  { path: '/about', meta: { title: '关于我们', page_code: 'about' }, name: 'About', component: () => import('@/views/About.vue') },
  { path: '/team', meta: { title: '团队介绍', page_code: 'team' }, name: 'Team', component: () => import('@/views/Team.vue') },
  { path: '/careers', meta: { title: '加入我们', page_code: 'careers' }, name: 'Careers', component: () => import('@/views/Careers.vue') },
  { path: '/admin/login', meta: { title: '后台登录', adminPublic: true }, name: 'AdminLogin', component: () => import('@/views/admin/AdminLogin.vue') },
  {
    path: '/admin',
    component: () => import('@/components/admin/AdminLayout.vue'),
    redirect: '/admin/dashboard',
    meta: { requiresAdmin: true },
    children: [
      { path: 'dashboard', meta: { title: '控制台', requiresAdmin: true }, component: () => import('@/views/admin/AdminDashboard.vue') },
      { path: 'site/leads', meta: { title: '咨询线索', requiresAdmin: true }, component: () => import('@/views/admin/AdminLeads.vue') },
      { path: 'site/sections', meta: { title: '页面模块', requiresAdmin: true }, component: () => import('@/views/admin/AdminSections.vue') },
      { path: 'site/media', meta: { title: '图片管理', requiresAdmin: true }, component: () => import('@/views/admin/AdminMedia.vue') },
      { path: 'site/jobs', meta: { title: '招聘管理', requiresAdmin: true }, component: () => import('@/views/admin/AdminJobs.vue') },
      { path: 'site/settings', meta: { title: '站点设置', requiresAdmin: true }, component: () => import('@/views/admin/AdminSiteSettings.vue') },
      { path: 'commerce/plans', meta: { title: '套餐管理', requiresAdmin: true }, component: () => import('@/views/admin/AdminPlans.vue') },
      { path: 'commerce/orders', meta: { title: '订单管理', requiresAdmin: true }, component: () => import('@/views/admin/AdminOrders.vue') },
      { path: 'system/roles', meta: { title: '角色权限', requiresAdmin: true }, component: () => import('@/views/admin/AdminRoles.vue') },
      { path: 'system/menus', meta: { title: '菜单管理', requiresAdmin: true }, component: () => import('@/views/admin/AdminMenus.vue') },
      { path: 'settings/profile', meta: { title: '个人设置', requiresAdmin: true }, component: () => import('@/views/admin/AdminProfile.vue') }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    return savedPosition || { top: 0 }
  }
})

const applyFavicon = (href) => {
  if (!href) return
  let link = document.querySelector('link[rel="icon"]')
  if (!link) {
    link = document.createElement('link')
    link.rel = 'icon'
    document.head.appendChild(link)
  }
  link.href = href
}

const applyMeta = (name, content) => {
  if (!content) return
  let meta = document.querySelector(`meta[name="${name}"]`)
  if (!meta) {
    meta = document.createElement('meta')
    meta.setAttribute('name', name)
    document.head.appendChild(meta)
  }
  meta.setAttribute('content', content)
}

const ensureSiteSettings = async () => {
  if (cachedSiteSettings) return cachedSiteSettings
  cachedSiteSettings = await getSiteSettings().catch(() => ({ site_title: '萧康云医官网' }))
  return cachedSiteSettings
}

router.beforeEach(async (to) => {
  if (to.meta.requiresAdmin && !localStorage.getItem('token')) {
    return { name: 'AdminLogin', query: { redirect: to.fullPath } }
  }
  const settings = await ensureSiteSettings()
  const siteTitle = settings.site_title || '萧康云医官网'
  document.title = to.meta.title ? `${to.meta.title} | ${siteTitle}` : siteTitle
  applyFavicon(settings.site_favicon)
  applyMeta('description', settings.default_seo?.description || '萧康云医为诊所提供全链路经营赋能。')
  applyMeta('keywords', settings.default_seo?.keywords || '诊所SaaS,云医,诊所管理')
  applyMeta('x-gso-summary', settings.default_gso?.summary || '诊所赋能 SaaS 平台')
})

export default router
