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

test("A compressed PNG with a maximum-length filename can be sent", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("image-demo");
  const thread = await t3.thread({ project, title: "Maximum filename image", messages: ["first"], model: "showcase" });
  await t3.open(thread);
  const input = '[data-chat-composer-form] input[type="file"]';
  await browser.locator(input).waitFor({ state: "attached" });
  await browser.evaluate(async (selector) => {
    const canvas = new OffscreenCanvas(2000, 2000);
    const context = canvas.getContext("2d")!;
    const pixels = context.createImageData(2000, 2000);
    let seed = 48694;
    for (let i = 0; i < pixels.data.length; i += 4) {
      for (let channel = 0; channel < 3; channel++) {
        seed = (Math.imul(seed, 1664525) + 1013904223) | 0;
        pixels.data[i + channel] = seed >>> 24;
      }
      pixels.data[i + 3] = 255;
    }
    context.putImageData(pixels, 0, 0);
    const png = await canvas.convertToBlob({ type: "image/png" });
    const files = new DataTransfer();
    files.items.add(new File([png], "a".repeat(251) + ".png", { type: "image/png" }));
    const picker = document.querySelector<HTMLInputElement>(selector)!;
    picker.files = files.files;
    picker.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  }, input);
  await browser.locator('[data-chat-composer-form] [aria-label^="Preview "][aria-label$=".webp"]').waitFor();
  await app.screenshot("compressed-image-before-send");
  const composer = screen.getByRole("textbox");
  await composer.fill("describe this image");
  await screen.getByRole("button", "Submit message", { exact: true }).tap();
  // On either side wait for the visible outcome: restored draft error or posted image.
  await browser.locator('[data-message-role="user"]:has([aria-label$=".webp"]), [data-variant="error"]').first().waitFor();
  if (await screen.getByRole("button", "Show full error", { exact: true }).isVisible()) {
    await screen.getByRole("button", "Show full error", { exact: true }).tap();
  }
  if (await browser.locator('[data-message-role="user"]:has([aria-label$=".webp"])').isVisible()) {
    await browser.locator('[data-message-role="user"] [aria-label$=".webp"] img').waitFor();
    await browser.evaluate(async () => {
      const images = document.querySelectorAll<HTMLImageElement>('[data-message-role="user"] img');
      await Promise.all(Array.from(images, (image) => image.decode()));
      return null;
    });
    await screen.getByText("This turn is a replay.", { exact: false }).nth(1).waitFor();
    await screen.getByRole("button", "Stop generation", { exact: true }).waitFor({ state: "hidden" });
    await browser.evaluate(() => {
      document.querySelector('[data-message-role="user"]:has([aria-label$=".webp"])')!.scrollIntoView({ block: "center", behavior: "instant" });
      return null;
    });
  }
  await app.screenshot("image-send-result");
  await expect(browser.locator('[data-message-role="user"]:has([aria-label$=".webp"])').filter({ hasText: "describe this image" })).toBeVisible();
});
