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

test("A rich paste with a thread link keeps its picture once", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Paste demo");
  const source = await t3.thread({ project, title: "Source thread", messages: ["Start"], model: "default" });
  const target = await t3.thread({ project, title: "Target thread", messages: ["Start"], model: "default" });
  await t3.open(source);
  const env = await runPromise(environmentId(app.baseUrl!));
  const link = `https://app.t3.codes/threads/${env}/${source.threadId}`;
  await t3.open(target);
  await screen.getByRole("textbox").tap();
  await browser.evaluate(async (link) => {
    const canvas = document.createElement("canvas");
    canvas.width = 200;
    canvas.height = 120;
    const ctx = canvas.getContext("2d")!;
    ctx.fillStyle = "#2563eb";
    ctx.fillRect(0, 0, 200, 120);
    ctx.fillStyle = "white";
    ctx.font = "bold 22px sans-serif";
    ctx.fillText("Paste picture", 24, 66);
    const png = await new Promise<Blob>((resolve) => canvas.toBlob((blob) => resolve(blob!), "image/png"));
    await navigator.clipboard.write([new ClipboardItem({
      "text/plain": new Blob([`See ${link} for details`], { type: "text/plain" }),
      "text/html": new Blob([`<p>See <a href="${link}">Source thread</a> for details</p><img src="${canvas.toDataURL()}">`], { type: "text/html" }),
      "image/png": png,
    })]);
    return null;
  }, link);
  await browser.keyboard.press("Control+v");
  try {
    await expect.poll(() => browser.evaluate(() => document.querySelectorAll('button[aria-label="Preview image.png"]').length)).toBe(1);
  } finally {
    await app.screenshot("rich-paste-with-thread-link");
  }
});
