"use client";

import Link from "next/link";
import type { ComponentProps } from "react";

import { useLanguage } from "@/app/context/LanguageContext";
import { DEFAULT_LOCALE } from "@/app/i18n/locales";

type Props = ComponentProps<typeof Link>;

/*
* A drop-in replacement for next/link's <Link> that keeps the current
* /hi or /kn URL prefix on every internal navigation. Plain <Link>
* always points at the unprefixed (English) path, so clicking any nav
* item while browsing in Hindi/Kannada silently dropped the user back
* to English — confirmed live (hovering a header link while on
* /kn/panchang/tomorrow-panchang showed it pointed at plain
* /horoscope/daily-horoscope, no /kn).
*/
export default function LocaleLink({ href, ...rest }: Props) {
  const { locale } = useLanguage();

  const localizedHref = ((): typeof href => {
    if (locale === DEFAULT_LOCALE) return href;

    if (typeof href === "string") {
      if (!href.startsWith("/") || href.startsWith("//")) return href;
      return `/${locale}${href === "/" ? "" : href}`;
    }

    if (href.pathname?.startsWith("/")) {
      return { ...href, pathname: `/${locale}${href.pathname === "/" ? "" : href.pathname}` };
    }

    return href;
  })();

  return <Link href={localizedHref} {...rest} />;
}
