"use client";

import Link from "next/link";
import { useSearchParams } from "next/navigation";
import type { ComponentProps } from "react";

type LocalizedLinkProps = ComponentProps<typeof Link>;

function withLanguage(href: LocalizedLinkProps["href"], lang: string | null) {
  if (typeof href !== "string" || (lang !== "dr" && lang !== "ps")) return href;
  if (!href.startsWith("/") || href.startsWith("//")) return href;

  const hashIndex = href.indexOf("#");
  const hrefWithoutHash = hashIndex >= 0 ? href.slice(0, hashIndex) : href;
  const hash = hashIndex >= 0 ? href.slice(hashIndex) : "";
  const queryIndex = hrefWithoutHash.indexOf("?");
  const path = queryIndex >= 0 ? hrefWithoutHash.slice(0, queryIndex) : hrefWithoutHash;
  const query = queryIndex >= 0 ? hrefWithoutHash.slice(queryIndex + 1) : "";
  const params = new URLSearchParams(query);

  if (!params.has("lang")) params.set("lang", lang);

  const nextQuery = params.toString();
  return `${path}${nextQuery ? `?${nextQuery}` : ""}${hash}`;
}

export function LocalizedLink({ href, ...props }: LocalizedLinkProps) {
  const searchParams = useSearchParams();

  return <Link href={withLanguage(href, searchParams.get("lang"))} {...props} />;
}
