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

test("Discard survives a pasted image finishing compression and Undo restores the prompt", WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project("Draft evidence");
  const source = await t3.thread({project, title:"Source thread", messages:["Hello"]});
  await t3.thread({project, title:"Other thread", messages:["Hello"]});
  await t3.open(source);
  // Keep the real encoder's result pending until the sidebar interaction completes.
  // No draft state or compression result is mocked.
  await browser.evaluate(() => {
    const original = OffscreenCanvas.prototype.convertToBlob;
    const state = {hold:false, releases:[] as (()=>void)[], completed:0};
    (window as any).__compression = state;
    OffscreenCanvas.prototype.convertToBlob = async function(options) {
      const result = await original.call(this, options);
      if (state.hold && this.width > 300) await new Promise<void>(resolve => state.releases.push(resolve));
      state.completed++;
      return result;
    };
  });
  const completedImage = async () => {
    await browser.evaluate(async () => {
      const canvas=document.createElement("canvas"); canvas.width=180; canvas.height=120;
      const ctx=canvas.getContext("2d")!; ctx.fillStyle="#1c9860"; ctx.fillRect(0,0,180,120);
      ctx.fillStyle="white"; ctx.font="20px sans-serif"; ctx.fillText("Saved image",15,60);
      const blob=await new Promise<Blob>(resolve=>canvas.toBlob(b=>resolve(b!),"image/png"));
      const data=new DataTransfer(); data.items.add(new File([blob],"saved-image.png",{type:"image/png"}));
      document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste",{clipboardData:data,bubbles:true,cancelable:true}));
      await new Promise(resolve=>setTimeout(resolve,1000));
    });
  };
  const paste = async () => {
    await browser.evaluate(async () => {
      const canvas = document.createElement("canvas");
      canvas.width=6000; canvas.height=4000;
      const ctx=canvas.getContext("2d")!;
      ctx.fillStyle="#1b3559"; ctx.fillRect(0,0,6000,4000);
      ctx.fillStyle="#ffffff"; ctx.font="160px sans-serif"; ctx.fillText("Synthetic screenshot",200,400);
      const blob=await new Promise<Blob>(resolve=>canvas.toBlob(b=>resolve(b!),"image/png"));
      (window as any).__compression.hold=true;
      const data=new DataTransfer(); data.items.add(new File([blob],"large-screenshot.png",{type:"image/png"}));
      document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste",{clipboardData:data,bubbles:true,cancelable:true}));
    });
    await screen.getByRole("button", "Remove large-screenshot.png").first().hover();
  };
  const finish = async () => {
    await browser.evaluate(async () => {
      const state=(window as any).__compression;
      while(!state.releases.length) await new Promise(resolve=>setTimeout(resolve,50));
      state.hold=false; for(const release of state.releases.splice(0)) release();
      await new Promise(resolve=>setTimeout(resolve,1000));
    });
  };
  await screen.getByRole("textbox").fill("Keep this existing-thread prompt");
  await completedImage();
  await paste();
  await app.screenshot("existing-preparing");
  await screen.getByTestId("sidebar-row-card").filter({hasText:"Other thread"}).tap();
  await screen.getByTestId("sidebar-row-card").filter({hasText:"Source thread"}).hover();
  await screen.getByTestId("sidebar-row-card").filter({hasText:"Source thread"}).getByRole("button","Discard draft").tap();
  await finish();
  await screen.getByRole("textbox").hover();
  await app.screenshot("existing-after-compression");
  const markerReturned = await browser.locator('[aria-label="Unsent draft"]').count();
  await screen.getByRole("button",/to undo|^Undo$/).tap();
  await screen.getByTestId("sidebar-row-card").filter({hasText:"Source thread"}).tap();
  await app.screenshot("existing-after-undo");
  const restoredImages = await browser.locator('[aria-label="Preview saved-image.png"]').count();
  const restored = await browser.evaluate(()=>document.querySelector('[contenteditable="true"]')?.textContent ?? "");
  const dismiss = screen.getByRole("button", "Dismiss notification");
  if (await dismiss.count()) await dismiss.tap();
  await screen.getByRole("button", "New thread in Draft evidence", {exact:true}).tap();
  await screen.getByRole("textbox").fill("Keep this new-thread prompt");
  await screen.getByTestId("sidebar-row-card").filter({hasText:"Other thread"}).tap();
  await screen.getByTestId("sidebar-draft-row").filter({hasText:"Keep this new-thread prompt"}).tap();
  await completedImage();
  await paste();
  await app.screenshot("new-draft-preparing");
  await screen.getByTestId("sidebar-draft-row").filter({hasText:"Keep this new-thread prompt"}).hover();
  await screen.getByTestId("sidebar-draft-row").filter({hasText:"Keep this new-thread prompt"}).getByRole("button", "Discard draft").tap();
  await finish();
  await app.screenshot("new-draft-after-compression");
  await screen.getByRole("button", /to undo|^Undo$/).tap();
  await browser.evaluate(async()=>{await new Promise(resolve=>setTimeout(resolve,500));});
  const restoredRow = screen.getByTestId("sidebar-draft-row").filter({hasText:"Keep this new-thread prompt"});
  if (await restoredRow.count()) await restoredRow.tap();
  await app.screenshot("new-draft-after-undo");
  const newRestored = await browser.evaluate(()=>document.querySelector('[contenteditable="true"]')?.textContent ?? "");
  const newRestoredImages = await browser.locator('[aria-label="Preview saved-image.png"]').count();
  const preparingRestored = await browser.locator('[aria-label="Preview large-screenshot.png"]').count();
  await expect(markerReturned).toBe(0);
  await expect(restoredImages).toBe(1);
  await expect(newRestoredImages).toBe(1);
  await expect(preparingRestored).toBe(0);
  await expect(newRestored).toContain("Keep this new-thread prompt");
  await expect(restored).toContain("Keep this existing-thread prompt");
});
