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

test("An image picked in another chat leaves focus on the current message", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("demo");
  const source = await t3.thread({project, title:"Image work", messages:["First thread prompt"]});
  await t3.thread({project, title:"Other work", messages:["Second thread prompt"]});
  await t3.open(source);
  await screen.getByText("first fixture turn complete").waitFor();
  await browser.evaluate(async () => {
    const canvas = new OffscreenCanvas(3500,3500);
    const ctx = canvas.getContext("2d")!;
    const pixels = ctx.createImageData(3500,3500);
    let seed = 123456;
    for(let i=0;i<pixels.data.length;i+=4) {
      for(let j=0;j<3;j++) {seed = (Math.imul(seed,1664525)+1013904223)|0; pixels.data[i+j]=seed>>>24;}
      pixels.data[i+3]=255;
    }
    ctx.putImageData(pixels,0,0);
    const blob = await canvas.convertToBlob({type:"image/png"});
    (window as any).pickedImage = new File([blob],"large-image.png",{type:"image/png"});
    return blob.size;
  });
  await screen.getByRole("textbox").tap();
  // Deliver the file chooser selection through the real input's change handler.
  await browser.evaluate(() => {
    const input = document.querySelector('input[type="file"][multiple]') as HTMLInputElement;
    if (!input) throw new Error("Attachment file input missing");
    const transfer = new DataTransfer();
    transfer.items.add((window as any).pickedImage);
    input.files=transfer.files;
    input.dispatchEvent(new Event("change",{bubbles:true}));
    return null;
  });
  await screen.getByRole("button","Other work",{exact:false}).tap();
  await screen.getByText("Second thread prompt",{exact:true}).tap();
  // Observe the asynchronous completion without touching focus.
  await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve,4000)));
  await browser.keyboard.type("typed after switch");
  await app.screenshot("focus-after-image-preparation");
  const draft = await browser.evaluate(() => document.querySelector('[data-testid="composer-editor"]')?.textContent ?? "");
  expect(draft).not.toContain("typed after switch");
});
