import { expect, test, type Page } from './fixtures';

// The edge swipe-back gesture (components/Screen.svelte) against the mock transport.
// Real multi-touch pinch is not reproducible in Playwright, so this drives the handler
// directly with synthetic PointerEvents (it listens at the window in the capture phase):
// a lone finger swiping right from the left edge navigates back; a two-finger gesture
// (a pinch-zoom, whose release would otherwise read as a swipe) does not.

async function loginLobby(page: Page): Promise<void> {
  await page.goto('/');
  await page.getByRole('button', { name: /guest/i }).click();
  await expect(page.getByText('Your turn')).toBeVisible();
}

function pointer(page: Page, type: string, x: number, y: number, id: number): Promise<void> {
  return page.evaluate(
    ({ type, x, y, id }) => {
      window.dispatchEvent(
        new PointerEvent(type, { clientX: x, clientY: y, pointerId: id, pointerType: 'touch', bubbles: true, cancelable: true }),
      );
    },
    { type, x, y, id },
  );
}

test('edge swipe-back: a lone finger navigates back, a pinch does not', async ({ page }) => {
  await loginLobby(page);

  // Open the Settings hub (back = lobby).
  await page.getByRole('button', { name: /Settings/ }).click();
  await expect(page.getByText('Your turn')).toBeHidden();

  // A two-finger gesture from the left edge is a pinch (its second finger joins after the
  // first): releasing it must NOT navigate back — we stay on Settings.
  await pointer(page, 'pointerdown', 8, 300, 1);
  await pointer(page, 'pointerdown', 60, 300, 2);
  await pointer(page, 'pointerup', 260, 300, 1);
  await pointer(page, 'pointerup', 90, 300, 2);
  await expect(page.getByText('Your turn')).toBeHidden();

  // A single finger swiping right from the left edge does return to the lobby.
  await pointer(page, 'pointerdown', 8, 300, 1);
  await pointer(page, 'pointerup', 260, 300, 1);
  await expect(page.getByText('Your turn')).toBeVisible();
});
