"use client";
import { useEffect } from "react";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { mergeRegister } from "@lexical/utils";
import { $getSelection, $isElementNode, $isRangeSelection, COMMAND_PRIORITY_LOW, PASTE_COMMAND, declarePeerDependency, defineExtension } from "lexical";
import { validateUrl } from "../../utils/url.js";
import { BylineFloatingUIExtension } from "../byline-floating-ui/byline-floating-ui-extension.js";
import { $toggleLink, AutoLinkNode, LinkNode, TOGGLE_LINK_COMMAND } from "./index.js";
import { FloatingLinkEditorPlugin } from "./floating-link-editor.js";
function registerLink(editor) {
    return mergeRegister(editor.registerCommand(TOGGLE_LINK_COMMAND, (payload)=>{
        if (null === payload) {
            $toggleLink(payload);
            return true;
        }
        if ('custom' === payload.linkType) {
            const url = payload.url ?? '';
            if (!url.startsWith('/') && !validateUrl(url)) return false;
        }
        $toggleLink(payload);
        return true;
    }, COMMAND_PRIORITY_LOW), editor.registerCommand(PASTE_COMMAND, (event)=>{
        const selection = $getSelection();
        if (!$isRangeSelection(selection) || selection.isCollapsed() || !(event instanceof ClipboardEvent) || null == event.clipboardData) return false;
        const clipboardText = event.clipboardData.getData('text');
        if (!validateUrl(clipboardText)) return false;
        if (selection.getNodes().some((node)=>$isElementNode(node))) return false;
        editor.dispatchCommand(TOGGLE_LINK_COMMAND, {
            linkType: 'custom',
            url: clipboardText
        });
        event.preventDefault();
        return true;
    }, COMMAND_PRIORITY_LOW));
}
function LinkPlugin() {
    const [editor] = useLexicalComposerContext();
    useEffect(()=>{
        if (!editor.hasNodes([
            LinkNode
        ])) throw new Error('LinkPlugin: LinkNode not registered on editor');
        return registerLink(editor);
    }, [
        editor
    ]);
    return null;
}
const LinkExtension = defineExtension({
    name: '@byline/richtext-lexical/Link',
    nodes: ()=>[
            LinkNode,
            AutoLinkNode
        ],
    register: registerLink,
    peerDependencies: [
        declarePeerDependency(BylineFloatingUIExtension.name, {
            items: [
                {
                    id: '@byline/richtext-lexical/Link/floating-editor',
                    Component: FloatingLinkEditorPlugin
                }
            ]
        })
    ]
});
export { LinkExtension, LinkPlugin, registerLink };
