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

const html = (version: string) => `<!doctype html><html><head><title>${version}</title><link rel="stylesheet" href="repro-43912.css"></head><body style="background:white;padding:32px;font:20px sans-serif"><h1>${version === "V1" ? "VERSION ONE" : "VERSION TWO"}</h1><p>Local workspace preview — stylesheet should be ${version === "V1" ? "red" : "blue"}.</p><p id="actual"></p><script>addEventListener('load',()=>{const color=getComputedStyle(document.querySelector('h1')).color;document.querySelector('#actual').textContent='Loaded heading color: '+color;document.title='${version} '+(color==='rgb(0, 0, 255)'?'BLUE':'RED');});</script></body></html>`;

test("Browser Refresh loads current workspace stylesheet", WEB, async ({t3, app, browser, screen}) => {
  await browser.setViewport({width:1440,height:900});
  const project=await t3.project("preview-demo", {"repro-43912.html":html("V1"),"repro-43912.css":"h1 { color: red; }"});
  const thread=await t3.thread({project,title:"Local HTML refresh",messages:["Start"]});
  await t3.open(thread);
  await screen.getByRole("button","Toggle right panel").tap();
  await screen.getByRole("button","Files F").tap();
  await screen.getByRole("treeitem","repro-43912.html").tap();
  await screen.getByRole("button","Open file in preview browser").tap();
  await screen.getByText("V1 RED",{exact:true}).waitFor({timeout:60000});
  await app.screenshot("initial-red-workspace-page");
  await writeFile(join(project,"repro-43912.css"),"h1 { color: blue; }");
  await writeFile(join(project,"repro-43912.html"),html("V2"));
  await screen.getByRole("button","Refresh",{exact:true}).tap();
  await screen.getByText(/^V2 (RED|BLUE)$/).waitFor({timeout:30000});
  try {
    await expect(screen.getByText("V2 BLUE",{exact:true})).toBeVisible({timeout:5000});
  } finally {
    await app.screenshot("after-refresh-current-stylesheet");
  }
});
