import { createRouter, createWebHistory, RouterView } from "vue-router";
import { h } from "vue";
import i18n, { setLanguage } from "@/i18n";

const supportedLangs = ['en', 'ru', 'me', 'ua'];

const routes = [
  {
    path: "/:lang(en|ru|me|ua)?",
    component: { render: () => h(RouterView) },
    children: [
      { path: "",          name: "home",      component: () => import("@/pages/Index.vue"),     meta: { title: "Home" } },
      { path: "auth",      name: "auth",      component: () => import("@/pages/Auth.vue"),      meta: { title: "Authentication" } },
      { path: "orders",    name: "orders",    component: () => import("@/pages/Orders.vue"),    meta: { title: "My Orders" } },
      { path: "portfolio", name: "portfolio", component: () => import("@/pages/Portfolio.vue"), meta: { title: "Portfolio" } },
      { path: "admin",     name: "admin",     component: () => import("@/pages/Admin.vue"),     meta: { title: "Admin Panel" } },
      { path: "privacy",   name: "privacy",   component: () => import("@/pages/Privacy.vue"),   meta: { title: "Privacy Policy" } },
      { path: "about",     name: "about",     component: () => import("@/pages/About.vue"),     meta: { title: "About Us" } },
      { path: "careers",   name: "careers",   component: () => import("@/pages/Careers.vue"),   meta: { title: "Careers" } },
      { path: "blog",      name: "blog",      component: () => import("@/pages/Blog.vue"),      meta: { title: "Blog" } },
      { path: "blog/:id",  name: "blog-post", component: () => import("@/pages/BlogPost.vue"),  meta: { title: "Blog Post" } },
      { path: "contact",   name: "contact",   component: () => import("@/pages/Contact.vue"),   meta: { title: "Contact" } },
      { path: "help",      name: "help",      component: () => import("@/pages/HelpCenter.vue"), meta: { title: "Help Center" } },
      { path: "guidelines", name: "guidelines", component: () => import("@/pages/Guidelines.vue"), meta: { title: "Guidelines" } },
      { path: "nuances",    name: "nuances",    component: () => import("@/pages/Nuances.vue"),    meta: { title: "Nuances" } },
      { path: "scanning",   name: "scanning",   component: () => import("@/pages/Scanning.vue"),   meta: { title: "3D Scanning" } },
      { path: "terms",     name: "terms",     component: () => import("@/pages/Terms.vue"),      meta: { title: "Terms of Service" } },
    ]
  },
  { path: "/:pathMatch(.*)*", component: () => import("@/pages/NotFound.vue"), meta: { title: "Not Found" } },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to) {
    if (to.hash) return { el: to.hash, behavior: "smooth" };
    return { top: 0 };
  },
});

router.beforeEach(async (to) => {
  const { useAuthStore } = await import("@/stores/auth");
  const authStore = useAuthStore();
  
  let lang = to.params.lang as string;
  const savedLang = localStorage.getItem('locale') || 'en';
  
  if (!lang) {
    const segments = to.path.split('/').filter(Boolean);
    const firstSegment = segments[0];
    
    if (firstSegment && firstSegment.length === 2 && !supportedLangs.includes(firstSegment)) {
      const remainingPath = segments.slice(1).join('/');
      return { path: `/${savedLang}/${remainingPath}`, query: to.query, hash: to.hash };
    }
    
    if ((window as any).__PRERENDER_INJECTED) {
      return;
    }
    
    return { path: `/${savedLang}${to.fullPath}` };
  }

  if (supportedLangs.includes(lang)) {
    if (i18n.global.locale.value !== lang) {
      await setLanguage(lang);
    }
  } else {
    return { path: `/${savedLang}/`, query: to.query };
  }

  const isPrerendering = (window as any).__PRERENDER_INJECTED !== undefined;
  if (!isPrerendering && !authStore.user && localStorage.getItem("token")) {
    await authStore.init();
  }

  const pathWithoutLang = to.path.replace(`/${lang}`, '') || '/';

  if (pathWithoutLang === "/admin" && authStore.user?.role !== "admin") {
    return { name: "auth", params: { lang } };
  }
  
  if (pathWithoutLang === "/orders" && !authStore.user) {
    return { name: "auth", params: { lang } };
  }
});

export default router;
