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

const page = (version: number, color: string) => `<!doctype html><html><body style="margin:0;background:${color};font:16px system-ui;padding:16px"><h1 style="font-size:24px">Version ${version}</h1><p>Workspace HTML preview</p></body></html>`;

test("Refreshing workspace files reloads an externally changed HTML preview", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("proj", { "page.html": page(1, "#b9edbb") });
  const thread = await t3.thread({ project, title: "go", messages: ["Start"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", { exact: true }).tap();
  await expect.poll(() => browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const row = host.shadowRoot?.querySelector<HTMLElement>('[data-item-path="page.html"]');
      if (row) { row.click(); return true; }
    }
    return false;
  })).toBe(true);
  const preview = browser.frameLocator('iframe[title="page.html"]:not([aria-hidden="true"])');
  await expect(preview.locator("body")).toContainText("Version 1");
  await app.screenshot("initial-version-1");
  await runPromise(Effect.flatMap(FileSystem.FileSystem, fs => fs.writeFileString(`${project}/page.html`, page(2, "#f2bfd7"))));
  await screen.getByRole("button", "Refresh workspace files").tap();
  try {
    await expect(preview.locator("body")).toContainText("Version 2");
  } finally {
    await app.screenshot("after-refresh");
  }
});
