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

test("Confirming referenced image removal returns typing to the composer", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("server", {"vite.config.ts": "export default {};\n"});
  const thread = await t3.thread({project, title: "Compare images", messages: ["Start"]});
  await t3.open(thread);
  await screen.getByTestId("composer-editor").waitFor();
  await screen.getByText("first fixture turn complete", {exact:false}).waitFor();
  await browser.keyboard.press("Control+p");
  await screen.getByPlaceholder("Search files…").fill("vite.config.ts");
  await screen.getByRole("option", "vite.config.ts", {exact:false}).tap();
  await screen.getByRole("button", "Browse server", {exact:true}).tap();
  await browser.keyboard.press("Escape");
  const composer = screen.getByTestId("composer-editor");
  await composer.fill("Compare ");
  await browser.evaluate(() => {
    const canvas = document.createElement("canvas"); canvas.width=120; canvas.height=80;
    const ctx=canvas.getContext("2d")!; ctx.fillStyle="#4686cc"; ctx.fillRect(0,0,120,80);
    const bytes=Uint8Array.from(atob(canvas.toDataURL("image/png").split(",")[1]!), c=>c.charCodeAt(0));
    const files=new DataTransfer();
    for (const name of ["pic1.png", "pic2.png"]) files.items.add(new File([bytes], name, {type:"image/png"}));
    const picker=document.querySelector<HTMLInputElement>('[data-chat-composer-form] input[type="file"]')!;
    picker.files=files.files; picker.dispatchEvent(new Event("change",{bubbles:true}));
    return null;
  });
  await screen.getByRole("button", "Remove pic2.png", {exact:true}).waitFor();
  await composer.tap();
  await browser.keyboard.press("Shift+Tab");
  await browser.keyboard.press("Shift+Tab");
  await browser.keyboard.press("Shift+Tab");
  await browser.keyboard.press("Enter");
  await screen.getByRole("button", "Cancel", {exact:true}).waitFor();
  await app.screenshot("confirm-image-removal");
  await browser.keyboard.press("Tab");
  await browser.keyboard.press("Enter");
  await screen.getByRole("button", "Remove pic1.png", {exact:true}).waitFor({state:"hidden"});
  await screen.getByRole("button", "Confirm", {exact:true}).waitFor({state:"hidden"});
  await browser.keyboard.type("x");
  await app.screenshot("typing-after-confirmed-removal");
  await expect(composer).toBeFocused();
  await expect(composer).toContainText("x");
});
