"use client";

import { useRouter, useSearchParams } from "next/navigation";
import { useLanguage } from "../context/LanguageContext";
import { getLocalizedUrl } from "../utils/urlHelper";

/**
 * Custom hook that wraps Next.js useRouter to automatically
 * include the current language and franchiseeId parameters in all navigation calls.
 */
export function useLocalizedNavigation() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { currentLanguage } = useLanguage();
  const currentFranchiseeId = searchParams.get("franchiseeId");

  const push = (href: string, options?: any, langOverride?: string) => {
    const localizedHref = getLocalizedUrl(href, langOverride || currentLanguage, currentFranchiseeId);
    router.push(localizedHref, options);
  };

  const replace = (href: string, options?: any, langOverride?: string) => {
    const localizedHref = getLocalizedUrl(href, langOverride || currentLanguage, currentFranchiseeId);
    router.replace(localizedHref, options);
  };

  const prefetch = (href: string, options?: any, langOverride?: string) => {
    const localizedHref = getLocalizedUrl(href, langOverride || currentLanguage, currentFranchiseeId);
    router.prefetch(localizedHref, options);
  };

  /**
   * A full page load instead of a client-side push - for changing language.
   *
   * The root layout (header, footer, nav menus, <html lang/dir>) is fetched on
   * the server and kept as-is across client-side navigations, so a language
   * change made with push() swapped only the page body and left the header and
   * footer in the old language until the visitor refreshed.
   */
  const assign = (href: string, langOverride?: string) => {
    window.location.assign(getLocalizedUrl(href, langOverride || currentLanguage, currentFranchiseeId));
  };

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