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

test("Edit from here restores the inline image at its original position", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("image-demo");
  const thread = await t3.thread({ project, title: "Describe an image", messages: ["Start"], model: "command-output" });
  await t3.open(thread);
  const composer = screen.getByRole("textbox");
  await composer.pressSequentially("Look at this image ");
  await browser.evaluate(async () => {
    const canvas = document.createElement("canvas");
    canvas.width = canvas.height = 64;
    const ctx = canvas.getContext("2d")!;
    ctx.fillStyle = "red";
    ctx.fillRect(0, 0, 64, 64);
    const blob = await new Promise<Blob>((resolve) => canvas.toBlob((blob) => resolve(blob!), "image/png"));
    const transfer = new DataTransfer();
    transfer.items.add(new File([blob], "red.png", { type: "image/png" }));
    const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
  });
  await composer.getByRole("button", "Image attachment", { exact: false }).waitFor();
  await composer.pressSequentially(" and describe it");
  await screen.getByRole("button", "Submit message", { exact: true }).tap();
  const edit = screen.getByRole("button", "Edit from here");
  await edit.waitFor();
  await expect(edit).toBeEnabled({ timeout: 60_000 });
  await edit.tap();
  await screen.getByRole("button", "Revert and keep changes").tap();
  await composer.getByText("Look at this image", { exact: false }).waitFor();
  await app.screenshot("restored-inline-image");
  await expect(composer).toHaveText("Look at this image red.png 1 KB and describe it");
  await expect(composer.getByRole("button", "Image attachment", { exact: false })).toHaveCount(1);
});
