/**
 * Double-tap gesture hook for footswitch capacitive touch / secondary actions.
 *
 * Detects two rapid taps within a configurable threshold and fires
 * onDoubleTap. Single taps fire onSingleTap after a short debounce.
 */

import { useRef, useCallback } from 'react';

interface UseDoubleTapOptions {
  /** Max ms between taps to count as double-tap (default: 300) */
  threshold?: number;
  /** Called on single tap after debounce */
  onSingleTap?: () => void;
  /** Called on double tap */
  onDoubleTap?: () => void;
}

export function useDoubleTap({
  threshold = 300,
  onSingleTap,
  onDoubleTap,
}: UseDoubleTapOptions) {
  const lastTapRef = useRef(0);
  const singleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const handleTap = useCallback(() => {
    const now = Date.now();
    const sinceLast = now - lastTapRef.current;

    if (sinceLast < threshold) {
      // Double tap detected
      if (singleTimerRef.current) {
        clearTimeout(singleTimerRef.current);
        singleTimerRef.current = null;
      }
      lastTapRef.current = 0;
      onDoubleTap?.();
    } else {
      // Potential single tap — wait for double-tap window to close
      lastTapRef.current = now;
      if (singleTimerRef.current) {
        clearTimeout(singleTimerRef.current);
      }
      singleTimerRef.current = setTimeout(() => {
        onSingleTap?.();
        singleTimerRef.current = null;
      }, threshold);
    }
  }, [threshold, onSingleTap, onDoubleTap]);

  return { handleTap };
}

/**
 * Hook for long-press gesture detection.
 * Fires onLongPress after `duration` ms of continuous hold.
 */
export function useLongPress({
  duration = 500,
  onLongPress,
}: {
  duration?: number;
  onLongPress?: () => void;
}) {
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  const handleStart = useCallback(() => {
    timerRef.current = setTimeout(() => {
      onLongPress?.();
    }, duration);
  }, [duration, onLongPress]);

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

  return { handleStart, handleEnd };
}
