import { autoUpdate, flip, offset, useFloating, useMergeRefs } from "@floating-ui/react";
import { useInternalNode } from "../../xyflow/react.js";
import { useEffect, useMemo, useRef } from "react";
function useFloatingPosition({ open = true, nodeId, anchorRect, placement = 'right-start', offset: offsetValue = 20, fallbackPlacement = 'none' }) {
    const referenceRef = useRef(null);
    const internalNode = useInternalNode(nodeId || '');
    const computedAnchor = useMemo(()=>{
        if (anchorRect) return anchorRect;
        if (!internalNode) return null;
        const position = internalNode.internals?.positionAbsolute || {
            x: 0,
            y: 0
        };
        const width = internalNode.measured?.width ?? internalNode.width ?? 200;
        const height = internalNode.measured?.height ?? internalNode.height ?? 100;
        return {
            x: position.x,
            y: position.y,
            width,
            height
        };
    }, [
        anchorRect,
        internalNode
    ]);
    const { refs, floatingStyles, update } = useFloating({
        placement,
        open: !!open && !!computedAnchor,
        middleware: [
            offset(offsetValue),
            flip({
                fallbackAxisSideDirection: fallbackPlacement
            })
        ],
        whileElementsMounted: autoUpdate
    });
    const mergedReferenceRef = useMergeRefs([
        refs.setReference,
        referenceRef
    ]);
    useEffect(()=>{
        if (open) update();
    }, [
        open,
        computedAnchor?.x,
        computedAnchor?.y,
        computedAnchor?.width,
        computedAnchor?.height,
        update
    ]);
    return {
        computedAnchor,
        floatingStyles,
        refs,
        mergedReferenceRef
    };
}
export { useFloatingPosition };
