import { useCallback } from 'react';

interface IEventWithTarget {
  target: EventTarget | null;
}

interface ITouchEvent extends IEventWithTarget {
  changedTouches?: TouchList;

  touches?: TouchList;
}

export function useTouchTarget() {
  const getTouchTarget = useCallback(
    (e: MouseEvent | TouchEvent | IEventWithTarget): HTMLElement => {
      // Check if it's a touch event
      if ('changedTouches' in e || 'touches' in e) {
        const touchEvent = e as ITouchEvent;
        const touch = touchEvent.changedTouches?.[0] || touchEvent.touches?.[0];

        if (touch) {
          return document.elementFromPoint(
            touch.clientX,
            touch.clientY
          ) as HTMLElement;
        }
      }

      // If it's not a touch event or touch is not available, fallback to target
      return (e.target as HTMLElement) || document.body;
    },
    []
  );

  return getTouchTarget;
}

export default useTouchTarget;
