import { useRef, useCallback } from 'react';

interface GameTouchButtonProps {
  onAction: () => void;
  children: React.ReactNode;
  className?: string;
  interval?: number;
  initialDelay?: number;
  disabled?: boolean;
}

/**
 * A button component that supports press-and-hold for continuous action
 * Used in mobile game controls
 */
const GameTouchButton = ({
  onAction,
  children,
  className = '',
  interval = 80,
  initialDelay = 120,
  disabled = false,
}: GameTouchButtonProps) => {
  const intervalRef = useRef<NodeJS.Timeout | null>(null);
  const timeoutRef = useRef<NodeJS.Timeout | null>(null);

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

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

  return (
    <button
      onTouchStart={(e) => {
        e.preventDefault();
        start();
      }}
      onTouchEnd={(e) => {
        e.preventDefault();
        stop();
      }}
      onTouchCancel={(e) => {
        e.preventDefault();
        stop();
      }}
      onMouseDown={start}
      onMouseUp={stop}
      onMouseLeave={stop}
      onContextMenu={(e) => e.preventDefault()}
      disabled={disabled}
      className={`select-none touch-none ${className}`}
    >
      {children}
    </button>
  );
};

export default GameTouchButton;
