import { useNodes, useOnSelectionChange, useReactFlow } from "../../../xyflow/react.js";
import { useCallback, useEffect, useState } from "react";
function applySelection(nodes, nodeId) {
    return nodes.map((node)=>{
        const shouldBeSelected = node.id === nodeId;
        if (node.selected === shouldBeSelected) return node;
        return {
            ...node,
            selected: shouldBeSelected
        };
    });
}
function useNodeSelection(nodeId, maintainSelection = true) {
    const nodes = useNodes();
    const { setNodes } = useReactFlow();
    const [selectedNodeId, setSelectedNodeId] = useState(nodeId || null);
    useOnSelectionChange({
        onChange: useCallback(({ nodes: selectedNodes })=>{
            if (!nodeId) 1 === selectedNodes.length && selectedNodes[0] ? setSelectedNodeId(selectedNodes[0].id) : setSelectedNodeId(null);
        }, [
            nodeId
        ])
    });
    useEffect(()=>{
        if (maintainSelection && selectedNodeId) setNodes((nds)=>applySelection(nds, selectedNodeId));
    }, [
        selectedNodeId,
        maintainSelection,
        setNodes
    ]);
    const selectedNode = nodes.find((node)=>node.id === selectedNodeId);
    return {
        selectedNodeId,
        setSelectedNodeId,
        selectedNode
    };
}
function useSetNodeSelection() {
    const { setNodes } = useReactFlow();
    const setSelectedNodeId = useCallback((nodeId)=>{
        setNodes((nds)=>applySelection(nds, nodeId));
    }, [
        setNodes
    ]);
    return {
        setSelectedNodeId
    };
}
export { useNodeSelection, useSetNodeSelection };
