import { useRef, useCallback } from 'react';

/**
 * Hook for handling press-and-hold touch interactions
 * Fires the callback continuously while the button is held
 */
export const useTouchHold = (
  callback: () => void,
  interval = 100,
  initialDelay = 150
) => {
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);

  const start = useCallback(() => {
    // Fire immediately on touch
    callback();
    
    // Start repeating after initial delay
    timeoutRef.current = setTimeout(() => {
      intervalRef.current = setInterval(() => {
        callback();
      }, interval);
    }, initialDelay);
  }, [callback, interval, initialDelay]);

  const stop = useCallback(() => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
      timeoutRef.current = null;
    }
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
  }, []);

  const handlers = {
    onTouchStart: (e: React.TouchEvent) => {
      e.preventDefault();
      start();
    },
    onTouchEnd: (e: React.TouchEvent) => {
      e.preventDefault();
      stop();
    },
    onTouchCancel: (e: React.TouchEvent) => {
      e.preventDefault();
      stop();
    },
    // Also support mouse for testing on desktop
    onMouseDown: start,
    onMouseUp: stop,
    onMouseLeave: stop,
  };

  return handlers;
};

export default useTouchHold;
