import { useReactFlow } from "../xyflow/react.js";
import { useCallback } from "react";
import { getInnerHandleContainerId } from "../components/LoopNode/LoopNode.helpers.js";
import { showPreviewGraph } from "../utils/index.js";
import { useNodeManifestResolver } from "./useCanvasNodeLayout.js";
const EMPTY_IGNORED_NODE_TYPES = [];
function getClientPosition(event) {
    if ('clientX' in event) return {
        x: event.clientX,
        y: event.clientY
    };
    const touch = event.changedTouches?.[0] ?? event.touches?.[0];
    return touch ? {
        x: touch.clientX,
        y: touch.clientY
    } : null;
}
function useAddNodeOnConnectEnd(ignoredNodeTypes = EMPTY_IGNORED_NODE_TYPES) {
    const reactFlowInstance = useReactFlow();
    const getManifestForNode = useNodeManifestResolver();
    return useCallback((event, connectionState)=>{
        if (!(reactFlowInstance && connectionState.fromNode && connectionState.fromHandle) || connectionState.toHandle) return;
        const clientPosition = getClientPosition(event);
        if (!clientPosition) return;
        const flowDropPosition = reactFlowInstance.screenToFlowPosition(clientPosition);
        const source = {
            nodeId: connectionState.fromNode.id,
            handleId: connectionState.fromHandle.id ?? 'output'
        };
        const containerId = getInnerHandleContainerId({
            source,
            reactFlowInstance,
            getManifestForNode
        });
        showPreviewGraph({
            source,
            reactFlowInstance,
            position: flowDropPosition,
            sourceHandleType: connectionState.fromHandle.type,
            handlePosition: connectionState.fromHandle.position,
            ignoredNodeTypes,
            ...containerId ? {
                containerId
            } : {}
        });
    }, [
        reactFlowInstance,
        getManifestForNode,
        ignoredNodeTypes
    ]);
}
export { useAddNodeOnConnectEnd };
