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

test("Scheduled task base preserves Unicode whitespace", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Unicode branches");
  for (const branch of ["feat\u00a0", "\u00a0"]) {
    await runPromise(run("git", ["branch", branch], { cwd: project }));
  }
  await t3.thread({ project, title: "Branch preservation", messages: ["first"] });
  await t3.open("/settings/scheduled-tasks");
  await screen.getByRole("button", "New task", { exact: true }).tap();
  await browser.locator("#scheduled-task-title").fill("Unicode branch task");
  await browser.locator("#scheduled-task-workspace").tap();
  await screen.getByRole("option", "Create a new worktree", { exact: true }).tap();
  await browser.locator("#scheduled-task-base-ref").tap();
  await browser.locator('[role="option"] [title="feat\u00a0"]').tap();
  await browser.locator("#scheduled-task-prompt").fill("Check the selected branch.");
  await screen.getByRole("button", "Every interval", { exact: true }).tap();
  await screen.getByRole("switch", "Enabled", { exact: true }).tap();
  await screen.getByRole("button", "Create task", { exact: true }).tap();
  await screen.getByRole("button", "Actions for Unicode branch task", { exact: true }).tap();
  await screen.getByRole("menuitem", "Edit", { exact: true }).tap();
  const featLabel = await browser.evaluate(() => document.querySelector('#scheduled-task-base-ref [title]')?.getAttribute('title'));
  await app.screenshot("saved-feat-base");
  await browser.locator("#scheduled-task-base-ref").tap();
  await browser.locator('[role="option"] [title="\u00a0"]').tap();
  await screen.getByRole("button", "Save task", { exact: true }).tap();
  await screen.getByRole("button", "Actions for Unicode branch task", { exact: true }).tap();
  await screen.getByRole("menuitem", "Edit", { exact: true }).tap();
  const whitespaceLabel = await browser.evaluate(() => document.querySelector('#scheduled-task-base-ref [title]')?.getAttribute('title'));
  await app.screenshot("saved-whitespace-only-base");
  expect(featLabel).toMatch(/^From feat\u00a0(?: \(remote\))?$/);
  expect(whitespaceLabel).toMatch(/^From \u00a0(?: \(remote\))?$/);
});
