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

test("Paste as Text keeps Word text without attaching its clipboard image", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("word-paste-demo");
  const thread = await t3.thread({ project, title: "Word clipboard paste", messages: ["Ready for clipboard reproduction"] });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.tap();
  const pasteWord = async () => browser.evaluate(() => {
    const editor = document.querySelector<HTMLElement>('[contenteditable="true"][role="textbox"]');
    if (!editor) throw new Error("Composer not found");
    const canvas = document.createElement("canvas");
    canvas.width = 360;
    canvas.height = 90;
    const context = canvas.getContext("2d")!;
    context.fillStyle = "white";
    context.fillRect(0, 0, 360, 90);
    context.fillStyle = "black";
    context.font = "24px serif";
    context.fillText("Hello from Word", 20, 53);
    const bytes = Uint8Array.from(atob(canvas.toDataURL("image/png").split(",")[1]!), c => c.charCodeAt(0));
    const clipboard = new DataTransfer();
    clipboard.setData("text/plain", "Hello from Word");
    clipboard.setData("text/html", "<p class=MsoNormal>Hello from Word</p>");
    clipboard.items.add(new File([bytes], "image.png", { type: "image/png" }));
    const paste = new ClipboardEvent("paste", { clipboardData: clipboard, bubbles: true, cancelable: true });
    editor.dispatchEvent(paste);
    return { defaultPrevented: paste.defaultPrevented };
  });
  await pasteWord();
  await screen.getByRole("button", "Remove image.png", { exact: true }).tap();
  await composer.tap();
  await browser.evaluate(() => {
    document.querySelector('[contenteditable="true"][role="textbox"]')!.dispatchEvent(new KeyboardEvent("keydown", { key: "v", code: "KeyV", ctrlKey: true, shiftKey: true, bubbles: true, cancelable: true }));
    return null;
  });
  await pasteWord();
  await app.screenshot("paste-as-text-result");
  await expect(composer).toContainText("Hello from Word");
  await expect(screen.getByRole("button", "Remove image.png", { exact: true })).toBeHidden();
});
