import { useRef, type TouchEvent } from 'react';

export interface EdgeSwipeOptions {
  edgeWidth: number;
  openThreshold: number;
  verticalTolerance: number;
}

export interface SwipePoint {
  x: number;
  y: number;
}

const DEFAULTS: EdgeSwipeOptions = {
  edgeWidth: 20,
  openThreshold: 60,
  verticalTolerance: 40,
};

export function evaluateEdgeSwipe(
  start: SwipePoint,
  end: SwipePoint,
  opts: EdgeSwipeOptions,
): 'open' | null {
  if (start.x >= opts.edgeWidth) return null;
  const dx = end.x - start.x;
  const dy = end.y - start.y;
  if (Math.abs(dy) > opts.verticalTolerance) return null;
  if (dx < opts.openThreshold) return null;
  return 'open';
}

interface UseEdgeSwipeOptions extends Partial<EdgeSwipeOptions> {
  enabled?: boolean;
  onOpen: () => void;
}

export function useEdgeSwipe({
  enabled = true,
  onOpen,
  edgeWidth = DEFAULTS.edgeWidth,
  openThreshold = DEFAULTS.openThreshold,
  verticalTolerance = DEFAULTS.verticalTolerance,
}: UseEdgeSwipeOptions) {
  const start = useRef<SwipePoint | null>(null);

  const onTouchStart = (e: TouchEvent<HTMLElement>) => {
    if (!enabled) return;
    const touch = e.touches[0];
    if (!touch) return;
    if (touch.clientX >= edgeWidth) return;
    start.current = { x: touch.clientX, y: touch.clientY };
  };

  const onTouchEnd = (e: TouchEvent<HTMLElement>) => {
    const s = start.current;
    start.current = null;
    if (!enabled || !s) return;
    const touch = e.changedTouches[0];
    if (!touch) return;
    const result = evaluateEdgeSwipe(
      s,
      { x: touch.clientX, y: touch.clientY },
      { edgeWidth, openThreshold, verticalTolerance },
    );
    if (result === 'open') onOpen();
  };

  const onTouchCancel = () => {
    start.current = null;
  };

  return { onTouchStart, onTouchEnd, onTouchCancel };
}
