/// <reference lib="dom" />
import { expect } from "e2e";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Editing a failed pull request reference clears its stale resolution error", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("pr-resolution", { "t3.json": JSON.stringify({ defaultThreadEnvMode: "local" }) });
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: project }));
  await browser.setViewport({ width: 1280, height: 800 });
  await t3.open("/");
  await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first().click();
  await screen.getByPlaceholder("Search refs...").fill("#99999");
  await screen.getByRole("option", /Checkout (?:pull|change) request/i).tap();
  const dialog = screen.getByRole("dialog", /Checkout (?:pull|change) request/i);
  const error = dialog.getByText(/Pull request not found/);
  await error.waitFor({ timeout: 60000 });
  await app.screenshot("failed-reference");
  // Keep editing inside the debounce window, as in the reported slow-typing reproduction.
  const edits = async () => {
    for (const reference of ["#4", "#45", "#450", "#4509", "#45095", "#4509", "#45095", "#4509", "#45095"]) {
      await dialog.getByRole("textbox").fill(reference);
      await new Promise(resolve => setTimeout(resolve, 200));
    }
  };
  const editing = edits();
  await dialog.getByText("Resolving pull request...", { exact: true }).waitFor();
  await app.screenshot("editing-reference");
  const staleVisible = await error.isVisible();
  await editing;
  await dialog.getByText("fix(web): clear stale pull request resolution error when editing input", { exact: true }).waitFor({ timeout: 60000 });
  await app.screenshot("resolved-reference");
  await dialog.getByRole("textbox").fill("#99999");
  await error.waitFor({ timeout: 60000 });
  await app.screenshot("current-reference-error");
  expect(staleVisible, "Editing a reference shows the resolving indicator without the previous reference's error").toBe(false);
});
