import * as fs 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("Detached HEAD exclusions reset on a named branch", IOS, async ({ t3, app, screen }) => {
  const project = await t3.project("Commit selection", { "include.ts": "export const include = 1;\n", "later.ts": "export const later = 1;\n" });
  const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
  await git("checkout", "--detach");
  await fs.writeFile(`${project}/include.ts`, "export const include = 2;\n");
  await fs.writeFile(`${project}/later.ts`, "export const later = 2;\n");
  await fs.writeFile(`${project}/.git/hooks/pre-commit`, "#!/bin/sh\nexit 1\n", { mode: 0o755 });
  await t3.thread({ project, title: "Commit selection", messages: ["Reply with just OK"] });
  await app.clearState().catch(() => {});
  await t3.open();
  await screen.getByText("Commit selection", { exact: false }).first().tap({ timeout: 120_000 });
  const openCommit = async () => {
    await screen.getByRole("button", "Git controls").tap({ timeout: 60_000 });
    await screen.getByText("More", { exact: true }).tap();
    await screen.getByText("Commit", { exact: true }).tap();
    await screen.getByRole("checkbox", "later.ts").waitFor();
  };
  await openCommit();
  await screen.getByRole("checkbox", "later.ts").tap();
  await screen.getByRole("textbox", "Commit message").fill("repro commit");
  await screen.getByRole("button", "Commit changes", { exact: true }).tap();
  await screen.getByRole("button", "Git controls").waitFor();
  await openCommit();
  await app.screenshot("same-detached-head-retry");
  await screen.getByRole("button", "Cancel commit").tap();
  await git("switch", "-c", "feature");
  await screen.getByRole("button", "Git controls").tap();
  await screen.getByText("feature", { exact: false }).first().waitFor({ timeout: 30_000 });
  await screen.getByText("More", { exact: true }).tap();
  await screen.getByText("Commit", { exact: true }).tap();
  await screen.getByRole("checkbox", "later.ts").waitFor();
  await app.screenshot("named-branch-selection");
  await expect(screen.getByText("2 of 2 selected", { exact: false })).toBeVisible();
});
