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

function image() {
  const crc = (data: Buffer) => {
    let value = 0xffffffff;
    for (const byte of data) {
      value ^= byte;
      for (let bit = 0; bit < 8; bit++) value = (value >>> 1) ^ ((value & 1) ? 0xedb88320 : 0);
    }
    return (value ^ 0xffffffff) >>> 0;
  };
  const chunk = (type: string, data: Buffer) => {
    const body = Buffer.concat([Buffer.from(type), data]);
    const size = Buffer.alloc(4); size.writeUInt32BE(data.length);
    const sum = Buffer.alloc(4); sum.writeUInt32BE(crc(body));
    return Buffer.concat([size, body, sum]);
  };
  const header = Buffer.alloc(13);
  header.writeUInt32BE(1920, 0); header.writeUInt32BE(1080, 4); header[8] = 8; header[9] = 2;
  const pixels = Buffer.alloc((1920 * 3 + 1) * 1080);
  for (let y = 0; y < 1080; y++) for (let x = 0; x < 1920; x++) {
    const offset = y * (1920 * 3 + 1) + 1 + x * 3;
    pixels[offset] = 35 + Math.floor(x / 12); pixels[offset + 1] = 65 + Math.floor(y / 8); pixels[offset + 2] = 160;
  }
  return 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("Image dimensions follow German app language in an English browser", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("image-preview", { "wide.png": image() });
  const thread = await t3.thread({ project, title: "Image preview", messages: ["Start"] });
  await t3.open("/settings/general");
  await screen.getByLabel("Language", { exact: true }).tap({ timeout: 120_000 });
  await screen.getByText("Deutsch", { exact: true }).tap();
  await screen.getByLabel("Sprache", { exact: true }).waitFor();
  await t3.open(thread);
  await screen.getByRole("button", "Rechtes Panel umschalten").tap();
  await screen.getByText("Dateien", { exact: true }).tap();
  await screen.getByRole("treeitem", "wide.png").tap();
  await screen.getByText(/1[,.]920 × 1[,.]080/, { exact: true }).waitFor();
  console.log("Capture environment", await browser.evaluate(() => ({ browserLanguage: navigator.language, numberLocale: new Intl.NumberFormat().resolvedOptions().locale, appLanguage: document.documentElement.lang })));
  await app.screenshot("german-image-dimensions");
  await expect(screen.getByText("1.920 × 1.080", { exact: true })).toBeVisible();
});
