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

test("Ordinary preview-annotation filename remains visible in sent media", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("image-demo");
  const cases = [
    { title: "Wordless image", name: "preview-annotation-1.png", text: "", label: "wordless-upload" },
    { title: "Image with text", name: "preview-annotation-1.png", text: "Here is my screenshot", label: "upload-with-text" },
    { title: "Ordinary name control", name: "screenshot-1.png", text: "Same image, ordinary name", label: "ordinary-name-control" },
  ];
  const threads = [];
  for (const item of cases) threads.push(await t3.thread({ project, title: item.title, messages: ["Start"], model: "default" }));
  const counts: number[] = [];
  for (const [index, item] of cases.entries()) {
    await t3.open(threads[index]!);
    const input = '[data-chat-composer-form] input[type="file"]';
    await browser.locator(input).waitFor({state: "attached"});
    await browser.evaluate(async ({input, name}) => {
      const canvas = new OffscreenCanvas(420, 180);
      const ctx = canvas.getContext("2d")!;
      ctx.fillStyle = "#e1f2ff"; ctx.fillRect(0,0,420,180);
      ctx.fillStyle = "#17628d"; ctx.fillRect(24,24,64,64);
      ctx.font = "bold 24px sans-serif"; ctx.fillText("Ordinary PNG image", 24, 130);
      const blob = await canvas.convertToBlob({type:"image/png"});
      const files = new DataTransfer();
      files.items.add(new File([blob], name, {type:"image/png"}));
      const picker = document.querySelector<HTMLInputElement>(input)!;
      picker.files = files.files;
      picker.dispatchEvent(new Event("change", {bubbles:true}));
      return null;
    }, {input, name:item.name});
    await screen.getByRole("button", `Remove ${item.name}`).waitFor();
    const composer = screen.getByRole("textbox");
    if(item.text) await composer.fill(item.text);
    await composer.press("Enter");
    await screen.getByRole("button", `Remove ${item.name}`).waitFor({state:"hidden"});
    await browser.locator('[data-message-role="user"]').last().waitFor();
    await screen.getByRole("button", "Stop generation").waitFor();
    await screen.getByRole("button", "Stop generation").waitFor({state:"hidden"});
    await browser.locator('[data-message-role="user"]').last().scrollIntoView();
    await app.screenshot(item.label);
    counts.push(await browser.evaluate(() => document.querySelectorAll('[data-message-role="user"] img').length));
  }
  await expect(counts).toEqual([1, 1, 1]);
});
