import { useStore } from "../../../../xyflow/react.js";
import { useLayoutEffect, useRef } from "react";
import { rebalanceWaypoints, waypointsEqual } from "../waypoints.js";
import { useEdgeWaypointWriter } from "./useEdgeWaypointWriter.js";
function useNodeDragRebalance(args) {
    const { edgeId, source, target, sourceX, sourceY, sourcePosition, targetX, targetY, targetPosition, waypoints, enabled, onChange } = args;
    const dragging = useStore((state)=>enabled && !!(state.nodeLookup.get(source)?.dragging || state.nodeLookup.get(target)?.dragging));
    const write = useEdgeWaypointWriter(edgeId, onChange);
    const baselineRef = useRef({
        s: {
            x: sourceX,
            y: sourceY
        },
        t: {
            x: targetX,
            y: targetY
        },
        waypoints
    });
    const lastRebalancedRef = useRef(null);
    const prevDraggingRef = useRef(false);
    const active = enabled && dragging && waypoints.length > 0;
    if (!dragging) baselineRef.current = {
        s: {
            x: sourceX,
            y: sourceY
        },
        t: {
            x: targetX,
            y: targetY
        },
        waypoints
    };
    let display = waypoints;
    if (active) {
        const { s, t, waypoints: w0 } = baselineRef.current;
        display = rebalanceWaypoints(w0, {
            position: sourcePosition,
            from: s,
            to: {
                x: sourceX,
                y: sourceY
            }
        }, {
            position: targetPosition,
            from: t,
            to: {
                x: targetX,
                y: targetY
            }
        });
        lastRebalancedRef.current = display;
    }
    useLayoutEffect(()=>{
        const wasDragging = prevDraggingRef.current;
        prevDraggingRef.current = dragging;
        if (!wasDragging || dragging) return;
        const final = lastRebalancedRef.current;
        lastRebalancedRef.current = null;
        if (enabled && final && !waypointsEqual(waypoints, final)) write(final);
    });
    return display;
}
export { useNodeDragRebalance };
