import { Locator } from "@playwright/test";

const SWIPE_STEPS = 10;

/**
 * Swipe a bottom sheet vertically by `deltaY` pixels.
 * Negative values swipe up (expand), positive values swipe down (dismiss).
 */
export default async function swipeBottomSheet(
  bottomSheet: Locator,
  deltaY: number,
): Promise<void> {
  const content = bottomSheet.getByTestId("BottomSheetContent");
  const box = await content.boundingBox();
  if (!box) throw new Error("BottomSheetContent not found");

  const x = box.x + box.width / 2;
  const startY = box.y + 20;
  const endY = startY + deltaY;

  const touch = (clientY: number) => [{ clientX: x, clientY, identifier: 0 }];

  await content.dispatchEvent("touchstart", {
    bubbles: true,
    cancelable: true,
    touches: touch(startY),
    targetTouches: touch(startY),
    changedTouches: touch(startY),
  });

  for (let i = 1; i <= SWIPE_STEPS; i++) {
    const y = startY + (deltaY * i) / SWIPE_STEPS;
    await content.dispatchEvent("touchmove", {
      bubbles: true,
      cancelable: true,
      touches: touch(y),
      targetTouches: touch(y),
      changedTouches: touch(y),
    });
  }

  await content.dispatchEvent("touchend", {
    bubbles: true,
    cancelable: true,
    touches: [],
    targetTouches: [],
    changedTouches: touch(endY),
  });
}
