/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { ProviderInstanceId } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB, rpcClient, runPromise } from "./t3.ts";

test("Editing an attached image cancels a send waiting for image preparation", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("demo");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.refreshProviders"]({instanceId: ProviderInstanceId.make("devReplay"), fresh: true, refreshModels: true});
  }).pipe(Effect.scoped));
  const thread = await t3.thread({project, title: "Compare screenshots", messages: ["Start"], model: "showcase"});
  await t3.open(thread);
  const composer = browser.locator('[data-chat-composer-form="true"]');
  const editor = composer.getByRole("textbox");
  await editor.waitFor({timeout:120_000});
  await editor.fill("Compare these screenshots");
  await browser.evaluate(async () => {
    const canvas = new OffscreenCanvas(600, 400);
    const ctx = canvas.getContext("2d")!;
    ctx.fillStyle = "#e0e7ff"; ctx.fillRect(0,0,600,400);
    ctx.fillStyle = "#334155"; ctx.font = "32px sans-serif"; ctx.fillText("Screenshot to review", 70, 190);
    const data = new DataTransfer();
    data.items.add(new File([await canvas.convertToBlob({type:"image/png"})], "small.png", {type:"image/png"}));
    const picker = document.querySelector<HTMLInputElement>('[data-chat-composer-form] input[type="file"]')!;
    picker.files = data.files; picker.dispatchEvent(new Event("change", {bubbles:true}));
    return null;
  });
  await composer.getByRole("button", "Preview small.png").waitFor();
  await browser.evaluate(async () => {
    const canvas = new OffscreenCanvas(5000, 3000);
    const ctx = canvas.getContext("2d")!;
    const pixels = ctx.createImageData(5000, 3000);
    let seed = 7;
    for(let i=0;i<pixels.data.length;i+=4) {
      seed = (seed * 1664525 + 1013904223) >>> 0;
      pixels.data[i]=seed&255; pixels.data[i+1]=(seed>>>8)&255; pixels.data[i+2]=(seed>>>16)&255; pixels.data[i+3]=255;
    }
    ctx.putImageData(pixels,0,0);
    const blob = await canvas.convertToBlob({type:"image/png"});
    const data = new DataTransfer();
    for(let n=2;n<=5;n++) data.items.add(new File([blob], `huge${n}.png`, {type:"image/png"}));
    const picker = document.querySelector<HTMLInputElement>('[data-chat-composer-form] input[type="file"]')!;
    picker.files=data.files; picker.dispatchEvent(new Event("change", {bubbles:true}));
    return null;
  });
  await composer.getByText("Preparing", {exact:true}).first().waitFor();
  await editor.press("Enter");
  await composer.getByRole("button", "Sending when ready").waitFor();
  await composer.getByRole("button", "Preview small.png").tap();
  await screen.getByRole("button", "Draw on image").tap();
  const drawing = 'svg[aria-label="Draw on small.png"]';
  await browser.locator(drawing).waitFor();
  const point = await browser.evaluate((selector) => {
    const rect=document.querySelector(selector)!.getBoundingClientRect();
    return {x:rect.x+rect.width/3,y:rect.y+rect.height/2};
  }, drawing);
  await browser.mouse.move(point.x, point.y);
  await browser.mouse.down();
  await browser.mouse.move(point.x+100,point.y+40);
  await browser.mouse.up();
  await screen.getByRole("button", "Done", {exact:true}).tap();
  await screen.getByRole("button", "Close image preview").tap();
  await app.screenshot("edited-image-while-send-is-waiting");
  await composer.getByText("Preparing", {exact:true}).first().waitFor({state:"hidden"});
  // Wait for the queued-send effect to settle before capturing the resulting draft or message.
  await browser.evaluate(() => new Promise<null>(resolve => setTimeout(() => resolve(null), 2000)));
  await app.screenshot("after-image-preparation");
  await expect(editor).toContainText("Compare these screenshots");
  await expect(composer.getByRole("button", "Preview small.png")).toBeVisible();
});
