/**
 * Touch swipe detection for horizontal month navigation.
 * Replaces swipe logic from webapp/js/main.js (threshold 50px).
 */

"use client";

import { useEffect, useRef } from "react";

export interface UseSwipeOptions {
  /** Minimum horizontal distance (px) to count as swipe. Default 50. */
  threshold?: number;
  /** When true, swipe handlers are not attached. */
  disabled?: boolean;
}

/**
 * Attaches touchstart/touchend to the element ref and invokes onSwipeLeft or onSwipeRight
 * when a horizontal swipe exceeds the threshold. Vertical swipes are ignored.
 */
export function useSwipe(
  elementRef: React.RefObject<HTMLElement | null>,
  onSwipeLeft: () => void,
  onSwipeRight: () => void,
  options: UseSwipeOptions = {}
): void {
  const { threshold = 50, disabled = false } = options;
  const startX = useRef(0);
  const startY = useRef(0);
  const onSwipeLeftRef = useRef(onSwipeLeft);
  const onSwipeRightRef = useRef(onSwipeRight);
  onSwipeLeftRef.current = onSwipeLeft;
  onSwipeRightRef.current = onSwipeRight;

  useEffect(() => {
    const el = elementRef.current;
    if (!el || disabled) return;

    const handleStart = (e: TouchEvent) => {
      if (e.changedTouches.length === 0) return;
      const t = e.changedTouches[0];
      startX.current = t.clientX;
      startY.current = t.clientY;
    };

    const handleEnd = (e: TouchEvent) => {
      if (e.changedTouches.length === 0) return;
      const t = e.changedTouches[0];
      const deltaX = t.clientX - startX.current;
      const deltaY = t.clientY - startY.current;
      if (Math.abs(deltaX) <= threshold) return;
      if (Math.abs(deltaY) > Math.abs(deltaX)) return;
      if (deltaX > threshold) {
        onSwipeRightRef.current();
      } else if (deltaX < -threshold) {
        onSwipeLeftRef.current();
      }
    };

    el.addEventListener("touchstart", handleStart, { passive: true });
    el.addEventListener("touchend", handleEnd, { passive: true });
    return () => {
      el.removeEventListener("touchstart", handleStart);
      el.removeEventListener("touchend", handleEnd);
    };
  }, [elementRef, disabled, threshold]);
}
