import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

test("A new repository in ..cache immediately permits its own branch switch", WEB, async ({ t3, app, browser, screen }) => {
  const outer = await t3.project("outer", { "..cache/sub/file.txt": "nested\n", "cache/sub/file.txt": "control\n" });
  const git = (cwd: string, ...args: string[]) => runPromise(run("git", args, { cwd }));
  await git(outer, "branch", "-m", "outer-branch");
  await git(outer, "branch", "outer-alt");
  const cli = makeState(T3_HOME).cli;
  for (const folder of ["..cache", "cache"]) {
    await runPromise(cli(["project", "add", `${outer}/${folder}/sub`, "--title", folder === "..cache" ? "nested-dotdot" : "nested-control"]));
  }
  await t3.thread({ project: outer, title: "busy outer", messages: ["Ask me something"], model: "question" });
  const nested = await t3.thread({ project: `${outer}/..cache/sub`, title: "nested repository", messages: ["Showcase"], model: "showcase" });
  const control = await t3.thread({ project: `${outer}/cache/sub`, title: "control repository", messages: ["Showcase"], model: "showcase" });
  await browser.setViewport({ width: 1280, height: 900 });
  const picker = () => browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first();
  const switchTo = async (branch: string) => {
    await picker().click();
    await screen.getByRole("option", new RegExp(`^${branch}\\b`)).click();
  };
  for (const thread of [nested, control]) {
    await t3.open(thread);
    await switchTo("outer-alt");
    await screen.getByText(/still working in this checkout/).first().waitFor();
  }
  for (const folder of ["..cache", "cache"]) {
    const cwd = `${outer}/${folder}`;
    await git(cwd, "init", "-b", "inner-main");
    await git(cwd, "add", ".");
    await git(cwd, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Inner repository");
    await git(cwd, "branch", "inner-alt");
  }
  // Forced ref snapshots coalesce for five seconds after opening the picker.
  await runPromise(Effect.sleep("6 seconds"));
  await t3.open(control);
  await switchTo("inner-alt");
  await browser.locator('[aria-label="Branch: inner-alt"]').first().waitFor();
  await t3.open(nested);
  await switchTo("inner-alt");
  await browser.locator('[aria-label="Branch: inner-alt"], [data-slot="toast-description"]:has-text("still working in this checkout")').first().waitFor();
  // Capture both outcomes before asserting: a blocked switch leaves inner-main and a busy-checkout error.
  // Let the toast entry animation finish so its full error is readable in the capture.
  await runPromise(Effect.sleep("1 second"));
  await app.screenshot("nested-repository-branch-switch");
  await expect(picker()).toHaveAttribute("aria-label", "Branch: inner-alt");
});
