import { createRouter, createWebHistory } from 'vue-router'
import AuthenticatedLayout from '@/components/layouts/AuthenticatedLayout.vue'
import UnauthenticatedLayout from '@/components/layouts/UnauthenticatedLayout.vue'
import HomeView from '@/views/HomeView.vue'
import LandingView from '@/views/LandingView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: UnauthenticatedLayout,
      children: [
        {
          path: '',
          component: LandingView,
          name: 'landing'
        }
      ]
    },
    {
      path: '/home',
      component: AuthenticatedLayout,
      children: [
        {
          path: '',
          name: 'home',
          component: HomeView,
          meta: {
            requiresAuth: true
          }
        }
      ]
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      // component: () => import('../views/AboutView.vue')
    },
    {
      path: '/game',
      component: AuthenticatedLayout,
      children: [
        {
          path: '',
          name: 'game',
          component: () => import('@/views/GameView.vue'),
          meta: {
            requiresAuth: true
          }
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  const isLoggedIn = !!sessionStorage.getItem('token')
  if (to.matched.some((record) => record.meta.requiresAuth) && !isLoggedIn) {
    next({ name: 'landing' })
  } else {
    next()
  }
})

export default router
