import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import { test, WEB } from "./t3.ts";

test("Branch pickers name the current branch after switching projects A to B to A", WEB,
  async ({ t3, app, screen, browser }) => {
    const repoA = await t3.project("repoA");
    const repoB = await t3.project("repoB");
    execFileSync("git", ["branch", "-m", "master"], { cwd: repoA });
    execFileSync("git", ["branch", "-m", "t3/fix-slider-action-touch-lag"], { cwd: repoB });
    await t3.open();
    const observed: Array<string | null> = [];
    for (const [project, branch, label] of [
      ["repoA", "master", "repoA-first"],
      ["repoB", "t3/fix-slider-action-touch-lag", "repoB-long-branch"],
      ["repoA", "master", "repoA-return"],
    ]) {
      await screen.getByRole("button", "New thread", { exact: true }).tap();
      await screen.getByRole("option").filter({ hasText: project }).first().tap();
      const toggle = screen.getByRole("button", "Toggle thread details panel");
      if (!(await screen.getByRole("region", "Version Control").isVisible())) await toggle.tap();
      const picker = screen.getByRole("region", "Version Control").getByRole("combobox");
      await picker.waitFor({ state: "visible" });
      // Readiness only: wait for the actual branch query, without asserting the bug away.
      await browser.locator('[role="combobox"]').filter({ hasText: branch }).first().waitFor({ state: "visible" });
      observed.push(await picker.getAttribute("aria-label"));
      await browser.evaluate(() => {
        document.getElementById("branch-evidence")?.remove();
        const region = document.querySelector('section[aria-label="Version Control"]');
        const picker = region?.querySelector('[role="combobox"]');
        const panel = document.createElement("pre");
        panel.id = "branch-evidence";
        panel.style.cssText = "position:fixed;left:270px;bottom:120px;z-index:99999;padding:16px;background:#fff;color:#111;border:2px solid #555;font:14px/1.6 monospace;max-width:650px;white-space:pre-wrap";
        panel.textContent = "Browser DOM inspection — thread details branch picker\n" +
          "role: " + picker?.getAttribute("role") + "\n" +
          "aria-label: " + JSON.stringify(picker?.getAttribute("aria-label")) + "\n" +
          "visible text: " + picker?.textContent;
        document.body.append(panel);
      });
      await browser.evaluate(async () => {
        await Promise.all(document.getAnimations().filter((animation) =>
          animation.effect?.getComputedTiming().iterations !== Infinity
        ).map((animation) => animation.finished.catch(() => {})));
      });
      await app.screenshot(label);
    }
    expect(observed).toEqual(["Branch: master", "Branch: t3/fix-slider-action-touch-lag", "Branch: master"]);
    await expect(screen.getByRole("region", "Version Control").getByRole("combobox")).toHaveAccessibleName("Branch: master");
  });
