"use client";

import { useCallback, useRef, useState } from "react";

type LongPressOptions = {
  delay?: number;
};

export function useLongPress(
  onLongPress: () => void,
  { delay = 2000 }: LongPressOptions = {}
) {
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const blockClickRef = useRef(false);
  const [pressing, setPressing] = useState(false);

  const clear = useCallback(() => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = null;
    }
  }, []);

  const onPointerDown = useCallback(
    (e: React.PointerEvent) => {
      if (e.button !== 0) return;
      blockClickRef.current = false;
      setPressing(true);
      clear();
      timerRef.current = setTimeout(() => {
        blockClickRef.current = true;
        setPressing(false);
        if (typeof navigator !== "undefined" && navigator.vibrate) {
          navigator.vibrate(15);
        }
        onLongPress();
      }, delay);
    },
    [clear, delay, onLongPress]
  );

  const endPress = useCallback(() => {
    clear();
    setPressing(false);
  }, [clear]);

  const shouldBlockClick = useCallback(() => {
    if (blockClickRef.current) {
      blockClickRef.current = false;
      return true;
    }
    return false;
  }, []);

  const cancelPress = useCallback(() => {
    clear();
    setPressing(false);
  }, [clear]);

  return {
    pressing,
    shouldBlockClick,
    cancelPress,
    handlers: {
      onPointerDown,
      onPointerUp: endPress,
      onPointerLeave: endPress,
      onPointerCancel: endPress,
      onContextMenu: (e: React.MouseEvent) => e.preventDefault(),
    },
  };
}
