/// <reference lib="dom" />
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 base preserves a branch's trailing U+00A0", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("unicode-base", { "a.txt": "base\n" });
  await runPromise(Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const git = (args: string[]) => run("git", args, { cwd: project });
    const commit = (message: string) => git(["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-am", message]);
    yield* git(["branch", "feat"]);
    yield* fs.writeFileString(`${project}/b.txt`, "b\n");
    yield* git(["add", "b.txt"]);
    yield* commit("add b");
    yield* git(["branch", "feat\u00a0"]);
    yield* fs.writeFileString(`${project}/c.txt`, "c\n");
    yield* git(["add", "c.txt"]);
    yield* commit("add c");
  }));
  const thread = await t3.thread({ project, title: "Unicode base comparison", messages: ["first"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Diff", { exact: true }).tap();
  const picker = () => screen.getByRole("combobox", /Change comparison target/);
  const choose = async (ref: string) => {
    await picker().tap();
    await screen.getByRole("option", "Automatic", { exact: true }).waitFor();
    await browser.evaluate((name) => {
      const option = Array.from(document.querySelectorAll<HTMLElement>('[role="option"]')).find(el => el.textContent === name);
      if (!option) throw new Error(`Missing exact option ${JSON.stringify(name)}`);
      option.click();
    }, ref);
  };
  await choose("feat");
  await screen.getByRole("button", "Expand b.txt").waitFor();
  await choose("Automatic");
  await choose("feat\u00a0");
  await screen.getByRole("button", "Expand c.txt").waitFor();
  await app.screenshot("unicode-base-diff");
  await picker().tap();
  await screen.getByRole("option", "Automatic", { exact: true }).waitFor();
  await app.screenshot("unicode-base-picker");
  const selected = await browser.evaluate(() => Array.from(document.querySelectorAll('[role="option"][aria-selected="true"]'), el => el.textContent));
  await expect(selected).toEqual(["feat\u00a0"]);
  await picker().tap();
  await expect(screen.getByRole("button", "Expand b.txt")).not.toBeVisible();
});
