"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    AddNodeManager: ()=>AddNodeManager
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const react_cjs_namespaceObject = require("../../xyflow/react.cjs");
const external_react_namespaceObject = require("react");
const external_constants_cjs_namespaceObject = require("../../constants.cjs");
const index_cjs_namespaceObject = require("../../core/index.cjs");
const useCanvasNodeLayout_cjs_namespaceObject = require("../../hooks/useCanvasNodeLayout.cjs");
const usePreviewNode_cjs_namespaceObject = require("../../hooks/usePreviewNode.cjs");
const createPreviewNode_cjs_namespaceObject = require("../../utils/createPreviewNode.cjs");
const external_FloatingCanvasPanel_index_cjs_namespaceObject = require("../FloatingCanvasPanel/index.cjs");
const external_AddNodeManager_helpers_cjs_namespaceObject = require("./AddNodeManager.helpers.cjs");
const external_AddNodePanel_cjs_namespaceObject = require("./AddNodePanel.cjs");
const AddNodeManager = ({ initializing, customPanel: CustomPanel, createNodeData, onBeforeNodeAdded, onNodeAdded, ignoredNodeTypes })=>{
    const reactFlowInstance = (0, react_cjs_namespaceObject.useReactFlow)();
    const registry = (0, index_cjs_namespaceObject.useOptionalNodeTypeRegistry)();
    const nodeLayout = (0, useCanvasNodeLayout_cjs_namespaceObject.useCanvasNodeLayout)();
    const { previewNode, previewNodeConnectionInfo } = (0, usePreviewNode_cjs_namespaceObject.usePreviewNode)();
    const lastPreviewNodeRef = (0, external_react_namespaceObject.useRef)(null);
    const restoreEdgesRef = (0, external_react_namespaceObject.useRef)(null);
    (0, external_react_namespaceObject.useEffect)(()=>{
        if (!previewNode && lastPreviewNodeRef.current) {
            reactFlowInstance.setNodes((nodes)=>nodes.filter((n)=>n.id !== external_constants_cjs_namespaceObject.PREVIEW_NODE_ID));
            reactFlowInstance.setEdges((edges)=>{
                const filteredEdges = edges.filter((edge)=>!(0, createPreviewNode_cjs_namespaceObject.isPreviewEdge)(edge));
                const restoredEdges = restoreEdgesRef.current ? [
                    ...filteredEdges,
                    ...restoreEdgesRef.current
                ] : filteredEdges;
                restoreEdgesRef.current = null;
                return restoredEdges;
            });
        } else if (previewNode && !restoreEdgesRef.current) {
            const originalEdge = (0, external_AddNodeManager_helpers_cjs_namespaceObject.getOriginalEdge)(previewNode);
            restoreEdgesRef.current = originalEdge ? [
                originalEdge
            ] : null;
        }
        lastPreviewNodeRef.current = previewNode || null;
    }, [
        previewNode,
        reactFlowInstance
    ]);
    const handleClose = (0, external_react_namespaceObject.useCallback)(()=>{
        reactFlowInstance.setNodes((nodes)=>nodes.map((n)=>n.id === external_constants_cjs_namespaceObject.PREVIEW_NODE_ID ? {
                    ...n,
                    selected: false
                } : n));
    }, [
        reactFlowInstance
    ]);
    const handleNodeSelect = (0, external_react_namespaceObject.useCallback)((nodeItem)=>{
        const currentPreviewNode = reactFlowInstance.getNode(external_constants_cjs_namespaceObject.PREVIEW_NODE_ID);
        if (!currentPreviewNode || !previewNodeConnectionInfo || 0 === previewNodeConnectionInfo.length) return;
        const newNodeId = `${nodeItem.data.type}-${Date.now()}`;
        const baseNodeData = createNodeData ? createNodeData(nodeItem) : {
            label: nodeItem.name,
            subLabel: nodeItem.description
        };
        const nodeData = currentPreviewNode.data?.useSmartHandles ? {
            ...baseNodeData,
            useSmartHandles: true
        } : baseNodeData;
        const previewNodeScope = currentPreviewNode.parentId ? {
            parentId: currentPreviewNode.parentId,
            extent: currentPreviewNode.extent
        } : {};
        const newNodeManifest = registry?.getManifest(nodeItem.data.type);
        const newNode = (0, external_AddNodeManager_helpers_cjs_namespaceObject.alignNodeToPreview)({
            id: newNodeId,
            type: nodeItem.data.type,
            position: currentPreviewNode.position,
            selected: true,
            data: nodeData,
            ...previewNodeScope
        }, currentPreviewNode, previewNodeConnectionInfo, newNodeManifest);
        const newEdges = [];
        const previewEdgeIds = new Set();
        for (const connectionInfoItem of previewNodeConnectionInfo){
            const newNodeHandleType = connectionInfoItem.addNewNodeAsSource ? 'source' : 'target';
            const newNodeDefaultHandle = newNodeManifest ? registry?.getDefaultHandle(newNodeManifest.nodeType, newNodeHandleType) : void 0;
            const newNodeHandleId = newNodeDefaultHandle?.id;
            const edgeSourceTargetData = connectionInfoItem.addNewNodeAsSource ? {
                source: newNode.id,
                sourceHandle: newNodeHandleId,
                target: connectionInfoItem.existingNodeId,
                targetHandle: connectionInfoItem.existingHandleId
            } : {
                source: connectionInfoItem.existingNodeId,
                sourceHandle: connectionInfoItem.existingHandleId,
                target: newNode.id,
                targetHandle: newNodeHandleId
            };
            const newEdgeId = `edge_${edgeSourceTargetData.source}-${edgeSourceTargetData.sourceHandle}-${edgeSourceTargetData.target}-${edgeSourceTargetData.targetHandle}`;
            newEdges.push({
                id: newEdgeId,
                ...edgeSourceTargetData,
                type: 'default'
            });
            previewEdgeIds.add(connectionInfoItem.previewEdgeId);
        }
        const { newNode: finalNode, newEdges: finalEdges } = onBeforeNodeAdded?.(newNode, newEdges) ?? {
            newNode,
            newEdges
        };
        const placementEdges = reactFlowInstance.getEdges();
        let placedNode = finalNode;
        reactFlowInstance.setNodes((nodes)=>{
            const newNodes = [
                ...nodes.filter((n)=>n.id !== external_constants_cjs_namespaceObject.PREVIEW_NODE_ID).map((n)=>({
                        ...n,
                        selected: false
                    })),
                finalNode
            ];
            const placement = (0, external_AddNodeManager_helpers_cjs_namespaceObject.placeAddedNode)({
                nodes: newNodes,
                edges: placementEdges,
                previewNode: currentPreviewNode,
                insertedNode: finalNode,
                layout: nodeLayout,
                ignoredNodeTypes
            });
            placedNode = placement.insertedNode;
            return placement.nodes;
        });
        reactFlowInstance.setEdges((edges)=>[
                ...edges.filter((edge)=>!previewEdgeIds.has(edge.id) && !(0, createPreviewNode_cjs_namespaceObject.isPreviewEdge)(edge)),
                ...finalEdges
            ]);
        restoreEdgesRef.current = null;
        const [firstConnection] = previewNodeConnectionInfo;
        if (firstConnection) {
            const firstMaterializedEdge = finalEdges.find((edge)=>edge.source === placedNode.id || edge.target === placedNode.id);
            const firstEdgeData = firstConnection.addNewNodeAsSource ? {
                source: placedNode.id,
                sourceHandle: firstMaterializedEdge?.sourceHandle ?? 'output'
            } : {
                source: firstConnection.existingNodeId,
                sourceHandle: firstConnection.existingHandleId
            };
            onNodeAdded?.(firstEdgeData.source, firstEdgeData.sourceHandle, placedNode);
        }
        lastPreviewNodeRef.current = null;
    }, [
        previewNodeConnectionInfo,
        reactFlowInstance,
        registry,
        nodeLayout,
        createNodeData,
        onBeforeNodeAdded,
        onNodeAdded,
        ignoredNodeTypes
    ]);
    if (!previewNode || !previewNodeConnectionInfo || 0 === previewNodeConnectionInfo.length) return null;
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_FloatingCanvasPanel_index_cjs_namespaceObject.FloatingCanvasPanel, {
        open: !!previewNode,
        nodeId: external_constants_cjs_namespaceObject.PREVIEW_NODE_ID,
        placement: "right-start",
        offset: external_constants_cjs_namespaceObject.FLOATING_CANVAS_PANEL_OFFSET,
        scrollableContent: !!CustomPanel,
        children: CustomPanel ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(CustomPanel, {
            onNodeSelect: (item)=>handleNodeSelect(item),
            onClose: handleClose
        }) : /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_AddNodePanel_cjs_namespaceObject.AddNodePanel, {
            loading: initializing,
            onNodeSelect: handleNodeSelect,
            onClose: handleClose
        })
    });
};
exports.AddNodeManager = __webpack_exports__.AddNodeManager;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "AddNodeManager"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});
