import { readFile, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { run } from "./shell.ts";
import { runPromise } from "./t3.ts";
import { IOS, test } from "./t3-mobile.ts";

test("Mobile worktree creation keeps the selected NBSP base ref", IOS, async ({ t3, app, screen }) => {
  const project = await t3.project("exact-base", { f: "base\n" });
  const git = async (...args: string[]) => (await runPromise(run("git", args, { cwd: project }))).stdout.trim();
  const commit = async (message: string) => {
    await git("add", "f");
    await git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", message);
  };
  await git("checkout", "-b", "release");
  await writeFile(`${project}/f`, "plain\n");
  await commit("plain release commit");
  await git("checkout", "main");
  await git("checkout", "-b", "release\u00a0");
  await writeFile(`${project}/f`, "nbsp\n");
  await commit("NBSP release commit");
  const wanted = await git("rev-parse", "HEAD");
  await t3.thread({ project, title: "Exact base worktree", messages: ["ready"] });
  await t3.open();
  await screen.getByText("Exact base worktree", { exact: false }).first().tap({ timeout: 240_000 });
  await screen.getByRole("button", "Git controls").tap();
  await screen.getByText("More", { exact: true }).tap();
  await screen.getByText("Branches & worktrees", { exact: true }).tap();
  await screen.getByLabel("Worktree branch name").fill("feature/new-worktree");
  await app.screenshot("selected-base-before-create");
  await screen.getByRole("button", "Create worktree").tap();
  // Opening the Git controls after creation also waits for navigation back to the thread.
  await screen.getByRole("button", "Git controls").tap({ timeout: 60_000 });
  await screen.getByText("More", { exact: true }).tap();
  await app.screenshot("created-worktree");
  const list = await git("worktree", "list", "--porcelain");
  const created = list.split("\n\n").find((block) => block.includes("branch refs/heads/feature/new-worktree"));
  const folder = created?.split("\n").find((line) => line.startsWith("worktree "))?.slice(9);
  const actual = created?.split("\n").find((line) => line.startsWith("HEAD "))?.slice(5);
  const contents = folder ? await readFile(`${folder}/f`, "utf8") : "worktree missing";
  expect({ head: actual, contents }).toEqual({ head: wanted, contents: "nbsp\n" });
});
