import { useReactFlow, useStore } from "../xyflow/react.js";
import { useMemo } from "react";
import { shallow } from "zustand/shallow";
import { PREVIEW_NODE_ID } from "../constants.js";
import { useOptionalNodeTypeRegistry } from "../core/index.js";
import { isPreviewEdge } from "../utils/createPreviewNode.js";
const previewNodeSelectedSelector = (state)=>{
    const node = state.nodes.find((n)=>n.id === PREVIEW_NODE_ID);
    return node?.selected ?? false;
};
const edgesConnectedToPreviewSelector = (state)=>state.edges.filter(isPreviewEdge).map((edge)=>({
            id: edge.id,
            source: edge.source,
            target: edge.target,
            sourceHandle: edge.sourceHandle,
            targetHandle: edge.targetHandle
        }));
const usePreviewNode = ()=>{
    const reactFlowInstance = useReactFlow();
    const isPreviewNodeSelected = useStore(previewNodeSelectedSelector);
    const previewEdges = useStore(edgesConnectedToPreviewSelector, shallow);
    const registry = useOptionalNodeTypeRegistry();
    const previewNode = isPreviewNodeSelected ? reactFlowInstance.getNode(PREVIEW_NODE_ID) ?? null : null;
    const connectionInfo = useMemo(()=>{
        if (!isPreviewNodeSelected) return null;
        const connections = previewEdges.map((previewEdge)=>{
            const sourceIsPreviewNode = previewEdge.source === PREVIEW_NODE_ID;
            const existingNodeId = sourceIsPreviewNode ? previewEdge.target : previewEdge.source;
            const existingNodeType = reactFlowInstance.getNode(existingNodeId)?.type;
            const existingNodeManifest = existingNodeType ? registry?.getManifest(existingNodeType) : void 0;
            const existingHandleId = sourceIsPreviewNode ? previewEdge.targetHandle || 'input' : previewEdge.sourceHandle || 'output';
            const existingHandleManifest = existingNodeManifest?.handleConfiguration.flatMap((hg)=>hg.handles).find((h)=>{
                if (h.id === existingHandleId) return true;
                const repeatHandleIdBase = h.repeat && h.id.split('{')[0];
                if (repeatHandleIdBase) return existingHandleId.startsWith(repeatHandleIdBase);
                return false;
            });
            return {
                addNewNodeAsSource: sourceIsPreviewNode,
                existingNodeId,
                existingHandleId,
                existingNodeManifest,
                existingHandleManifest,
                previewEdgeId: previewEdge.id
            };
        });
        return connections;
    }, [
        isPreviewNodeSelected,
        previewEdges,
        reactFlowInstance,
        registry
    ]);
    return {
        previewNode,
        previewNodeConnectionInfo: connectionInfo
    };
};
export { usePreviewNode };
