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

test("A different comparison prompt starts after a rejected base branch", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo");
  await runPromise(run("git", ["branch", "feature"], { cwd: project }));
  const seed = await t3.thread({ project, title: "Setup", messages: ["Start"] });
  await t3.open(seed);
  await screen.getByRole("button", "New thread in demo", { exact: true }).tap();
  await browser.locator("[data-chat-provider-model-picker]").tap();
  await screen.getByPlaceholder("Search models...").fill("Multi turn");
  await browser.keyboard.down("Shift");
  await screen.getByRole("option", /^Multi turn/).tap();
  await browser.keyboard.up("Shift");
  await browser.keyboard.press("Escape");
  const branch = browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first();
  await branch.click();
  await screen.getByRole("option", /^feature\b/).tap();
  await runPromise(run("git", ["branch", "-D", "feature"], { cwd: project }));
  const composer = screen.getByRole("textbox");
  await composer.fill("First comparison");
  await composer.press("Enter");
  await screen.getByText(/Base ref "feature" does not resolve/).first().waitFor();
  const capture = async (label: string) => {
    const notification = screen.getByText(/A background prompt could not be sent|Started 2 threads in background/);
    if (await notification.count()) await notification.last().hover();
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().filter((animation) => animation.effect?.getComputedTiming().iterations !== Infinity).map((animation) => animation.finished.catch(() => undefined)));
      return null;
    });
    await app.screenshot(label);
  };
  await screen.getByRole("button", "Restore prompt", { exact: true }).waitFor();
  await browser.evaluate(() => {
    document.querySelectorAll<HTMLButtonElement>('[data-slot="toast-close"]').forEach((button) => button.click());
    return null;
  });
  await screen.getByText(/Base ref "feature" does not resolve/).first().waitFor({ state: "hidden" });
  await branch.click();
  await screen.getByRole("option", /^main\b/).tap();
  await composer.fill("Second comparison");
  await composer.press("Enter");
  // Both outcomes produce a toast after all selected model launches settle.
  await screen.getByText(/Started 2 threads|previous request may have started/).first().waitFor();
  const threads = screen.getByRole("button", /^Second comparison(?:,|$)/);
  if (await screen.getByText("Started 2 threads in background", { exact: true }).count()) {
    await threads.nth(1).waitFor();
  }
  await capture("second-comparison-result");
  await expect.poll(() => threads.count()).toBe(2);
});
