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

function png(red: number, green: number, blue: number) {
  const crc = (bytes: Uint8Array) => {
    let value = 0xffffffff;
    for (const byte of bytes) {
      value ^= byte;
      for (let bit = 0; bit < 8; bit++) value = (value >>> 1) ^ ((value & 1) ? 0xedb88320 : 0);
    }
    return (value ^ 0xffffffff) >>> 0;
  };
  const chunk = (name: string, data: Buffer) => {
    const type = Buffer.from(name);
    const size = Buffer.alloc(4); size.writeUInt32BE(data.length);
    const checksum = Buffer.alloc(4); checksum.writeUInt32BE(crc(Buffer.concat([type, data])));
    return Buffer.concat([size, type, data, checksum]);
  };
  const header = Buffer.alloc(13); header.writeUInt32BE(3200); header.writeUInt32BE(1800, 4); header[8] = 8; header[9] = 2;
  const pixels = Buffer.alloc((3200 * 3 + 1) * 1800);
  for (let y = 0; y < 1800; y++) for (let x = 0; x < 3200; x++) {
    const i = y * (3200 * 3 + 1) + 1 + x * 3;
    const line = x % 400 < 12 || y % 300 < 12;
    pixels[i] = line ? 245 : red; pixels[i + 1] = line ? 245 : green; pixels[i + 2] = line ? 245 : blue;
  }
  return new Uint8Array(Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]), chunk("IHDR", header), chunk("IDAT", deflateSync(pixels)), chunk("IEND", Buffer.alloc(0))]));
}

test("Cached images are fitted on their first visible frame", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("image-preview", { "a.png": png(30, 110, 180), "b.png": png(180, 75, 40) });
  const thread = await t3.thread({ project, title: "Image preview", messages: ["Start"] });
  await browser.setViewport({ width: 1280, height: 800 });
  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();
  const click = (path: string) => browser.evaluate((path) => {
    for (const host of document.querySelectorAll("*")) {
      const row = host.shadowRoot?.querySelector<HTMLElement>(`[data-item-path="${path}"]`);
      if (row) { row.click(); return true; }
    }
    return false;
  }, path);
  await browser.locator('[data-file-tree-host]').waitFor({ state: "attached" }).catch(() => {});
  // Warm both image resources before observing eight cached switches.
  for (const file of ["a.png", "b.png"]) {
    await click(file);
    await browser.locator(`button[aria-label="Zoom ${file}"] img`).waitFor();
    await screen.getByRole("button", "Actual image size").waitFor();
    await browser.evaluate(async (file) => {
      for (let frame = 0; frame < 30; frame++) await new Promise(requestAnimationFrame);
      return document.querySelector<HTMLImageElement>(`img[alt="${file}"]`)?.naturalWidth;
    }, file);
  }
  await app.screenshot("cached-image-ready");
  const samples = await browser.evaluate(async () => {
    const samples: Array<{ switch: number; width: number; viewport: number; visible: boolean; complete: boolean; natural: number }> = [];
    for (let index = 0; index < 8; index++) {
      const file = index % 2 ? "b.png" : "a.png";
      for (const host of document.querySelectorAll("*")) {
        const row = host.shadowRoot?.querySelector<HTMLElement>(`[data-item-path="${file}"]`);
        if (row) { row.click(); break; }
      }
      for (let frame = 0; frame < 30; frame++) {
        await new Promise(requestAnimationFrame);
        const image = document.querySelector<HTMLImageElement>(`button[aria-label="Zoom ${file}"] img`);
        if (!image) continue;
        const style = getComputedStyle(image);
        samples.push({ switch: index + 1, width: image.getBoundingClientRect().width, viewport: image.closest('button')!.parentElement!.parentElement!.clientWidth, visible: style.visibility !== "hidden" && style.display !== "none" && style.opacity !== "0", complete: image.complete, natural: image.naturalWidth });
      }
    }
    return samples;
  });
  console.log("IMAGE_FRAME_SAMPLES", JSON.stringify(samples));
  await app.screenshot("after-eight-cached-switches");
  expect(samples.filter(s => s.visible && s.complete && s.natural === 3200 && s.width > s.viewport)).toEqual([]);
});
