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

test("File preview refresh shows external edits that collide under the old hash", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("preview-demo", { "sample.js": "console.log('c475b532');\n" });
  const thread = await t3.thread({ project, title: "Inspect sample.js", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByText("fixture turn complete", { exact: false }).waitFor();
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  await screen.getByRole("treeitem", "sample.js", { exact: true }).tap();
  const editorText = () => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const content = host.shadowRoot?.querySelector("[data-content]");
      if (content) return content.textContent ?? "";
    }
    return null;
  });
  await expect.poll(editorText).toContain("c475b532");
  await app.screenshot("initial-content");
  const errors: unknown[] = [];
  const editAndCapture = async (value: string, label: string) => {
    await writeFile(`${project}/sample.js`, `console.log('${value}');\n`);
    await screen.getByRole("button", "Refresh workspace files").tap();
    try {
      await expect.poll(editorText).toContain(value);
    } catch (error) {
      errors.push(error);
    }
    await app.screenshot(label);
  };
  await editAndCapture("bb9b5e11", "after-colliding-edit-refresh");
  await editAndCapture("bb9b5e12", "non-colliding-control");
  await editAndCapture("c475b532", "restored-original");
  await editAndCapture("bb9b5e11", "repeated-colliding-edit-refresh");
  if (errors.length) throw errors[0];
});
