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

declare global {
  interface Window {
    checkoutHold: { started: Promise<void>; release: () => void; finished: Promise<void> };
  }
}

test("Moving a draft preserves its workspace and releases a waiting send immediately", WEB,
async ({ t3, app, browser, screen }) => {
  const source = await t3.project("hello-world");
  await runPromise(run("git", ["remote", "add", "origin", "https://github.com/octocat/Hello-World.git"], { cwd: source }));
  await runPromise(run("git", ["fetch", "--depth=1", "origin", "master"], { cwd: source }));
  await runPromise(run("git", ["checkout", "-B", "master", "FETCH_HEAD"], { cwd: source }));
  const destination = await t3.project("other-project", { "t3.json": JSON.stringify({ defaultThreadEnvMode: "local" }) });
  await runPromise(run("git", ["branch", "-m", "develop"], { cwd: destination }));
  await browser.addInitScript(() => {
    const started = Promise.withResolvers<void>();
    const released = Promise.withResolvers<void>();
    const finished = Promise.withResolvers<void>();
    window.checkoutHold = { started: started.promise, release: released.resolve, finished: finished.promise };
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      const request = typeof data === "string" ? JSON.parse(data) : null;
      if (request?._tag !== "Request" || request.tag !== "git.preparePullRequestThread") return send.call(this, data);
      started.resolve();
      this.addEventListener("message", function listener(event) {
        const response = JSON.parse(event.data);
        if (response._tag === "Exit" && response.requestId === request.id) {
          finished.resolve();
          this.removeEventListener("message", listener);
        }
      });
      void released.promise.then(() => send.call(this, data));
    };
  });

  const snapshots: Array<{ branch: string | null; workspace: string | null; prompt: string | null }> = [];
  let sendReleased = false;
  let retrySent = false;
  const capture = async (label: string) => {
    // Let transient toast entrance animations finish before retaining a still.
    await browser.evaluate(() => new Promise<null>((resolve) => setTimeout(() => resolve(null), 800)));
    await app.screenshot(label);
  };
  for (const entry of ["handoff", "waiting", "detail"]) {
    const waitingSend = entry === "waiting";
    await t3.open(entry === "detail"
      ? "/pull-requests?repository=octocat%2FHello-World&number=11799&selectedUrl=https%3A%2F%2Fgithub.com%2Foctocat%2FHello-World%2Fpull%2F11799"
      : "/new?pr=octocat/Hello-World/11799");
    if (entry === "detail") {
      await screen.getByRole("button", "Check out", { exact: true }).waitFor();
      await capture("detail-panel-entry");
    }
    await screen.getByRole("button", "Check out", { exact: true }).tap();
    if (entry === "detail") await screen.getByRole("menuitem", "In a separate worktree", { exact: false }).tap();
    await browser.evaluate(async () => { await window.checkoutHold.started; return null; });
    const composer = screen.getByRole("textbox");
    const prompt = waitingSend ? "Explain the pull request changes after reviewing the moved draft" : "Explain the pull request changes";
    await composer.fill(prompt);
    if (waitingSend) {
      await browser.locator("[data-chat-provider-model-picker-label]").first().tap();
      await browser.keyboard.type("Command output");
      await browser.keyboard.press("Enter");
      await browser.keyboard.press("Escape");
      await composer.press("Enter");
    }
    await browser.locator("[data-draft-project-trigger]").tap();
    await screen.getByRole("option", "other-project", { exact: true }).tap();
    await browser.locator("[data-draft-project-trigger]").filter({ hasText: "other-project" }).waitFor();
    if (waitingSend) {
      // Inspect the actual composer while the original checkout request is still held.
      await capture("waiting-send-after-moving-before-checkout-finishes");
      sendReleased = await browser.evaluate(() => document.body.innerText.includes("Draft changed while preparing this message. Review it and send again."));
      await composer.press("Enter");
      // A normal retry reaches the real replay provider before the held checkout is released.
      if (sendReleased) await screen.getByText(prompt, { exact: true }).first().waitFor();
      await capture("retry-before-original-checkout-finishes");
      retrySent = await browser.evaluate((text) => {
        const composer = document.querySelector('[contenteditable="true"]');
        return document.body.innerText.includes(text) && !composer?.textContent?.includes(text);
      }, prompt);
    }
    await browser.evaluate(async () => { window.checkoutHold.release(); await window.checkoutHold.finished; return null; });
    await screen.getByRole("dialog", "Preparing the pull request checkout...").waitFor({ state: "hidden" });
    await capture(waitingSend ? "waiting-send-after-checkout" : entry === "detail" ? "detail-panel-moved-draft-after-checkout" : "moved-draft-after-checkout");
    if (!waitingSend) snapshots.push(await browser.evaluate(() => ({
      branch: document.querySelector('[data-slot="combobox-trigger"][aria-label^="Branch:"]')?.getAttribute("aria-label") ?? null,
      workspace: document.querySelector('[data-composer-shortcut="composer.workspace"]')?.textContent ?? null,
      prompt: document.querySelector('[contenteditable="true"]')?.textContent ?? null,
    })));
  }
  for (const snapshot of snapshots) {
    expect(snapshot.branch).toBe("Branch: develop");
    expect(snapshot.workspace).toContain("Current checkout");
    expect(snapshot.prompt).toContain("Explain the pull request changes");
  }
  expect(sendReleased, "Moving the draft aborts the waiting send before checkout finishes").toBe(true);
  expect(retrySent, "The reviewed draft can be sent immediately while the original checkout is still held").toBe(true);
});
