/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { run } from "./shell.ts";
import { runPromise, test, WEB } from "./t3.ts";

test("An open branch picker finds a branch downloaded by background fetch", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("demo", { "t3.json": '{"defaultThreadEnvMode":"local"}' });
  const git = (cwd: string, ...args: string[]) => runPromise(run("git", args, { cwd }));
  const remote = `${project}/../remote.git`;
  const second = `${project}/../publisher`;
  await git(project, "init", "--bare", remote);
  await git(project, "remote", "add", "origin", remote);
  await git(project, "push", "-u", "origin", "main");
  await git(project, "clone", "--branch", "main", remote, second);
  await browser.setViewport({ width: 1280, height: 800 });
  await browser.addInitScript(() => {
    const refresh = new Set<string>();
    const watched = new WeakSet<WebSocket>();
    const scan = (value: unknown) => {
      if (!value || typeof value !== "object") return;
      const obj = value as Record<string, unknown>;
      if (typeof obj.behindCount === "number") document.documentElement.dataset.behind = String(obj.behindCount);
      for (const child of Object.values(obj)) scan(child);
    };
    const send = WebSocket.prototype.send;
    WebSocket.prototype.send = function(data) {
      if (typeof data === "string") for (const req of [JSON.parse(data)].flat()) {
        if (req?.tag === "vcs.listRefs" && req.payload?.refresh === true) refresh.add(String(req.id));
      }
      if (!watched.has(this)) {
        watched.add(this);
        this.addEventListener("message", event => {
          if (typeof event.data !== "string") return;
          const parsed = JSON.parse(event.data);
          scan(parsed);
          for (const res of [parsed].flat()) if (res?._tag === "Exit" && res.exit?._tag === "Success" && refresh.has(String(res.requestId))) document.documentElement.dataset.refRefresh = "done";
        });
      }
      return send.call(this, data);
    };
  });
  await t3.open();
  await screen.getByRole("button", "New thread in demo", {exact:true}).first().tap();
  await browser.locator('html[data-behind="0"]').waitFor({state:"attached", timeout:60000});
  await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').first().click();
  await screen.getByRole("option", /^main\b/).waitFor();
  await browser.locator('html[data-ref-refresh="done"]').waitFor({state:"attached"});
  await screen.getByPlaceholder("Search refs...").fill("review-target");
  await runPromise(Effect.sleep("1 second"));
  await git(second, "-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", "Remote update");
  await git(second, "push", "origin", "HEAD:main", "HEAD:review-target");
  await browser.locator('html[data-behind="1"]').waitFor({state:"attached", timeout:120000});
  await git(project, "show-ref", "--verify", "refs/remotes/origin/review-target");
  await runPromise(Effect.sleep("20 seconds"));
  await app.screenshot("open-picker-after-background-fetch");
  await expect(screen.getByRole("option", /^origin\/\s*review-target\b/)).toBeVisible();
});
