import type { TouchEvent } from "react";
import { createTouchCanvasPointerEvent, createTouchMouseDownEvent } from "./timelineTouchAdapters.js";
import { getTouchPoint, resolveTouchDragDecision } from "./timelineTouch.js";

type MutableCurrent<T> = { current: T };
type TouchDecisionState = { x: number; y: number; decided: boolean };

export function forwardTouchStartAsMouseDown<TCurrentTarget, TOptions>({
  event,
  touchStartRef,
  decided,
  onMouseDown,
  opts,
}: {
  event: TouchEvent<TCurrentTarget>;
  touchStartRef: MutableCurrent<TouchDecisionState>;
  decided: boolean;
  onMouseDown: (event: ReturnType<typeof createTouchMouseDownEvent>, opts: TOptions) => void;
  opts: TOptions;
}) {
  event.preventDefault();
  const point = getTouchPoint(event);
  touchStartRef.current = { x: point.clientX, y: point.clientY, decided };
  onMouseDown(createTouchMouseDownEvent(point, event.currentTarget), opts);
}

export function forwardCanvasTouchMove<TCurrentTarget>({
  event,
  touchStartRef,
  onCanvasMouseMove,
}: {
  event: TouchEvent<TCurrentTarget>;
  touchStartRef: MutableCurrent<TouchDecisionState>;
  onCanvasMouseMove: (event: ReturnType<typeof createTouchCanvasPointerEvent>) => void;
}) {
  const point = getTouchPoint(event);
  const decision = resolveTouchDragDecision(touchStartRef.current, point);
  touchStartRef.current = decision.nextState;
  if (!decision.shouldHandleDrag) return;
  onCanvasMouseMove(createTouchCanvasPointerEvent(point));
}

export function forwardCanvasTouchEnd<TCurrentTarget>({
  event,
  onCanvasMouseUp,
}: {
  event: TouchEvent<TCurrentTarget>;
  onCanvasMouseUp: (event: ReturnType<typeof createTouchCanvasPointerEvent>) => Promise<void> | void;
}) {
  return onCanvasMouseUp(createTouchCanvasPointerEvent(getTouchPoint(event)));
}
