import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import { getRuntime } from '../config/runtime'
import { getToken } from '../utils/auth'

const isEmbeddedShell = import.meta.env.MODE === 'ios' || getRuntime().embedded

const router = createRouter({
  // file/custom scheme 下 pathname 常为 /index.html，必须固定 hash base 为 /
  history: isEmbeddedShell ? createWebHashHistory('/') : createWebHistory(),
  routes: [
    { path: '/login', name: 'Login', component: () => import('../pages/Login.vue') },
    { path: '/register', name: 'Register', component: () => import('../pages/Register.vue') },
    {
      path: '/',
      component: () => import('../layouts/MainLayout.vue'),
      meta: { requiresAuth: true },
      children: [
        { path: '', name: 'Dashboard', component: () => import('../pages/Dashboard.vue') },
        { path: 'translate', name: 'Translate', component: () => import('../pages/Translate.vue') },
        { path: 'words', name: 'WordLibrary', component: () => import('../pages/WordLibrary.vue') },
        { path: 'quiz', name: 'DailyQuiz', component: () => import('../pages/DailyQuiz.vue') },
        { path: 'spell', name: 'SpellQuiz', component: () => import('../pages/SpellQuiz.vue') },
        {
          path: 'graph-practice',
          name: 'GraphPractice',
          component: () => import('../pages/GraphPractice.vue'),
        },
        {
          path: 'coach',
          name: 'MemoryCoach',
          component: () => import('../pages/MemoryCoach.vue'),
        },
        { path: 'settings', name: 'Settings', component: () => import('../pages/Settings.vue') },
        {
          path: 'book-settings',
          name: 'BookSettings',
          component: () => import('../pages/BookSettings.vue'),
        },
        {
          path: 'accumulation-settings',
          name: 'AccumulationSettings',
          component: () => import('../pages/AccumulationSettings.vue'),
        },
        {
          path: 'settings/username',
          name: 'SettingsUsername',
          component: () => import('../pages/UsernameSettings.vue'),
        },
        {
          path: 'settings/password',
          name: 'SettingsPassword',
          component: () => import('../pages/PasswordSettings.vue'),
        },
      ],
    },
  ],
})

router.beforeEach((to, _from, next) => {
  const token = getToken()
  if (to.meta.requiresAuth && !token) {
    next('/login')
  } else if ((to.path === '/login' || to.path === '/register') && token) {
    next('/')
  } else {
    next()
  }
})

export default router
