<template>
    <DefaultTheme.Layout />
</template>

<script setup lang="ts">
import { watch, onMounted, nextTick } from "vue";
import { useData, inBrowser } from "vitepress";
import DefaultTheme from "vitepress/theme";

const data = useData();

const performRedirect = (targetLocale: string, currentPath: string) => {
    const pathWithoutLocale = currentPath.replace(/^\/(?:ja|en)(\/|$)/, "/");

    const newPath =
        pathWithoutLocale === "/"
            ? `/${targetLocale}`
            : `/${targetLocale}${pathWithoutLocale}`;

    if (newPath !== currentPath) {
        console.log(`Redirecting from ${currentPath} to ${newPath}`);
        window.location.replace(newPath);
        return true;
    }
    return false;
};

onMounted(() => {
    if (!inBrowser) return;

    const path = window.location.pathname;
    const savedLocale = localStorage.getItem("locale") || "ja";

    const pathLocaleMatch = path.match(/^\/(?:ja|en)(?:\/|$)/);
    const currentPathLocale = pathLocaleMatch ? path.substring(1, 3) : null;

    if (currentPathLocale) {
        localStorage.setItem("locale", currentPathLocale);
    }

    if (path === "/" || path === "" || !currentPathLocale) {
        performRedirect(savedLocale, path);
    }
});

watch(
    data.lang,
    async (newLang, oldLang) => {
        if (!inBrowser || !newLang || newLang === oldLang) return;

        await nextTick();

        const currentPath = window.location.pathname;
        const savedLocale = localStorage.getItem("locale");

        if (newLang !== savedLocale) {
            localStorage.setItem("locale", newLang);
        }

        const pathLocaleMatch = currentPath.match(/^\/(?:ja|en)(?:\/|$)/);
        const currentPathLocale = pathLocaleMatch
            ? currentPath.substring(1, 3)
            : null;

        if (currentPathLocale !== newLang) {
            setTimeout(() => {
                performRedirect(newLang, currentPath);
            }, 100);
        }
    },
    { flush: "post" },
);
</script>
