import { createRouter, createWebHistory } from 'vue-router'
import Appointment from '@/pages/appointment.vue'
import Checkin from '@/pages/checkin.vue'
import CheckinDetail from '@/pages/checkinDetail.vue'
import Course from '@/pages/course.vue'
import Index from '@/pages/index.vue'
import Introduction from '@/pages/introduction.vue'
import Login from '@/pages/login.vue'
import SelfAssessment from '@/pages/self-assessment.vue'
import { useAppStore } from '@/stores/app'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  scrollBehavior () {
    return { left: 0, top: 0 }
  },
  routes: [
    {
      path: '/',
      name: 'home',
      component: Index,
    },
    {
      path: '/introduction',
      name: 'introduction',
      component: Introduction,
      meta: { title: '計畫簡介｜運動玩轉健康力' },
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
    },
    {
      path: '/self-assessment',
      name: 'self-assessment',
      component: SelfAssessment,
    },
    {
      path: '/appointment',
      name: 'appointment',
      component: Appointment,
      meta: { requiresAuth: true },
    },
    {
      path: '/course',
      name: 'course',
      component: Course,
      meta: { requiresAuth: true, title: '課程建議｜運動玩轉健康力' },
    },
    {
      path: '/checkin',
      name: 'checkin',
      component: Checkin,
      meta: { requiresAuth: true },
    },
    {
      path: '/checkin/:code',
      name: 'checkin-detail',
      component: CheckinDetail,
      meta: { requiresAuth: true },
    },
  ],
})

// 簡單的導航守衛：只有標記需要登入的頁面會導向登入頁
router.beforeEach(to => {
  const store = useAppStore()

  if (to.meta.requiresAuth && !store.isLoggedIn) {
    return { name: 'login' }
  }
})

router.afterEach(to => {
  document.title = typeof to.meta.title === 'string' ? to.meta.title : '運動玩轉健康力'
})

export default router
