/// <reference lib="dom" />
import { writeFile } from "node:fs/promises";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { runPromise, test, WEB } from "./t3.ts";

test("Returning to cold-loaded Changes shows an external edit on first focus", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("demo", {"notes.txt": "original note\n"});
  const thread = await t3.thread({project, title: "Changes focus", messages: ["first"], model: "default"});
  await browser.setViewport({width: 1440, height: 900});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Add panel surface").tap();
  await screen.getByRole("menuitem", "Diff D", {exact: true}).tap();
  await screen.getByText("No net changes in this selection.", {exact: true}).waitFor();
  await browser.evaluate(() => location.reload());
  await screen.getByText("No net changes in this selection.", {exact: true}).waitFor();
  // The real preview must be older than the ten-second arrival floor.
  await runPromise(Effect.sleep("12 seconds"));
  await writeFile(`${project}/notes.txt`, "externally edited note\n");
  await browser.evaluate(() => window.dispatchEvent(new Event("focus")));
  await runPromise(Effect.sleep("2 seconds"));
  await app.screenshot("changes-after-first-focus");
  await expect(screen.getByText("notes.txt", {exact: true}).first()).toBeVisible({timeout: 3000});
});
