import { commonMask } from "@/utils";
import { createNavigation } from "next-intl/navigation";
import { defineRouting } from "next-intl/routing";
const modulesFiles = require.context("../../messages", true, /\.json$/);
export const locales = modulesFiles.keys().map((modulePath: string) => {
    return modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");
});
// 路由
const {
    Link: BaseLink,
    redirect,
    usePathname,
    useRouter: useBaseRouter,
} = createNavigation({
    locales,
});

export const defaultLocale = locales.at(0) as string;

export const routing = defineRouting({
    locales: locales,
    defaultLocale: defaultLocale,
    localeCookie: { name: "language" },
});

const useRouter = () => {
    const router = useBaseRouter();
    const cfg: any = { ...router };
    Object.keys(router).forEach((key: any) => {
        cfg[key] = (...args: any) => {
            if (key === "push") {
                commonMask.show();
            }
            (router as any)[key].apply(null, args);
        };
    });
    return cfg;
};

const Link = ({ children, ...props }: any) => {
    const { onClick } = props;
    const newProps = {
        ...props,
    };
    if (typeof window !== "undefined") {
        newProps.onClick = onClick
            ? onClick
            : () => {
                  commonMask.show();
              };
    }
    return <BaseLink {...newProps}>{children}</BaseLink>;
};

export { Link, redirect, usePathname, useRouter };
