import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Diff comparison refs follow the search query", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("repo", { "a.txt": "" });
  await runPromise(run("git", ["branch", "feature-x"], { cwd: project }));
  await runPromise(run("git", ["checkout", "-b", "work"], { cwd: project }));
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.writeFileString(`${project}/a.txt`, "one line\n");
  }));
  const thread = await t3.thread({ project, title: "go", messages: ["first"] });
  await browser.setViewport({ width: 1280, height: 800 });
  await t3.open(thread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Diff", { exact: true }).tap();
  await screen.getByRole("combobox", /Change comparison target/).tap();
  await screen.getByRole("option", "feature-x", { exact: true }).waitFor();
  await screen.getByRole("option", "main", { exact: true }).tap();
  await screen.getByRole("combobox", /Change comparison target/).tap();
  await app.screenshot("empty-query");
  const search = screen.getByPlaceholder("Search refs...");
  const options = browser.locator('[role="option"]:visible');
  await search.fill("zzz-no-match");
  await screen.getByText("No matching refs.", { exact: true }).waitFor();
  await app.screenshot("unmatched-query");
  const unmatchedCount = await options.count();
  await search.fill("main");
  await screen.getByRole("option", "main", { exact: true }).waitFor();
  await app.screenshot("matching-query");
  const matchingCount = await options.count();
  const automaticForMain = await browser.locator('[role="option"]:visible').filter({ hasText: "Automatic" }).count();
  await search.fill("");
  await screen.getByRole("option", "feature-x", { exact: true }).waitFor();
  await app.screenshot("cleared-query");
  const clearedCount = await options.count();
  await expect(unmatchedCount).toBe(0);
  await expect(matchingCount).toBe(1);
  await expect(automaticForMain).toBe(0);
  await expect(clearedCount).toBe(3);
});
