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

test("Held image sends retain counts in Russian, Japanese, Korean and Chinese", WEB, async ({ t3, app, browser, screen }) => {
  // Hold compression requests before decoding so the transient banner stays visible.
  // Serialize real thumbnail work to avoid concurrently decoding 22 large JPEGs.
  await browser.addInitScript(() => {
    const NativeWorker = window.Worker;
    window.Worker = class extends NativeWorker {
      constructor(url: string | URL, options?: WorkerOptions) {
        super(url, options);
        if (String(url).includes("imageCompression")) {
          const post = this.postMessage.bind(this);
          const queue: unknown[] = [];
          let busy = false;
          const next = () => {
            const message = queue.shift();
            busy = message !== undefined;
            if (busy) post(message);
          };
          this.addEventListener("message", next);
          this.postMessage = (message) => {
            if (message.task?.kind === "fit") return;
            queue.push(message);
            if (!busy) next();
          };
        }
      }
    };
  });
  await browser.setViewport({ width: 1440, height: 1000 });
  const project = await t3.project("Image count demo");
  const cases = [
    ["English", "Language", "en", 2, "Sending once 2 images are ready"],
    ["Русский", "Язык", "ru", 21, "Отправится, когда 21 изображение будет готово"],
    ["Русский", "Язык", "ru", 22, "Отправится, когда 22 изображения будут готовы"],
    ["Русский", "Язык", "ru", 1, "Отправится, когда изображение будет готово"],
    ["日本語", "言語", "ja", 2, "2枚の画像の準備ができたら送信"],
    ["日本語", "言語", "ja", 1, "画像の準備ができたら送信"],
    ["한국어", "언어", "ko", 2, "이미지 2개가 준비되면 전송"],
    ["한국어", "언어", "ko", 1, "이미지가 준비되면 전송"],
    ["中文（简体）", "语言", "zh", 2, "2 张图片就绪后发送"],
    ["中文（简体）", "语言", "zh", 1, "图片就绪后发送"],
  ] as const;
  const readings: { label: string; visible: string; expected: string }[] = [];
  let currentLanguageLabel = "Language";
  let currentLocale = "";
  for (const [language, languageLabel, locale, count, expected] of cases) {
    const thread = await t3.thread({ project, title: `${locale}: ${count} images`, messages: ["Start"] });
    if (currentLocale !== locale) {
      await t3.open("/settings/general");
      await screen.getByLabel(currentLanguageLabel, { exact: true }).tap();
      await screen.getByRole("option", language, { exact: true }).tap();
      await screen.getByLabel(languageLabel, { exact: true }).waitFor();
      currentLanguageLabel = languageLabel;
      currentLocale = locale;
    }
    await t3.open(thread);
    await screen.getByRole("textbox").tap();
    await browser.keyboard.type("hello");
    await browser.evaluate(async (count) => {
      const canvas = document.createElement("canvas");
      canvas.width = 6000;
      canvas.height = 4000;
      const context = canvas.getContext("2d")!;
      context.fillStyle = "#186a91";
      context.fillRect(0, 0, canvas.width, canvas.height);
      context.fillStyle = "#fff";
      context.font = "160px sans-serif";
      context.fillText("Synthetic image preparation demo", 180, 500);
      const blob = await new Promise<Blob>(resolve => canvas.toBlob(value => resolve(value!), "image/jpeg", 0.95));
      canvas.width = 0;
      canvas.height = 0;
      const clipboardData = new DataTransfer();
      for (let i = 0; i < count; i++) clipboardData.items.add(new File([blob], `sample-${i + 1}.jpg`, { type: "image/jpeg" }));
      document.activeElement!.dispatchEvent(new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }));
      return null;
    }, count);
    await browser.keyboard.press("Enter");
    const banner = browser.locator('[aria-live="polite"]').filter({ hasText: /Sending once|Отправится|準備ができたら送信|준비되면 전송|就绪后发送/ });
    await banner.waitFor();
    const visible = await banner.textContent();
    await app.screenshot(`${locale}-${count}-images-held`);
    readings.push({ label: `${locale}-${count}`, visible: visible ?? "", expected });
    await browser.keyboard.press("Escape");
    await browser.evaluate(() => {
      for (const button of document.querySelectorAll<HTMLButtonElement>('button[aria-label*="sample-"]:not(:disabled)')) button.click();
      return null;
    });
  }
  expect(readings.map(row => `${row.label}: ${row.visible}`)).toEqual(readings.map(row => `${row.label}: ${row.expected}`));
});
