import { expect } from "e2e";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("Branch creation and exact queries preserve Unicode edge whitespace", WEB, async ({ t3, app, browser, screen }) => {
  const name = "\u00a0topic\u3000";
  const project = await t3.project("unicode-branches");
  const thread = await t3.thread({ project, title: "Unicode branch names", messages: ["first"] });
  await t3.open(thread);
  const picker = browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first();
  await picker.click();
  const search = screen.getByPlaceholder("Search refs...");
  await search.fill(name);
  const create = screen.getByRole("option", /Create new ref/);
  await create.waitFor();
  await app.screenshot("unicode-name-create-option");
  await create.tap();
  await search.waitFor({ state: "hidden" });
  await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"][aria-label*="topic"]:visible').first().waitFor();
  const git = (args: string[]) => runPromise(run("git", args, { cwd: project }));
  // Read Git's actual name, removing only the command's newline.
  const created = (await git(["symbolic-ref", "--short", "HEAD"])).stdout.replace(/\n$/, "");
  await app.screenshot("created-branch");
  await git(["branch", name]).catch(() => undefined);
  await git(["branch", "topic"]).catch(() => undefined);
  await git(["branch", "\u00a0other\u3000"]);
  await picker.click();
  await search.fill(name);
  await screen.getByRole("option", /topic/).first().waitFor();
  await app.screenshot("exact-unicode-query");
  const options = await browser.evaluate(() => Array.from(document.querySelectorAll('[role="option"]')).map(el => el.textContent));
  await expect({ created, matches: options.length }).toEqual({ created: name, matches: 1 });
});
