import type { PendingVote, ViewportMode } from "../types/player";

export const HOLD_THRESHOLD_MS = 120;
export const DRAG_THRESHOLD_PX = 24;

interface ComputeCandidateIndexInput {
  baselineIndex: number;
  dragDistance: number;
  totalCandidates: number;
  dragSpan: number;
}

interface CreatePendingVoteInput {
  lectureId: string;
  slideId: string;
  previousGlitchSlideId: string;
  selectedGlitchSlideId: string;
  startedAtSec: number;
}

export function getBrowseAxis(viewportMode: ViewportMode) {
  return viewportMode === "mobile-portrait" ? "horizontal" : "vertical";
}

export function getBrowseCueLabel(viewportMode: ViewportMode) {
  return getBrowseAxis(viewportMode) === "horizontal"
    ? "Swipe left or right"
    : "Swipe up or down";
}

export function computeCandidateIndex({
  baselineIndex,
  dragDistance,
  totalCandidates,
  dragSpan
}: ComputeCandidateIndexInput) {
  if (totalCandidates <= 1) {
    return 0;
  }

  const stepWidth = Math.max(dragSpan, 120);
  const threshold = stepWidth * 0.25;
  const distance = Math.abs(dragDistance);
  const direction = Math.sign(dragDistance);
  const offset =
    distance < threshold
      ? 0
      : direction * (1 + Math.floor((distance - threshold) / stepWidth));
  const unclampedIndex = baselineIndex + offset;

  return Math.min(totalCandidates - 1, Math.max(0, unclampedIndex));
}

export function hasSelectionChanged(
  baselineGlitchSlideId: string | null,
  selectedGlitchSlideId: string | null
) {
  return Boolean(
    baselineGlitchSlideId &&
      selectedGlitchSlideId &&
      baselineGlitchSlideId !== selectedGlitchSlideId
  );
}

export function createPendingVote({
  lectureId,
  slideId,
  previousGlitchSlideId,
  selectedGlitchSlideId,
  startedAtSec
}: CreatePendingVoteInput): PendingVote {
  return {
    lectureId,
    slideId,
    previousGlitchSlideId,
    selectedGlitchSlideId,
    startedAtSec,
    createdAtIso: new Date().toISOString()
  };
}
