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

function png(red: number, blue: number) {
  const crc = (data: Buffer) => {
    let c = 0xffffffff;
    for (const b of data) { c ^= b; for (let i = 0; i < 8; i++) c = (c >>> 1) ^ (c & 1 ? 0xedb88320 : 0); }
    return (c ^ 0xffffffff) >>> 0;
  };
  const chunk = (name: string, data: Buffer) => {
    const type = Buffer.from(name); const len = Buffer.alloc(4); len.writeUInt32BE(data.length);
    const sum = Buffer.alloc(4); sum.writeUInt32BE(crc(Buffer.concat([type, data])));
    return Buffer.concat([len, type, data, sum]);
  };
  const header = Buffer.alloc(13); header.writeUInt32BE(200, 0); header.writeUInt32BE(200, 4); header[8] = 8; header[9] = 2;
  const raw = Buffer.alloc(200 * 601);
  for (let y = 0; y < 200; y++) for (let x = 0; x < 200; x++) { raw[y * 601 + 1 + x * 3] = red; raw[y * 601 + 3 + x * 3] = blue; }
  return Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]), chunk("IHDR",header), chunk("IDAT",deflateSync(raw)), chunk("IEND",Buffer.alloc(0))]);
}

test("Refresh workspace files reloads the embedded Markdown image", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("image-refresh", {"README.md":"# Image refresh demo\n\n![Workspace square](d.png)\n", "d.png":png(255,0)});
  const thread = await t3.thread({project, title:"Markdown image refresh", messages:["first"]});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", {exact:true}).tap();
  await screen.getByRole("button", "Refresh workspace files").waitFor();
  await browser.evaluate(() => {
    for (const host of document.querySelectorAll("*")) {
      const row = host.shadowRoot?.querySelector<HTMLElement>('[data-item-path="README.md"]');
      if(row) { row.click(); return; }
    }
    throw new Error("README tree row missing");
  });
  await screen.getByRole("button", "Show rendered markdown").tap();
  await screen.getByRole("button", "Preview Workspace square").waitFor();
  const pixel = () => browser.evaluate(async () => {
    const img = document.querySelector<HTMLImageElement>('img[alt="Workspace square"]');
    if (!img) return null;
    await img.decode();
    const canvas = document.createElement("canvas"); canvas.width=200; canvas.height=200;
    const ctx = canvas.getContext("2d")!; ctx.drawImage(img,0,0);
    return [...ctx.getImageData(100,100,1,1).data].slice(0,3);
  });
  // Wait for the initial asset to finish decoding before overwriting it.
  await pixel();
  await screen.getByRole("heading", "Image refresh demo").tap();
  await app.screenshot("initial-red-image");
  const original = await stat(`${project}/d.png`);
  await writeFile(`${project}/d.png`,png(0,255));
  if ((await stat(`${project}/d.png`)).ino !== original.ino) throw new Error("Overwrite changed inode");
  await screen.getByRole("button", "Refresh workspace files").tap();
  // Text change is a control that the selected Markdown file actually refreshed.
  await writeFile(`${project}/README.md`,"# Readme v2 text updated\n\n![Workspace square](d.png)\n");
  await screen.getByRole("button", "Refresh workspace files").tap();
  await screen.getByRole("heading", "Readme v2 text updated").waitFor();
  await pixel();
  await screen.getByRole("heading", "Readme v2 text updated").tap();
  await app.screenshot("after-overwrite-and-refresh");
  await expect.poll(pixel).toEqual([0,0,255]);
});
