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

test("A finished bravo checkout leaves alpha's newer checkout dialog open", WEB, async ({ t3, app, browser, screen }) => {
  const alpha = await t3.project("alpha");
  const bravo = await t3.project("bravo");
  for (const [cwd, remote] of [[alpha, "pingdotgg/t3code"], [bravo, "cli/cli"]]) {
    await runPromise(run("git", ["remote", "add", "origin", `https://github.com/${remote}.git`], { cwd }));
  }
  const thread = await t3.thread({ project: alpha, title: "hello alpha", messages: ["Hello"] });
  // Hold only delivery of the real server response; GitHub resolution and git checkout run normally.
  await browser.addInitScript(() => {
    const NativeWebSocket = window.WebSocket;
    window.WebSocket = class extends NativeWebSocket {
      private checkoutId: string | undefined;
      constructor(...args: ConstructorParameters<typeof WebSocket>) {
        super(...args);
        this.addEventListener("message", (event) => {
          if (!this.checkoutId || typeof event.data !== "string") return;
          const reply = [JSON.parse(event.data)].flat().find(frame => frame._tag === "Exit" && String(frame.requestId) === this.checkoutId);
          if (!reply) return;
          this.checkoutId = undefined;
          event.stopImmediatePropagation();
          document.documentElement.dataset.checkoutReply = reply.exit._tag;
          document.addEventListener("release-checkout", () => {
            this.dispatchEvent(new MessageEvent("message", { data: event.data }));
          }, { once: true });
        });
      }
      override send(data: Parameters<WebSocket["send"]>[0]) {
        if (typeof data === "string") {
          const request = [JSON.parse(data)].flat().find(frame => frame.tag === "git.preparePullRequestThread");
          if (request) this.checkoutId = String(request.id);
        }
        super.send(data);
      }
    };
  });
  await t3.open(thread);
  await screen.getByRole("button", "New thread in alpha", { exact: true }).tap();
  const picker = browser.locator("[data-draft-project-trigger]");
  await picker.tap();
  await screen.getByRole("option", "bravo", { exact: true }).tap();
  await picker.filter({ hasText: "bravo" }).waitFor();
  const openCheckout = async (number: number) => {
    await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first().tap();
    await screen.getByPlaceholder("Search refs...").fill(`#${number}`);
    await screen.getByRole("option", /Checkout (?:pull|change) request/i).tap();
    const dialog = screen.getByRole("dialog", /Checkout (?:pull|change) request/i);
    await dialog.getByText(new RegExp(`#${number} ·`)).waitFor();
    return dialog;
  };
  const first = await openCheckout(15192);
  await first.getByRole("button", "Worktree", { exact: true }).tap();
  await browser.locator('html[data-checkout-reply="Success"]').waitFor();
  await app.screenshot("bravo-checkout-pending");
  await browser.evaluate(() => { history.back(); return null; });
  await picker.filter({ hasText: "alpha" }).waitFor();
  const second = await openCheckout(48877);
  await app.screenshot("alpha-dialog-before-old-checkout-finishes");
  await browser.evaluate(() => { document.dispatchEvent(new Event("release-checkout")); return null; });
  // The next screenshot command runs after delivery; allow React's queued work to paint.
  await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 1000)); return null; });
  await app.screenshot("alpha-dialog-after-old-checkout-finishes");
  await expect(second).toBeVisible();
  expect(await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first().getAttribute("aria-label")).toContain("main");
});
