import { createRouter, createWebHistory } from 'vue-router'
import config from '@/utils/config'
import { store } from '@/utils/store'
import bridge from '@/utils/bridge'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'Welcome',
      component: () => import('@/views/Welcome.vue')
    },
    {
      path: '/upload',
      name: 'Upload',
      component: () => import('@/views/Upload.vue')
    },
    {
      path: '/characters',
      name: 'Characters',
      component: () => import('@/views/Characters.vue')
    },
    {
      path: '/style',
      name: 'Style',
      component: () => import('@/views/StyleSelect.vue')
    },
    {
      path: '/story',
      name: 'Story',
      component: () => import('@/views/StoryInput.vue')
    },
    {
      path: '/creating',
      name: 'Creating',
      component: () => import('@/views/Creating.vue')
    },
    {
      path: '/preview/:workId?',
      name: 'Preview',
      component: () => import('@/views/Preview.vue')
    },
    {
      path: '/edit-info/:workId',
      name: 'EditInfo',
      component: () => import('@/views/EditInfo.vue')
    },
    {
      path: '/save-success/:workId',
      name: 'SaveSuccess',
      component: () => import('@/views/SaveSuccess.vue')
    },
    {
      path: '/dubbing/:workId',
      name: 'Dubbing',
      component: () => import('@/views/Dubbing.vue')
    },
    {
      path: '/read/:workId',
      name: 'Read',
      component: () => import('@/views/BookReader.vue'),
      meta: { noAuth: true }
    }
  ]
})

// Auth guard: 全局 token 初始化 + 双模式认证检查
router.beforeEach((to, from, next) => {
  // 持久化 from 参数（所有页面通用，含 noAuth 页面）
  const sp = new URLSearchParams(window.location.search)
  const urlFrom = sp.get('from')
  if (urlFrom) sessionStorage.setItem('le_from', urlFrom)

  if (to.meta.noAuth) {
    next()
    return
  }

  // ─── 全局 token 初始化：从 URL query 读取 ───
  // 支持 iframe src 直接带 token 加载任意页面
  // 如: /edit-info/190xxx?token=xxx&orgId=xxx&phone=xxx&embed=1
  const searchParams = new URLSearchParams(window.location.search)
  const urlToken = searchParams.get('token')
  const urlOrgId = searchParams.get('orgId')
  const urlPhone = searchParams.get('phone')

  if (urlToken && urlOrgId && !store.sessionToken) {
    store.setSession(urlOrgId, urlToken)
    if (urlPhone) store.setPhone(urlPhone)
    window.history.replaceState({}, '', window.location.pathname + window.location.hash)
  }

  // hash 路由参数兼容（hash模式下参数在 #/?token=xxx 中）
  if (!store.sessionToken && !store.appSecret) {
    const hashQuery = window.location.hash.split('?')[1] || ''
    if (hashQuery) {
      const hp = new URLSearchParams(hashQuery)
      const hToken = hp.get('token')
      const hOrgId = hp.get('orgId')
      const hPhone = hp.get('phone')
      if (hToken && hOrgId) {
        store.setSession(hOrgId, hToken)
        if (hPhone) store.setPhone(hPhone)
        window.history.replaceState({}, '', window.location.pathname + '#' + to.path)
      }
    }
  }

  // ─── 认证检查 ───
  if (to.name === 'Welcome') {
    next()
    return
  }

  // 有 sessionToken 或 appSecret 任一即可通过
  if (store.sessionToken || store.appSecret) {
    next()
  } else {
    next({ name: 'Welcome' })
  }
})

export default router
