export const GALLERY_DISTANCE_RATIO = 0.18;
export const GALLERY_MIN_DISTANCE_PX = 56;
export const GALLERY_FAST_SWIPE_MIN_DISTANCE_PX = 24;
export const GALLERY_FAST_SWIPE_VELOCITY_PX_PER_MS = 0.45;
export const GALLERY_EDGE_RESISTANCE = 0.28;

export type GallerySwipeDirection = -1 | 0 | 1;

export interface ResolveGallerySwipeInput {
  distance: number;
  durationMs: number;
  viewportWidth: number;
  hasPrevious: boolean;
  hasNext: boolean;
}

export function getResistedGalleryDragDistance(
  distance: number,
  hasPrevious: boolean,
  hasNext: boolean,
): number {
  if (distance > 0 && !hasPrevious) {
    return distance * GALLERY_EDGE_RESISTANCE;
  }
  if (distance < 0 && !hasNext) {
    return distance * GALLERY_EDGE_RESISTANCE;
  }
  return distance;
}

export function resolveGallerySwipeDirection({
  distance,
  durationMs,
  viewportWidth,
  hasPrevious,
  hasNext,
}: ResolveGallerySwipeInput): GallerySwipeDirection {
  if (distance === 0) return 0;

  const absoluteDistance = Math.abs(distance);
  const distanceThreshold = Math.max(
    GALLERY_MIN_DISTANCE_PX,
    Math.max(0, viewportWidth) * GALLERY_DISTANCE_RATIO,
  );
  const velocity = absoluteDistance / Math.max(1, durationMs);
  const passedDistanceThreshold = absoluteDistance >= distanceThreshold;
  const passedVelocityThreshold =
    absoluteDistance >= GALLERY_FAST_SWIPE_MIN_DISTANCE_PX &&
    velocity >= GALLERY_FAST_SWIPE_VELOCITY_PX_PER_MS;

  if (!passedDistanceThreshold && !passedVelocityThreshold) return 0;
  if (distance > 0) return hasPrevious ? -1 : 0;
  return hasNext ? 1 : 0;
}
