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

test("restoring a saving stash preserves its image until retry", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("demo");
  await t3.open();
  const composer = screen.getByRole("textbox");
  await composer.fill("Look at this screenshot");
  await browser.evaluate(async () => {
    const canvas = new OffscreenCanvas(1700, 1700);
    const ctx = canvas.getContext("2d")!;
    const pixels = ctx.createImageData(1700, 1700);
    let seed = 47279;
    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);
    ctx.fillStyle = "white";
    ctx.fillRect(80, 80, 1540, 260);
    ctx.fillStyle = "#172554";
    ctx.font = "bold 70px sans-serif";
    ctx.fillText("Synthetic screenshot", 130, 230);
    const file = new File([await canvas.convertToBlob({ type: "image/png" })], "screenshot.png", { type: "image/png" });
    const transfer = new DataTransfer();
    transfer.items.add(file);
    const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
    input.files = transfer.files;
    input.dispatchEvent(new Event("change", { bubbles: true }));
    return null;
  });
  await browser.locator('img[alt="screenshot.png"]').waitFor();
  // Delay only the save read after attachment preparation. All bytes and app code stay real.
  await browser.evaluate(() => {
    const read = FileReader.prototype.readAsDataURL;
    (window as any).finishStashRead = null;
    FileReader.prototype.readAsDataURL = function (blob) {
      FileReader.prototype.readAsDataURL = read;
      (window as any).finishStashRead = () => read.call(this, blob);
    };
    return null;
  });
  await composer.press("ControlOrMeta+s");
  await screen.getByRole("button", /Stashed prompts: 1/).tap();
  await screen.getByText("saving 1 image…", { exact: false }).waitFor();
  await app.screenshot("saving-before-restore");
  await screen.getByRole("button", /Restore stashed prompt: Look at this screenshot/).tap();
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().filter(a => a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => {}))); return null; });
  await app.screenshot("restore-during-save");
  const retained = await browser.evaluate(() => document.body.textContent!.includes("saving 1 image"));
  await expect.poll(() => browser.evaluate(() => typeof (window as any).finishStashRead)).toBe("function");
  await browser.evaluate(() => { (window as any).finishStashRead(); return null; });
  if (retained) {
    await screen.getByText("saving 1 image…", { exact: false }).waitFor({ state: "hidden" });
    await screen.getByRole("button", /Restore stashed prompt: Look at this screenshot/).tap();
    await browser.locator('img[alt="screenshot.png"]').waitFor();
  } else {
    await screen.getByText("Stashed images did not attach", { exact: false }).waitFor();
  }
  await browser.evaluate(async () => { await Promise.all(document.getAnimations().filter(a => a.effect?.getTiming().iterations !== Infinity).map(a => a.finished.catch(() => {}))); return null; });
  await app.screenshot("after-saving-and-retry");
  await expect(retained).toBe(true);
  await expect(composer).toContainText("Look at this screenshot");
  await expect(browser.locator('img[alt="screenshot.png"]')).toBeVisible();
});
