import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";

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

test(
  "Changes follows a branch checkout in the same folder",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo");
    await t3.open("/settings/appearance");
    await screen.getByRole("button", /^Thread details: \d+ of \d+ on$/).tap();
    const changesSummary = screen.getByRole("menuitemcheckbox", "Changes", { exact: true });
    await changesSummary.tap();
    await browser.keyboard.press("Escape");
    const git = (...args: string[]) => run("git", args, { cwd: project });
    await runPromise(
      Effect.gen(function* () {
        const fs = yield* FileSystem.FileSystem;
        for (const branch of ["first-topic", "second-topic"]) {
          yield* git("switch", "-c", branch, "main");
          yield* fs.writeFileString(`${project}/${branch}.txt`, `${branch} change\n`);
          yield* git("add", `${branch}.txt`);
          yield* git(
            "-c",
            "user.name=Scenario",
            "-c",
            "user.email=scenario@example.invalid",
            "commit",
            "-m",
            branch,
          );
        }
        yield* git("switch", "first-topic");
      }),
    );
    const thread = await t3.thread({ project, title: "Switch branches", messages: ["first"] });

    await t3.open(thread);
    await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
    await screen.getByText("Diff", { exact: true }).tap();
    await screen.getByRole("combobox", /^Change comparison target/).tap();
    await screen.getByRole("option", "main", { exact: true }).tap();
    await screen.getByRole("button", /^(Expand|Collapse) first-topic\.txt$/).waitFor();

    await screen.getByRole("button", "Toggle thread details panel", { exact: true }).tap();
    const branch = browser
      .locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible')
      .first();
    await branch.tap();
    await screen.getByRole("option", "second-topic", { exact: true }).tap();
    // The picker stays disabled until the checkout returns, so Git has switched once it is enabled.
    await expect(branch.filter({ hasText: "second-topic" })).toBeEnabled();
    // Setup, not the assertion: a checkout Git never made must not read as the stale-diff bug.
    const current = await runPromise(git("branch", "--show-current"));
    if (current.stdout.trim() !== "second-topic") {
      throw new ScenarioError({ message: "Git did not check out second-topic" });
    }

    await app.screenshot("changes-after-checking-out-second-topic");
    await expect(screen.getByRole("button", /^(Expand|Collapse) second-topic\.txt$/)).toBeVisible();
  },
);
