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

test("Escape dismissing checkout prevents the late draft and prompt handoff", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("checkout-demo");
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/pingdotgg/t3code.git"], { cwd: project }));
  await runPromise(run("git", ["fetch", APP_DIR, "refs/remotes/origin/main:refs/remotes/origin/main"], { cwd: project }));
  await runPromise(run("git", ["reset", "--hard", "origin/main"], { cwd: project }));
  await browser.addInitScript(() => {
    const starts = new WeakMap<WebSocket, string>();
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string" && /^[{\[]/.test(data)) for (const request of [JSON.parse(data)].flat()) {
        if (request?._tag === "Request" && request.tag === "git.preparePullRequestThread") starts.set(this, String(request.id));
      }
      return send.call(this, data);
    };
    const listen = WebSocket.prototype.addEventListener;
    WebSocket.prototype.addEventListener = function(this: WebSocket, type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions) {
      if (type !== "message" || typeof listener !== "function") return listen.call(this, type, listener, options);
      return listen.call(this, type, (event: Event) => {
        const data = (event as MessageEvent).data;
        const wire = typeof data === "string" && /^[{\[]/.test(data) ? [JSON.parse(data)].flat() : [];
        if (wire.some(message => message?._tag === "Exit" && String(message.requestId) === starts.get(this))) {
          document.documentElement.dataset.checkoutReply = JSON.stringify(wire);
          document.addEventListener("release-checkout", () => listener.call(this, event), { once: true });
        } else listener.call(this, event);
      }, options);
    } as typeof WebSocket.prototype.addEventListener;
  });
  await t3.open("/new?pr=https://github.com/pingdotgg/t3code/pull/46628&prompt=REPRO-ESCAPE-PROMPT%20check%20this%20pull%20request");
  await screen.getByRole("button", "Check out", { exact: true }).tap();
  const toast = screen.getByRole("dialog", "Preparing the pull request checkout...");
  await toast.waitFor();
  await toast.press("Escape");
  await toast.waitFor({state: "hidden"});
  await app.screenshot("dismissed-before-checkout-finishes");
  await browser.locator("html[data-checkout-reply]").waitFor({timeout: 180_000});
  await browser.evaluate(() => {
    const wire = JSON.parse(document.documentElement.dataset.checkoutReply!);
    if (!wire.some((frame: {exit?: {_tag?: string}}) => frame.exit?._tag === "Success")) throw new Error("Real checkout failed: " + JSON.stringify(wire));
    document.dispatchEvent(new Event("release-checkout"));
    return null;
  });
  // Let the real completion propagate through the draft stores before capturing both sides.
  await browser.evaluate(() => new Promise<null>(resolve => setTimeout(() => resolve(null), 1500)));
  await app.screenshot("draft-after-dismissed-checkout-completes");
  const promptAfterEscape = await screen.getByTestId("composer-editor").textContent();
  const worktreeAfterEscape = await screen.getByText("Current worktree", {exact: true}).first().isVisible();

  await t3.open("/pull-requests?repository=pingdotgg%2Ft3code&number=36927&selectedUrl=https%3A%2F%2Fgithub.com%2Fpingdotgg%2Ft3code%2Fpull%2F36927");
  await screen.getByRole("button", "Check out", {exact: true}).tap();
  await screen.getByRole("menuitem", /In a separate worktree/).tap();
  const detailToast = screen.getByRole("dialog", "Preparing the pull request checkout...");
  await detailToast.waitFor();
  await detailToast.getByRole("button", "Dismiss notification").tap();
  await detailToast.waitFor({state: "hidden"});
  await app.screenshot("detail-dismissed-before-checkout-finishes");
  await browser.locator("html[data-checkout-reply]").waitFor({timeout: 180_000});
  await browser.evaluate(() => {
    const wire = JSON.parse(document.documentElement.dataset.checkoutReply!);
    if (!wire.some((frame: {exit?: {_tag?: string}}) => frame.exit?._tag === "Success")) throw new Error("Real detail checkout failed: " + JSON.stringify(wire));
    document.dispatchEvent(new Event("release-checkout"));
    return null;
  });
  await browser.evaluate(() => new Promise<null>(resolve => setTimeout(() => resolve(null), 1500)));
  await app.screenshot("detail-draft-after-dismissed-checkout-completes");
  const worktreeAfterDetailDismiss = await screen.getByText("Current worktree", {exact: true}).first().isVisible();
  expect(promptAfterEscape, "Escape dismissal keeps the task prompt out of the composer").not.toContain("REPRO-ESCAPE-PROMPT");
  expect(worktreeAfterEscape, "Escape dismissal keeps the draft in the current checkout").toBe(false);
  expect(worktreeAfterDetailDismiss, "Detail dismiss button keeps the draft in the current checkout").toBe(false);
});
