import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Queued image labels stay in their sentence", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Header design", { "src/math.ts": "export const sum = 1 + 1;\n" });
  await t3.open();
  await screen.getByRole("button", "New thread", { exact: true }).waitFor();
  await app.open("/settings/chat");
  await screen.getByRole("combobox", "Tool calls in chat").tap();
  await screen.getByRole("option", "Hide all", { exact: true }).tap();
  await app.open("/");
  const composer = screen.getByRole("textbox");
  await composer.fill("Give me a short tour");
  await composer.press("Enter");
  await screen.getByRole("button", "Stop generation").waitFor();
  await composer.fill("Make the header look like ");
  await browser.evaluate(() => {
    const canvas = document.createElement("canvas");
    canvas.width = 320;
    canvas.height = 100;
    const ctx = canvas.getContext("2d")!;
    ctx.fillStyle = "#244c76";
    ctx.fillRect(0, 0, 320, 100);
    ctx.fillStyle = "#ffffff";
    ctx.font = "bold 24px sans-serif";
    ctx.fillText("HEADER", 24, 60);
    const bytes = Uint8Array.from(atob(canvas.toDataURL("image/png").split(",")[1]!), c => c.charCodeAt(0));
    const transfer = new DataTransfer();
    transfer.items.add(new File([bytes], "header.png", { type: "image/png" }));
    document.querySelector('[role="textbox"]')!.dispatchEvent(new ClipboardEvent("paste", { clipboardData: transfer, bubbles: true, cancelable: true }));
    return null;
  });
  await screen.getByText("header.png", { exact: true }).first().waitFor();
  await composer.press("End");
  await composer.pressSequentially(" and keep the logo.");
  await composer.press("Control+Enter");
  const queued = screen.getByRole("listitem", "Queued message 1 of 1, not sent");
  await queued.waitFor();
  await queued.getByRole("button", "Edit queued message").waitFor();
  await app.screenshot("queued-preview");
  const queuedText = await queued.textContent();
  await queued.waitFor({ state: "hidden", timeout: 120_000 });
  await screen.getByRole("button", "Dismiss error").tap();
  await screen.getByText("Make the header look like", { exact: false }).first().scrollIntoView();
  await app.screenshot("dispatched-message");
  expect(queuedText).toContain("Make the header look like header.png and keep the logo.");
});
