import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("A reopened pairing dialog survives the first link completing", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("Pairing demo");
  await t3.open("/settings/access");
  let release!: () => void;
  const held = new Promise<void>((resolve) => { release = resolve; });
  await browser.route(/\/api\/auth\/pairing-token$/, async (route) => {
    await held;
    await route.continue();
  });
  await screen.getByRole("button", "Create link", { exact: true }).tap();
  await screen.getByRole("textbox").fill("Waiting tablet");
  await screen.getByRole("dialog", "Create pairing link", { exact: true }).getByRole("button", "Create link", { exact: true }).tap();
  await screen.getByRole("button", "Creating…", { exact: true }).waitFor();
  await browser.keyboard.press("Escape");
  await screen.getByRole("dialog", "Create pairing link", { exact: true }).waitFor({ state: "hidden" });
  await screen.getByRole("button", "Create link", { exact: true }).tap();
  await screen.getByRole("dialog", "Create pairing link", { exact: true }).waitFor();
  // Hold the network until the reopened popup has painted and the recording shows it.
  await browser.evaluate(() => new Promise((resolve) => setTimeout(resolve, 1500)));
  await app.screenshot("reopened-before-completion");
  release();
  await screen.getByText("Waiting tablet", { exact: true }).waitFor();
  await browser.evaluate(() => new Promise((resolve) => setTimeout(resolve, 1500)));
  await app.screenshot("after-first-link-finishes");
  await expect(screen.getByRole("dialog", "Create pairing link", { exact: true })).toBeVisible();
});
