"use client";

import { useTranslation } from "@/hooks/useTranslation";
import { locales } from "@/utils/routeTranslations";
import NextLink from "next/link";
import { ComponentProps } from "react";

function isAlreadyLocalized(path: string): boolean {
    return locales.some((locale) => path === `/${locale}` || path.startsWith(`/${locale}/`));
}

function localizeHref(href: string, language: string): string {
    if (
        !href.startsWith("/") ||
        href.startsWith("//") ||
        isAlreadyLocalized(href)
    ) {
        return href;
    }

    return `/${language}${href}`;
}

type LocaleLinkProps = Omit<ComponentProps<typeof NextLink>, "href"> & {
    href: string;
};

export default function LocaleLink({ href, ...props }: LocaleLinkProps) {
    const { language } = useTranslation();

    return <NextLink href={localizeHref(href, language)} {...props} />;
}
