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

test("A stale tab preserves another tab's finalized stashed image", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("image-stash-demo");
  const original = await t3.thread({ project, title: "Image draft", messages: ["Prepare image review"] });
  const other = await t3.thread({ project, title: "Unrelated draft", messages: ["Prepare unrelated notes"] });
  await t3.open(original);
  await screen.getByTestId("composer-editor").fill("Review the blue reference image");
  await browser.evaluate(async () => {
    const canvas = document.createElement("canvas");
    canvas.width = 640; canvas.height = 400;
    const ctx = canvas.getContext("2d")!;
    ctx.fillStyle = "#2563eb"; ctx.fillRect(0, 0, 640, 400);
    ctx.fillStyle = "white"; ctx.font = "bold 40px sans-serif";
    ctx.fillText("REFERENCE IMAGE", 100, 185); ctx.font = "24px sans-serif";
    ctx.fillText("Must survive a stale tab", 175, 240);
    const blob = await new Promise<Blob>((resolve) => canvas.toBlob((b) => resolve(b!), "image/png"));
    const transfer = new DataTransfer();
    transfer.items.add(new File([blob], "blue-reference.png", { type: "image/png" }));
    const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
    input.files = transfer.files; input.dispatchEvent(new Event("change", { bubbles: true }));
  });
  // Delay only the browser encoding API, leaving the application's stash and storage logic real.
  await browser.evaluate(() => {
    const native = FileReader.prototype.readAsDataURL;
    (window as any).releaseEncoding = () => {
      FileReader.prototype.readAsDataURL = native;
      for (const start of (window as any).pendingEncodes) start();
    };
    (window as any).pendingEncodes = [];
    FileReader.prototype.readAsDataURL = function (blob) {
      (window as any).pendingEncodes.push(() => native.call(this, blob));
    };
  });
  await browser.keyboard.press("Control+s");
  await browser.evaluate(async (otherId) => {
    const key = "t3code:prompt-stash:v2";
    const wait = async (predicate: () => boolean) => {
      const deadline = Date.now() + 30000;
      while (!predicate()) {
        if (Date.now() > deadline) throw new Error("Timed out waiting for scenario precondition");
        await new Promise((resolve) => setTimeout(resolve, 50));
      }
    };
    await wait(() => JSON.parse(localStorage.getItem(key) ?? '{}').state?.entries?.some((e: any) => e.pendingImageCount === 1));
    const url = new URL(location.href); url.pathname = url.pathname.replace(/[^/]+$/, otherId);
    const tab = window.open(url, "stale-image-tab")!;
    (window as any).staleTab = tab;
    await wait(() => !!tab.document.querySelector('[data-testid="composer-editor"]'));
    // The composer mounts after the tab's stash store has loaded the pending entry.
    (window as any).releaseEncoding();
    await wait(() => JSON.parse(localStorage.getItem(key) ?? '{}').state.entries.some((e: any) => e.attachments.length === 1 && !e.pendingImageCount));
  }, other.threadId);
  await screen.getByRole("button", "Stashed prompts: 1. Open stash.").tap();
  await app.screenshot("image-finalized-before-stale-write");
  await screen.getByRole("button", "Close stash").tap();
  await browser.evaluate(async () => {
    const tab = (window as any).staleTab as Window;
    const editor = tab.document.querySelector<HTMLElement>('[data-testid="composer-editor"]')!;
    editor.focus(); tab.document.execCommand("insertText", false, "Unrelated text from tab B");
    await new Promise((resolve) => setTimeout(resolve, 250));
    editor.dispatchEvent(new (tab as any).KeyboardEvent("keydown", { key: "s", code: "KeyS", ctrlKey: true, bubbles: true, cancelable: true }));
    const deadline = Date.now() + 30000;
    while (!JSON.parse(localStorage.getItem("t3code:prompt-stash:v2") ?? '{}').state.entries.some((e: any) => e.text === "Unrelated text from tab B" || e.prompt === "Unrelated text from tab B")) {
      if (Date.now() > deadline) throw new Error("Tab B did not stash its unrelated text");
      await new Promise((resolve) => setTimeout(resolve, 50));
    }
    tab.close();
  });
  await app.open(await browser.evaluate(() => location.pathname));
  await screen.getByRole("button", "Stashed prompts: 2. Open stash.").tap();
  await app.screenshot("stash-after-reload");
  await screen.getByRole("button", /^Restore stashed prompt: Review the blue reference image/).tap();
  await expect(screen.getByRole("button", "Preview blue-reference.png")).toBeVisible();
});
