/**
 * useResizeDrag — the shared pointer gesture behind every drag handle
 * (ResizeHandle, PaneSplitHandle, InspectorSplitHandle).
 *
 * Returns a `pointerdown` handler: on a primary-button press it measures the
 * gesture's start value, then tracks the pointer on `window` (it leaves the thin
 * handle immediately) and feeds each delta along `axis` to `apply`. While
 * dragging, the body is forced to the matching resize cursor with text selection
 * suppressed; release restores both and detaches the listeners.
 *
 * Only the gesture lives here — what "the start value" means (a pane width, a
 * region height) and how a delta becomes layout is the caller's, as is the
 * keyboard/ARIA half of the splitter contract (it differs per handle).
 */

export function useResizeDrag(
  axis: 'x' | 'y',
  measureStart: () => number,
  apply: (start: number, delta: number) => void,
): (e: React.PointerEvent<HTMLElement>) => void {
  const coord = (e: { clientX: number; clientY: number }) => (axis === 'x' ? e.clientX : e.clientY);
  return (e) => {
    if (e.button !== 0) return; // primary button only
    e.preventDefault();
    const startPos = coord(e);
    const start = measureStart();

    const onMove = (ev: PointerEvent) => apply(start, coord(ev) - startPos);
    const onUp = () => {
      window.removeEventListener('pointermove', onMove);
      window.removeEventListener('pointerup', onUp);
      document.body.style.cursor = '';
      document.body.style.userSelect = '';
    };

    window.addEventListener('pointermove', onMove);
    window.addEventListener('pointerup', onUp);
    document.body.style.cursor = axis === 'x' ? 'col-resize' : 'row-resize';
    document.body.style.userSelect = 'none';
  };
}
