"use client";

import Link, { LinkProps } from "next/link";
import { useLanguage } from "@/src/lib/context/LanguageContext";
import { getLocalizedUrl } from "@/src/lib/utils/urlHelper";
import { useSearchParams } from "next/navigation";
import { ReactNode } from "react";

// Next.js LinkProps covers Next specific props, but we need standard anchor attributes like target/rel too
interface LanguageAwareLinkProps extends Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, keyof LinkProps>, LinkProps {
  children: ReactNode;
  className?: string;
  onClick?: () => void;
}

export default function LanguageAwareLink({
  href,
  children,
  ...props
}: LanguageAwareLinkProps) {
  const { currentLanguage } = useLanguage();
  const searchParams = useSearchParams();
  const franchiseeId = searchParams.get("franchiseeId");

  // Pull out Next-only props so they never leak onto a plain <a> below.
  const {
    prefetch: _prefetch,
    replace: _replace,
    scroll: _scroll,
    shallow: _shallow,
    passHref: _passHref,
    locale: _locale,
    legacyBehavior: _legacyBehavior,
    onClick,
    ...anchorProps
  } = props;

  let finalHref = href;

  // Handle string href
  if (typeof href === "string") {
    finalHref = getLocalizedUrl(href, currentLanguage, franchiseeId);
  } 
  // Handle object href (LinkProps style)
  else if (typeof href === "object" && href.pathname) {
    const localizedUrlStr = getLocalizedUrl(href.pathname, currentLanguage, franchiseeId);
    const url = new URL(localizedUrlStr, "https://dummy.com");
    
    // Merge new params into existing query object
    const query = typeof href.query === "object" ? { ...href.query } : {};
    url.searchParams.forEach((value, key) => {
      query[key] = value;
    });

    finalHref = {
      ...href,
      query,
    };
  }

  // In-page anchors (e.g. "#program-Form") must NOT go through the router.
  //
  // next/link treats a hash link as a client-side navigation. The first click
  // adds the hash to the URL and resolves from cache, so it scrolls instantly.
  // A second click targets the URL the browser is *already* on, which the App
  // Router handles by re-fetching the route — and because the root layout is
  // `force-dynamic` and refetches header/programs/workshops on every request,
  // that round-trip costs ~1s before the scroll even begins.
  //
  // A plain <a> does a native hash jump instead: no RSC request, identical
  // timing on every click.
  if (typeof finalHref === "string" && finalHref.startsWith("#")) {
    const targetId = finalHref.slice(1);

    // We animate the jump ourselves rather than leaning on the stylesheet's
    // `html { scroll-behavior: smooth }`. That rule is fragile — anything that
    // sets an inline `scrollBehavior` on <html> silently wins over it and the
    // CTA starts teleporting. An explicit scrollIntoView always animates.
    const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
      onClick?.();

      // Leave modified clicks and unknown targets to the browser.
      if (e.defaultPrevented || e.button !== 0) return;
      if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;

      const target = document.getElementById(targetId);
      if (!target) return;

      e.preventDefault();
      target.scrollIntoView({ behavior: "smooth", block: "start" });
    };

    return (
      <a href={finalHref} {...anchorProps} onClick={handleClick}>
        {children}
      </a>
    );
  }

  return (
    <Link href={finalHref} {...props}>
      {children}
    </Link>
  );
}
