import { createRouter, createWebHistory } from "vue-router";
import { useGlobalStore } from "../store/GlobalStore";
import pinia from "@/store";
import NotFound from "@/core/components/NotFound.vue";
import DefaultLayout from "@/core/layouts/default/Default.vue";

import importRoutes from "./routes";

const globalStore = useGlobalStore(pinia);

const router = createRouter({
  history: createWebHistory(),
  routes: [
    ...importRoutes(),
    // Fallback route
    {
      path: "/:catchAll(.*)",
      component: DefaultLayout,
      children: [
        {
          path: "",
          name: "404",
          component: NotFound,
          meta: { title: "صفحة غير موجودة" },
        },
      ],
    },
  ],
  scrollBehavior(to) {
    if (to.hash) {
      return {
        el: to.hash,
        behavior: "smooth",
      };
    }
  },
});

const originalPush = router.push;
router.push = function push(location) {
  return originalPush.call(this, location).catch((err) => {
    if (err.name !== "NavigationDuplicated") throw err;
  });
};

const DEFAULT_TITLE = "MNS";
router.afterEach((to) => {
  document.title = to.meta.title || DEFAULT_TITLE;
});

router.afterEach(() => {
  window.scrollTo(0, 0);
  globalStore.isDrawerVisible = false;
});

export default router;
