/// <reference lib="dom" />
import { execFileSync } from "node:child_process";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Checks popover text does not select its enclosing pull request row", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("popover-proof");
  execFileSync("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: project });
  await t3.open("/pull-requests?involvement=all&state=open");
  const row = browser.locator("button").filter({ hasText: "#38170" }).first();
  await row.waitFor({ timeout: 60_000 });
  await row.tap();
  await browser.waitForURL(/number=38170/);
  await screen.getByText("Measured on Linux", { exact: false }).first().waitFor();
  await app.screenshot("ordinary-row-selection");
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  const trigger = row.getByRole("button", "Checks: All checks have passed", { exact: true });
  await trigger.click();
  const heading = screen.getByText("All checks have passed", { exact: true });
  await heading.waitFor();
  await browser.locator('[data-slot="popover-popup"]:not([data-starting-style])').waitFor();
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().filter((animation) => animation.effect?.getComputedTiming().iterations !== Infinity).map((animation) => animation.finished.catch(() => {})));
    return null;
  });
  await app.screenshot("checks-open-detail-closed");
  await browser.keyboard.press("Escape");
  await heading.waitFor({ state: "hidden" });
  await trigger.focus();
  await browser.keyboard.press("Enter");
  await heading.waitFor();
  await browser.locator('[data-slot="popover-popup"]:not([data-starting-style])').waitFor();
  await browser.evaluate(async () => {
    await Promise.all(document.getAnimations().filter((animation) => animation.effect?.getComputedTiming().iterations !== Infinity).map((animation) => animation.finished.catch(() => {})));
    return null;
  });
  await app.screenshot("keyboard-reopened-checks");
  const selectedByKeyboard = await browser.evaluate(() => new URL(location.href).searchParams.has("number"));
  await heading.tap();
  await app.screenshot("after-popover-heading-click");
  expect(selectedByKeyboard, "Reopening checks with Enter leaves the PR unselected").toBe(false);
  expect(await browser.evaluate(() => new URL(location.href).searchParams.has("number")), "Clicking checks text leaves the PR unselected").toBe(false);
});
