import { useReactFlow, useStore } from "../../xyflow/react.js";
import { useCallback } from "react";
function useNodeCollapse({ nodeId, collapseConfig }) {
    const { setNodes, setEdges } = useReactFlow();
    const isCollapseEnabled = collapseConfig?.enabled ?? false;
    const isCollapsed = collapseConfig?.collapsed ?? false;
    const handleIds = collapseConfig?.handleIds ?? [];
    const connectedNodeIds = useStore((state)=>{
        if (!isCollapseEnabled || 0 === handleIds.length) return new Set();
        const connectedIds = new Set();
        state.edges.forEach((edge)=>{
            if (edge.source === nodeId && handleIds.includes(edge.sourceHandle ?? '')) connectedIds.add(edge.target);
            if (edge.target === nodeId && handleIds.includes(edge.targetHandle ?? '')) connectedIds.add(edge.source);
        });
        return connectedIds;
    }, (a, b)=>a.size === b.size && [
            ...a
        ].every((id)=>b.has(id)));
    const hasCollapsibleConnections = connectedNodeIds.size > 0;
    const collapse = useCallback(()=>{
        if (!isCollapseEnabled || 0 === connectedNodeIds.size) return;
        setNodes((nodes)=>nodes.map((node)=>connectedNodeIds.has(node.id) ? {
                    ...node,
                    hidden: true
                } : node));
        setEdges((edges)=>edges.map((edge)=>connectedNodeIds.has(edge.source) || connectedNodeIds.has(edge.target) ? {
                    ...edge,
                    hidden: true
                } : edge));
        collapseConfig?.onCollapseChange?.(true);
    }, [
        isCollapseEnabled,
        connectedNodeIds,
        setNodes,
        setEdges,
        collapseConfig
    ]);
    const expand = useCallback(()=>{
        if (!isCollapseEnabled || 0 === connectedNodeIds.size) return;
        setNodes((nodes)=>nodes.map((node)=>connectedNodeIds.has(node.id) ? {
                    ...node,
                    hidden: false
                } : node));
        setEdges((edges)=>edges.map((edge)=>connectedNodeIds.has(edge.source) || connectedNodeIds.has(edge.target) ? {
                    ...edge,
                    hidden: false
                } : edge));
        collapseConfig?.onCollapseChange?.(false);
    }, [
        isCollapseEnabled,
        connectedNodeIds,
        setNodes,
        setEdges,
        collapseConfig
    ]);
    const toggle = useCallback(()=>{
        if (isCollapsed) expand();
        else collapse();
    }, [
        isCollapsed,
        expand,
        collapse
    ]);
    return {
        isCollapsed,
        isCollapseEnabled,
        hasCollapsibleConnections,
        expand,
        collapse,
        toggle
    };
}
export { useNodeCollapse };
