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

test("Restoring into a full draft removes the skipped image chip", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("demo");
  const threadInput = {project, title: "Stash image limit", messages: ["Start"]};
  const thread = await t3.thread({...threadInput, model: "multi-turn"}).catch((error) => {
    if (!String(error).includes("Advertised models: default")) throw error;
    return t3.thread({...threadInput, model: "default"});
  });
  await t3.open(thread);
  await screen.getByRole("textbox").fill("Review this screenshot please ");
  const attach = async (names: string[]) => {
    await browser.evaluate((names) => {
      const picker = document.querySelector<HTMLInputElement>('[data-chat-composer-form] input[type="file"]')!;
      const files = new DataTransfer();
      const canvas = document.createElement("canvas"); canvas.width=80; canvas.height=60;
      const ctx=canvas.getContext("2d")!; ctx.fillStyle="#2563eb"; ctx.fillRect(0,0,80,60);
      const bytes=Uint8Array.from(atob(canvas.toDataURL("image/png").split(",")[1]!),c=>c.charCodeAt(0));
      for (const name of names) files.items.add(new File([bytes], name, {type: "image/png"}));
      picker.files = files.files;
      picker.dispatchEvent(new Event("change", {bubbles:true}));
      return null;
    }, names);
    await browser.locator(`button[aria-label="Preview ${names[names.length - 1]}"]:not([disabled])`).waitFor({state:"attached"});
  };
  await attach(["screenshot.png"]);
  await screen.getByRole("textbox").tap();
  await browser.keyboard.press("Control+s");
  await browser.locator('[aria-label="Stashed prompts: 1. Open stash."]').waitFor({state:"attached"});
  for (let batch=0; batch<5; batch++) await attach(Array.from({length:20}, (_,i)=>`filler-${batch*20+i+1}.png`));
  await browser.evaluate(() => { document.querySelector<HTMLButtonElement>('[aria-label="Stashed prompts: 1. Open stash."]')!.click(); return null; });
  await browser.locator('[data-stash-restore]').waitFor({state:"attached"});
  await browser.evaluate(() => { document.querySelector<HTMLButtonElement>('[data-stash-restore]')!.click(); return null; });
  await screen.getByText("Some attachments were not restored", {exact:true}).waitFor();
  await app.screenshot("restored-stash-at-image-limit");
  const result = await browser.evaluate(() => {
    const editor = document.querySelector('[role="textbox"]')!;
    return {text: editor.textContent?.trim(), broken: editor.querySelectorAll('[aria-label="Unavailable context, screenshot.png"]').length, previews: document.querySelectorAll('button[aria-label^="Preview filler-"]').length, screenshot: document.querySelectorAll('button[aria-label="Preview screenshot.png"]').length};
  });
  expect(result).toEqual({text:"Review this screenshot please", broken:0, previews:100, screenshot:0});
});
