"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";

import type { ComponentProps } from "react";

type TurboLinkProps = ComponentProps<typeof Link>;

export const TurboLink = ({
  onClick,
  onMouseEnter,
  onPointerEnter,
  onTouchStart,
  onFocus,
  children,
  ...props
}: TurboLinkProps) => {
  const router = useRouter();
  const strHref =
    typeof props.href === "string" ? props.href : props.href.href;

  const conditionalPrefetch = () => {
    if (strHref) {
      void router.prefetch(strHref);
    }
  };

  const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
    onClick?.(e);
    if (e.defaultPrevented) return;

    const hash = strHref?.split("#")[1];
    if (hash) {
      const el = document.getElementById(hash);
      if (el) {
        e.preventDefault();
        el.scrollIntoView({ behavior: "smooth" });
        window.history.pushState(null, "", `#${hash}`);
      }
    }
  };

  return (
    <Link
      {...props}
      prefetch={false}
      onClick={handleClick}
      onMouseEnter={(e) => {
        conditionalPrefetch();
        onMouseEnter?.(e);
      }}
      onPointerEnter={(e) => {
        conditionalPrefetch();
        onPointerEnter?.(e);
      }}
      onTouchStart={(e) => {
        conditionalPrefetch();
        onTouchStart?.(e);
      }}
      onFocus={(e) => {
        conditionalPrefetch();
        onFocus?.(e);
      }}
    >
      {children}
    </Link>
  );
};
