import * as React from "react";
import { useRouter } from "next/navigation";
import { useEdenContext } from "../components/context";
import * as Path from "../utils/path";
export default function usePatchedInternalLinks() {
    const { lang, path, isConnected } = useEdenContext();
    const router = useRouter();
    const patchInternalLinkClick = React.useCallback(async (e) => {
        const selector = "section[data-template] a";
        const link = e.target.closest(selector);
        const hasBeenPrevented = e.defaultPrevented;
        if (!hasBeenPrevented && link) {
            const href = link.getAttribute("href");
            if (!href)
                return;
            const hasTargetBlank = link.getAttribute("target") === "_blank";
            const relativePath = Path.getRelative(href);
            if (relativePath && !hasTargetBlank) {
                e.preventDefault();
                router.push(relativePath);
            }
        }
    }, [lang, path, router]);
    React.useEffect(() => {
        if (!isConnected) {
            document.addEventListener("click", patchInternalLinkClick);
            return () => {
                document.removeEventListener("click", patchInternalLinkClick);
            };
        }
    }, [isConnected, patchInternalLinkClick]);
}
