"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { ReactExtension } from "@lexical/react/ReactExtension";
import { useOptionalExtensionDependency } from "@lexical/react/useExtensionComponent";
import { $findMatchingParent, $insertNodeToNearestRoot, mergeRegister } from "@lexical/utils";
import { $createParagraphNode, $createTextNode, $getNodeByKey, $getSelection, $isDecoratorNode, $isElementNode, $isLineBreakNode, $isParagraphNode, $isRangeSelection, $isTextNode, COMMAND_PRIORITY_EDITOR, COMMAND_PRIORITY_LOW, COMMAND_PRIORITY_NORMAL, KEY_ARROW_DOWN_COMMAND, KEY_ARROW_LEFT_COMMAND, KEY_ARROW_RIGHT_COMMAND, KEY_ARROW_UP_COMMAND, configExtension, declarePeerDependency, defineExtension } from "lexical";
import { useToolbarActiveEditor } from "../../plugins/toolbar-plugin/toolbar-active-editor.js";
import { DropDownItem } from "../../ui/dropdown.js";
import { BylineFloatingUIExtension } from "../byline-floating-ui/byline-floating-ui-extension.js";
import { BylineToolbarExtension } from "../byline-toolbar/byline-toolbar-extension.js";
import { FloatingTextFormatExtension } from "../floating-text-format/floating-text-format-extension.js";
import { FloatingTextFormatToolbarPlugin } from "../floating-text-format/index.js";
import { INSERT_ADMONITION_COMMAND, OPEN_ADMONITION_MODAL_COMMAND } from "./admonition-commands.js";
import { AdmonitionModal } from "./admonition-modal.js";
import { $createAdmonitionNode, $isAdmonitionNode, AdmonitionNode } from "./admonition-node.js";
import * as __rspack_external_react from "react";
function $selectionInsideAdmonition() {
    const selection = $getSelection();
    if (!$isRangeSelection(selection)) return false;
    return null != $findMatchingParent(selection.anchor.getNode(), $isAdmonitionNode);
}
function $flattenToParagraph(element) {
    const paragraph = $createParagraphNode();
    const children = element.getChildren();
    const allInline = children.length > 0 && children.every((child)=>$isTextNode(child) || $isLineBreakNode(child) || child.isInline());
    if (allInline) paragraph.append(...children);
    else {
        const text = element.getTextContent();
        if (text.length > 0) paragraph.append($createTextNode(text));
    }
    element.replace(paragraph);
}
function $normalizeAdmonition(node) {
    const parent = node.getParent();
    const ancestorAdmonition = null != parent ? $findMatchingParent(parent, (candidate)=>$isAdmonitionNode(candidate)) : null;
    if (null != ancestorAdmonition) {
        for (const child of node.getChildren())node.insertBefore(child);
        node.remove();
        return;
    }
    if (0 === node.getChildrenSize()) return void node.append($createParagraphNode());
    for (const child of node.getChildren())if (!$isParagraphNode(child)) {
        if ($isTextNode(child) || $isLineBreakNode(child) || child.isInline()) {
            const paragraph = $createParagraphNode();
            child.insertBefore(paragraph);
            paragraph.append(child);
            continue;
        }
        if ($isDecoratorNode(child)) {
            child.remove();
            continue;
        }
        if ($isElementNode(child)) $flattenToParagraph(child);
    }
}
function $onEscapeUp() {
    const selection = $getSelection();
    if ($isRangeSelection(selection) && selection.isCollapsed() && 0 === selection.anchor.offset) {
        const admonition = $findMatchingParent(selection.anchor.getNode(), $isAdmonitionNode);
        if ($isAdmonitionNode(admonition)) {
            const parent = admonition.getParent();
            if (null != parent && parent.getFirstChild() === admonition && selection.anchor.key === admonition.getFirstDescendant()?.getKey()) admonition.insertBefore($createParagraphNode());
        }
    }
    return false;
}
function $onEscapeDown() {
    const selection = $getSelection();
    if ($isRangeSelection(selection) && selection.isCollapsed()) {
        const admonition = $findMatchingParent(selection.anchor.getNode(), $isAdmonitionNode);
        if ($isAdmonitionNode(admonition)) {
            const parent = admonition.getParent();
            if (null != parent && parent.getLastChild() === admonition) {
                const lastParagraph = admonition.getLastDescendant();
                if (null != lastParagraph && selection.anchor.key === lastParagraph.getKey() && selection.anchor.offset === lastParagraph.getTextContentSize()) admonition.insertAfter($createParagraphNode());
            }
        }
    }
    return false;
}
function AdmonitionPlugin() {
    const [editor] = useLexicalComposerContext();
    const [open, setOpen] = __rspack_external_react.useState(false);
    const [editNodeKey, setEditNodeKey] = __rspack_external_react.useState(null);
    const [modalData, setModalData] = __rspack_external_react.useState({
        title: '',
        admonitionType: void 0
    });
    (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, (payload)=>{
            if (null == payload) {
                setEditNodeKey(null);
                setModalData({
                    title: '',
                    admonitionType: void 0
                });
                setOpen(true);
                return true;
            }
            const data = editor.getEditorState().read(()=>{
                const node = $getNodeByKey(payload.nodeKey);
                return $isAdmonitionNode(node) ? {
                    title: node.getTitle(),
                    admonitionType: node.getAdmonitionType()
                } : null;
            });
            if (null == data) return false;
            setEditNodeKey(payload.nodeKey);
            setModalData(data);
            setOpen(true);
            return true;
        }, COMMAND_PRIORITY_NORMAL), editor.registerCommand(INSERT_ADMONITION_COMMAND, (payload)=>{
            const selection = $getSelection();
            if (!$isRangeSelection(selection)) return false;
            if ($selectionInsideAdmonition()) return true;
            const admonition = $createAdmonitionNode(payload);
            admonition.append($createParagraphNode());
            $insertNodeToNearestRoot(admonition);
            admonition.selectStart();
            return true;
        }, COMMAND_PRIORITY_EDITOR), editor.registerNodeTransform(AdmonitionNode, $normalizeAdmonition), editor.registerCommand(KEY_ARROW_DOWN_COMMAND, $onEscapeDown, COMMAND_PRIORITY_LOW), editor.registerCommand(KEY_ARROW_RIGHT_COMMAND, $onEscapeDown, COMMAND_PRIORITY_LOW), editor.registerCommand(KEY_ARROW_UP_COMMAND, $onEscapeUp, COMMAND_PRIORITY_LOW), editor.registerCommand(KEY_ARROW_LEFT_COMMAND, $onEscapeUp, COMMAND_PRIORITY_LOW));
    }, [
        editor
    ]);
    const handleSubmit = ({ admonitionType, title })=>{
        setOpen(false);
        if (null == admonitionType) return;
        const key = editNodeKey;
        if (null != key) editor.update(()=>{
            const node = $getNodeByKey(key);
            if ($isAdmonitionNode(node)) node.update({
                admonitionType,
                title
            });
        });
        else editor.dispatchCommand(INSERT_ADMONITION_COMMAND, {
            admonitionType,
            title
        });
        setEditNodeKey(null);
    };
    return /*#__PURE__*/ jsx(AdmonitionModal, {
        open: open,
        data: modalData,
        onClose: ()=>{
            setOpen(false);
            setEditNodeKey(null);
        },
        onSubmit: handleSubmit
    });
}
function AdmonitionFloatingTextFormat({ anchorElem }) {
    const hasGlobalToolbar = void 0 !== useOptionalExtensionDependency(FloatingTextFormatExtension);
    if (hasGlobalToolbar) return null;
    return /*#__PURE__*/ jsx(FloatingTextFormatToolbarPlugin, {
        anchorElem: anchorElem,
        shouldShow: $selectionInsideAdmonition
    });
}
function AdmonitionInsertItem() {
    const editor = useToolbarActiveEditor();
    return /*#__PURE__*/ jsxs(DropDownItem, {
        onClick: ()=>{
            editor.dispatchCommand(OPEN_ADMONITION_MODAL_COMMAND, null);
        },
        className: "item",
        children: [
            /*#__PURE__*/ jsx("i", {
                className: "icon admonition"
            }),
            /*#__PURE__*/ jsx("span", {
                className: "text",
                children: "Admonition"
            })
        ]
    });
}
const AdmonitionExtension = defineExtension({
    name: '@byline/richtext-lexical/Admonition',
    nodes: ()=>[
            AdmonitionNode
        ],
    dependencies: [
        configExtension(ReactExtension, {
            decorators: [
                /*#__PURE__*/ jsx(AdmonitionPlugin, {}, "d")
            ]
        })
    ],
    peerDependencies: [
        declarePeerDependency(BylineToolbarExtension.name, {
            items: [
                {
                    id: '@byline/richtext-lexical/Admonition/insert',
                    placement: 'insert-menu',
                    order: 30,
                    node: /*#__PURE__*/ jsx(AdmonitionInsertItem, {})
                }
            ]
        }),
        declarePeerDependency(BylineFloatingUIExtension.name, {
            items: [
                {
                    id: '@byline/richtext-lexical/Admonition/floating-text-format',
                    Component: AdmonitionFloatingTextFormat
                }
            ]
        })
    ]
});
export { AdmonitionExtension, AdmonitionPlugin, INSERT_ADMONITION_COMMAND, OPEN_ADMONITION_MODAL_COMMAND };
