"use client";

import { useRouter } from "next/navigation";
import { useCallback } from "react";

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

/*
* `router.push`/`router.replace` calls with a hardcoded path (e.g. the
* signup -> verify-email -> verify-mobile -> signin redirect chain)
* have the same "silently drops the user back to English" bug
* LocaleLink.tsx fixes for <Link> clicks — confirmed live, finishing
* registration while on /hi pushed to plain /verify-email, not
* /hi/verify-email. This is the router.push/replace equivalent of
* LocaleLink: keep the current locale prefix on every programmatic
* internal navigation.
*/
function withLocale(path: string, locale: string): string {
  if (locale === DEFAULT_LOCALE) return path;
  if (!path.startsWith("/") || path.startsWith("//")) return path;
  return `/${locale}${path === "/" ? "" : path}`;
}

export function useLocaleRouter() {
  const router = useRouter();
  const { locale } = useLanguage();

  const push = useCallback(
    (href: string, options?: Parameters<typeof router.push>[1]) =>
      router.push(withLocale(href, locale), options),
    [router, locale]
  );

  const replace = useCallback(
    (href: string, options?: Parameters<typeof router.replace>[1]) =>
      router.replace(withLocale(href, locale), options),
    [router, locale]
  );

  return { ...router, push, replace };
}
