import { useRef, useState } from 'react';

export default function useHorizontalSwipeMenu({ railWidth = 132, threshold = 66 } = {}) {
  const pointerId = useRef(null);
  const start = useRef({ x: 0, y: 0 });
  const suppressClick = useRef(false);
  const [translateX, setTranslateX] = useState(0);
  const [open, setOpen] = useState(false);
  const [dragging, setDragging] = useState(false);

  const close = () => {
    setOpen(false);
    setTranslateX(0);
  };

  const onPointerDown = (event) => {
    if (event.pointerType === 'mouse' && event.button !== 0) return;
    pointerId.current = event.pointerId;
    start.current = { x: event.clientX, y: event.clientY };
    suppressClick.current = false;
    setDragging(false);
  };

  const onPointerMove = (event) => {
    if (pointerId.current !== event.pointerId) return;
    const dx = event.clientX - start.current.x;
    const dy = event.clientY - start.current.y;

    if (!dragging && (Math.abs(dx) < 8 || Math.abs(dx) < Math.abs(dy))) return;

    event.currentTarget.setPointerCapture?.(event.pointerId);
    event.preventDefault();
    suppressClick.current = true;
    setDragging(true);

    const base = open ? -railWidth : 0;
    const next = Math.max(-railWidth, Math.min(0, base + dx));
    setTranslateX(next);
  };

  const onPointerUp = (event) => {
    if (pointerId.current !== event.pointerId) return;
    event.currentTarget.releasePointerCapture?.(event.pointerId);
    pointerId.current = null;

    const shouldOpen = Math.abs(translateX) > threshold;
    setOpen(shouldOpen);
    setTranslateX(shouldOpen ? -railWidth : 0);
    window.setTimeout(() => setDragging(false), 40);
  };

  const onPointerCancel = () => {
    pointerId.current = null;
    setDragging(false);
    setTranslateX(open ? -railWidth : 0);
  };

  return {
    open,
    dragging,
    translateX,
    revealRatio: Math.min(1, Math.abs(translateX) / railWidth),
    close,
    swipeHandlers: {
      onPointerDown,
      onPointerMove,
      onPointerUp,
      onPointerCancel,
      onClickCapture: (event) => {
        if (!suppressClick.current) return;
        event.preventDefault();
        event.stopPropagation();
        suppressClick.current = false;
      },
    },
  };
}
