import { useRef } from "react";

export const useClickDetection = () => {
  const pointerDownRef = useRef(null);
  const isScrollingRef = useRef(false);

  const handlePointerDown = (e, id) => {
    pointerDownRef.current = {
      x: e.clientX,
      y: e.clientY,
      time: Date.now(),
      id,
    };
    isScrollingRef.current = false;
  };

  const handlePointerUp = (e, id, callback) => {
    if (!pointerDownRef.current || isScrollingRef.current) {
      return;
    }

    const { x: startX, y: startY, time: startTime } = pointerDownRef.current;
    const endX = e.clientX;
    const endY = e.clientY;
    const endTime = Date.now();

    // Проверяем расстояние и время
    const distance = Math.sqrt(
      Math.pow(endX - startX, 2) + Math.pow(endY - startY, 2)
    );
    const duration = endTime - startTime;

    // Если расстояние маленькое и время короткое - это клик
    if (distance < 10 && duration < 300) {
      callback(id);
    }

    pointerDownRef.current = null;
  };

  const handleScroll = () => {
    isScrollingRef.current = true;
    pointerDownRef.current = null;
  };

  return {
    handlePointerDown,
    handlePointerUp,
    handleScroll,
  };
};
