type EdgeSwipeTracking = {
  startX: number;
  startY: number;
  direction: 'back' | 'forward';
};

const EDGE_HOTZONE_PX = 24;
const MIN_HORIZONTAL_SWIPE_PX = 12;
const MAX_VERTICAL_DRIFT_PX = 48;

function isMobileTouchEnvironment() {
  if (typeof window === 'undefined') {
    return false;
  }

  return window.matchMedia('(pointer: coarse)').matches || window.matchMedia('(hover: none)').matches;
}

export function setupMobileNavigationGestureBlocker() {
  if (typeof window === 'undefined' || typeof document === 'undefined' || !isMobileTouchEnvironment()) {
    return () => undefined;
  }

  let tracking: EdgeSwipeTracking | null = null;

  const handleTouchStart = (event: TouchEvent) => {
    const touch = event.touches[0];

    if (!touch || event.touches.length !== 1) {
      tracking = null;
      return;
    }

    if (touch.clientX <= EDGE_HOTZONE_PX) {
      tracking = {
        startX: touch.clientX,
        startY: touch.clientY,
        direction: 'back',
      };
      return;
    }

    if (touch.clientX >= window.innerWidth - EDGE_HOTZONE_PX) {
      tracking = {
        startX: touch.clientX,
        startY: touch.clientY,
        direction: 'forward',
      };
      return;
    }

    tracking = null;
  };

  const handleTouchMove = (event: TouchEvent) => {
    const touch = event.touches[0];

    if (!tracking || !touch) {
      return;
    }

    const deltaX = touch.clientX - tracking.startX;
    const deltaY = touch.clientY - tracking.startY;
    const absDeltaY = Math.abs(deltaY);
    const isHorizontalEdgeSwipe =
      absDeltaY <= MAX_VERTICAL_DRIFT_PX &&
      ((tracking.direction === 'back' && deltaX >= MIN_HORIZONTAL_SWIPE_PX) ||
        (tracking.direction === 'forward' && deltaX <= MIN_HORIZONTAL_SWIPE_PX * -1));

    if (!isHorizontalEdgeSwipe) {
      return;
    }

    event.preventDefault();
  };

  const resetTracking = () => {
    tracking = null;
  };

  document.addEventListener('touchstart', handleTouchStart, { passive: true, capture: true });
  document.addEventListener('touchmove', handleTouchMove, { passive: false, capture: true });
  document.addEventListener('touchend', resetTracking, { passive: true, capture: true });
  document.addEventListener('touchcancel', resetTracking, { passive: true, capture: true });

  return () => {
    document.removeEventListener('touchstart', handleTouchStart, true);
    document.removeEventListener('touchmove', handleTouchMove, true);
    document.removeEventListener('touchend', resetTracking, true);
    document.removeEventListener('touchcancel', resetTracking, true);
  };
}
