import { useCallback, useEffect, useRef } from "react";
import { useLatestRef } from "./useLatestRef.js";
function useDragSession(handlers) {
    const handlersRef = useLatestRef(handlers);
    const startRef = useRef(null);
    const cleanupRef = useRef(null);
    useEffect(()=>()=>cleanupRef.current?.(), []);
    return useCallback((e)=>{
        if (0 !== e.button) return;
        e.stopPropagation();
        e.preventDefault();
        startRef.current = {
            x: e.clientX,
            y: e.clientY
        };
        handlersRef.current.onStart?.();
        const handleMove = (ev)=>{
            const start = startRef.current;
            if (!start) return;
            handlersRef.current.onMove?.({
                x: ev.clientX - start.x,
                y: ev.clientY - start.y
            });
        };
        const handleUp = ()=>{
            startRef.current = null;
            window.removeEventListener('mousemove', handleMove);
            window.removeEventListener('mouseup', handleUp);
            cleanupRef.current = null;
            handlersRef.current.onEnd?.();
        };
        cleanupRef.current = ()=>{
            window.removeEventListener('mousemove', handleMove);
            window.removeEventListener('mouseup', handleUp);
            startRef.current = null;
        };
        window.addEventListener('mousemove', handleMove);
        window.addEventListener('mouseup', handleUp);
    }, [
        handlersRef,
        startRef,
        cleanupRef
    ]);
}
export { useDragSession };
