"use client";
import { jsx } from "react/jsx-runtime";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { $insertNodeToNearestRoot, mergeRegister } from "@lexical/utils";
import { $getSelection, $isRangeSelection, COMMAND_PRIORITY_EDITOR, COMMAND_PRIORITY_NORMAL, createCommand } from "lexical";
import { $createAdmonitionNode, AdmonitionNode } from "../../nodes/admonition-node/index.js";
import { AdmonitionModal } from "./admonition-modal.js";
import * as __rspack_external_react from "react";
const OPEN_ADMONITION_MODAL_COMMAND = createCommand('OPEN_ADMONITION_MODAL_COMMAND');
const INSERT_ADMONITION_COMMAND = createCommand('INSERT_ADMONITION_COMMAND');
function AdmonitionPlugin() {
    const [editor] = useLexicalComposerContext();
    const [open, setOpen] = __rspack_external_react.useState(false);
    (0, __rspack_external_react.useEffect)(()=>{
        if (!editor.hasNodes([
            AdmonitionNode
        ])) throw new Error('AdmonitionPlugin: AdmonitionNode not registered on editor');
        return mergeRegister(editor.registerCommand(OPEN_ADMONITION_MODAL_COMMAND, ()=>{
            setOpen(true);
            return true;
        }, COMMAND_PRIORITY_NORMAL), editor.registerCommand(INSERT_ADMONITION_COMMAND, (payload)=>{
            const selection = $getSelection();
            if (!$isRangeSelection(selection)) return false;
            const focusNode = selection.focus.getNode();
            if (null !== focusNode) {
                const admonitionNode = $createAdmonitionNode(payload);
                $insertNodeToNearestRoot(admonitionNode);
            }
            return true;
        }, COMMAND_PRIORITY_EDITOR));
    }, [
        editor
    ]);
    const handleInsertAdmonition = ({ admonitionType, title })=>{
        if (null != title && null != admonitionType) {
            const admonitionPayload = {
                admonitionType,
                title
            };
            editor.dispatchCommand(INSERT_ADMONITION_COMMAND, admonitionPayload);
        } else console.error('Error: missing title or type for admonition.');
        setOpen(false);
    };
    return /*#__PURE__*/ jsx(AdmonitionModal, {
        open: open,
        data: {
            title: '',
            admonitionType: void 0
        },
        onClose: ()=>setOpen(false),
        onSubmit: handleInsertAdmonition
    });
}
export { AdmonitionPlugin, INSERT_ADMONITION_COMMAND, OPEN_ADMONITION_MODAL_COMMAND };
