import { createRouter, createWebHistory, createWebHashHistory } from "vue-router";
import AuthContainer from '@/views/AuthContainer.vue';
import MainContainer from '@/views/MainContainer.vue';
import Login from '@/views/Login/index.vue';
import Files from '@/views/Files/index.vue';
import Map from '@/views/Discover/Map/index.vue';
import Conformance from '@/views/Discover/Conformance/index.vue';
import MemberArea from '@/views/MemberArea/index.vue';
import NotFound404 from '@/views/NotFound404.vue';

const routes = [
  {
    path: '/', // 預設進入路由
    redirect: '/files'  //重定向
   },
  {
    path: '/',
    name: "AuthContainer",
    component: AuthContainer,
    children: [
      {
        path: "/login",
        name: "Login",
        component: Login,
      },
    ]
  },
  {
    path: "/",
    name: "MainContainer",
    component: MainContainer,
    children: [
      {
        path: "/member-area",
        name: "MemberArea",
        component: MemberArea,
      },
      {
        path: "/files",
        name: "Files",
        component: Files,
      },
      {
        path: "/discover",
        name: "Discover",
        children: [
          {
            path: "/discover/map/:type/:fileId",
            name: "Map",
            component: Map,
          },
          {
            path: "/discover/conformance/:type/:fileId",
            name: "Conformance",
            component: Conformance,
          },
        ]
      },
    ]
  },
  {
    path: "/:pathMatch(.*)*",
    name: "NotFound404",
    component: NotFound404,
  },
];



const base_url = import.meta.env.BASE_URL;
const router = createRouter({
  history: createWebHistory(base_url), //(/)
  // history: createWebHashHistory(base_url), // (/#)

  routes
});

// 全域性路由守衛
router.beforeEach((to, from) => {
  // to: Route: 即將要進入的目標 路由物件
  // from: Route: 當前導航正要離開的路由

  const nextRoute = ['MemberArea', 'Files'];
  let isCookie = document.cookie.split(';').some(c => c.trim().startsWith('luciaToken=')); // 是否登入

  // 未登入狀態；當路由到nextRoute指定頁時，跳轉至login
  if (nextRoute.indexOf(to.name) >= 0) {
   if (!isCookie) router.push({ name: 'Login' });
  }
  // 已登入狀態；當路由到login時，跳轉至home
  if (to.name === 'Login') {
   if (isCookie) router.push({ name: 'Files' });
  }
 });

export default router;
