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

const page = (version: string, color: string) => `<!doctype html><title>VERSION ${version}</title><style>html,body{margin:0;background:${color};color:#182030;font: bold 34px system-ui}main{padding:40px 24px}p{font:18px system-ui}</style><main>VERSION ${version}<p>Workspace file preview cache reproduction</p></main>`;

test("Reopening a changed workspace file in Browser shows its current bytes", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("preview-cache", {"repro.html": page("ONE", "#ffb0c8")});
  const thread = await t3.thread({ project, title: "File preview", messages: ["first"] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", {exact:true}).tap();
  const openFile = async () => {
    for(let attempt=0;attempt<100;attempt++) {
    const found = await browser.evaluate(() => {
      for (const host of document.querySelectorAll("*")) {
        const row = host.shadowRoot?.querySelector<HTMLElement>('[data-item-path="repro.html"]');
        if(row) {row.click(); return true;}
      }
      return false;
    });
    if (found) return;
    await new Promise(r=>setTimeout(r,100));
    }
    throw new Error("File tree row repro.html missing");
  };
  // Waits are setup conditions, not verdicts about the cache bug.
  const ready = async () => {
    for(let i=0;i<100;i++) {
      if(await browser.evaluate(() => !!document.querySelector('[data-server-browser-surface] canvas') && !document.querySelector('.preview-loading-progress[data-loading="true"]'))) return;
      await new Promise(r=>setTimeout(r,100));
    }
    throw new Error("Browser did not finish loading");
  };
  const color = () => browser.evaluate(() => {
    const canvas = document.querySelector<HTMLCanvasElement>('[data-server-browser-surface] canvas');
    if(!canvas) return "missing";
    const copy = document.createElement("canvas"); copy.width=canvas.width; copy.height=canvas.height;
    const ctx = copy.getContext("2d")!; ctx.drawImage(canvas,0,0);
    const pixel = ctx.getImageData(10,10,1,1).data;
    return pixel && pixel[1] > pixel[0] ? "TWO" : "ONE";
  });
  const stableCapture = async (label:string) => {
    await ready();
    await new Promise(r=>setTimeout(r,700));
    let previous = await app.screenshot(`${label}-settling`);
    for(let i=0;i<10;i++) {
      await new Promise(r=>setTimeout(r,500));
      const current = await app.screenshot(label);
      if((await readFile(previous)).equals(await readFile(current))) return;
      previous = current;
    }
    throw new Error("Capture did not settle");
  };
  await openFile();
  await screen.getByRole("button", "Open file in preview browser").tap();
  await stableCapture("initial-browser");
  await writeFile(`${project}/repro.html`, page("TWO", "#a0e8ff"));
  await screen.getByRole("button", "Close VERSION ONE", {exact:true}).tap();
  await screen.getByText("repro.html", {exact:true}).first().tap();
  await new Promise(r=>setTimeout(r,700));
  let first = await app.screenshot("files-after-overwrite-settling");
  let settled = false;
  for(let i=0;i<10;i++) {
    await new Promise(r=>setTimeout(r,500));
    const second = await app.screenshot("files-after-overwrite");
    if((await readFile(first)).equals(await readFile(second))) { settled = true; break; }
    first = second;
  }
  if(!settled) throw new Error("Files capture did not settle");
  await screen.getByRole("button", "Open file in preview browser").tap();
  await stableCapture("reopened-browser");
  await expect.poll(color).toBe("TWO");
});
