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

test("Russian stash warning refers to all 21 unsaved images", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("image-demo");
  const thread = await t3.thread({project, title:"Проверка изображений", messages:["first"]});
  await t3.open("/settings/general");
  await screen.getByRole("combobox", "Language", {exact:true}).tap();
  await screen.getByRole("option", "Русский", {exact:false}).tap();
  await t3.open(thread);
  await screen.getByRole("textbox").waitFor();
  for (const count of [1,21]) {
    await screen.getByRole("textbox").fill(`Проверка тайника с ${count} изображением`);
    await browser.evaluate(async (count) => {
      const data = new DataTransfer();
      for(let i=1;i<=count;i++) {
        const c = new OffscreenCanvas(64,64);
        const ctx = c.getContext("2d")!;
        ctx.fillStyle = `hsl(${i*17},70%,50%)`; ctx.fillRect(0,0,64,64);
        ctx.fillStyle="white"; ctx.font="20px sans-serif"; ctx.fillText(String(i),12,40);
        data.items.add(new File([await c.convertToBlob({type:"image/png"})],`img-${i}.png`,{type:"image/png"}));
      }
      document.querySelector('[contenteditable="true"]')!.dispatchEvent(new ClipboardEvent("paste", {clipboardData:data,bubbles:true,cancelable:true}));
      return null;
    }, count);
    await browser.locator(`button[aria-label*="img-${count}.png"]`).first().waitFor();
    await screen.getByText("Подготовка", {exact:true}).first().waitFor({state:"hidden"});
    await app.screenshot(`${count}-images-in-composer`);
    await browser.evaluate(() => new Promise<string>((resolve,reject) => {
      const editor = document.querySelector('[contenteditable="true"]') as HTMLElement;
      editor.focus();
      let opened=false;
      const observer=new MutationObserver(()=>{
        const del=document.querySelector('[aria-label="Удалить спрятанный промпт"]') as HTMLButtonElement|null;
        if(del){
          const text=del.closest('li')!.textContent!;
          observer.disconnect();
          if(!text.includes("сохранение")){reject(new Error("Encoding already finished: "+text));return;}
          del.click(); resolve(text); return;
        }
        const badge=document.querySelector('[data-prompt-stash-badge="true"]') as HTMLButtonElement|null;
        if(badge&&!opened){opened=true;badge.click();}
      });
      observer.observe(document.body,{subtree:true,childList:true,attributes:true});
      editor.dispatchEvent(new KeyboardEvent("keydown",{key:"s",code:"KeyS",ctrlKey:true,bubbles:true,cancelable:true}));
    }));
    await screen.getByText("Спрятанные изображения не прикрепились", {exact:true}).waitFor();
    await screen.getByText(`сохранения ${count} изображения.`, {exact:false}).waitFor();
    // Allow the toast entrance transition to settle before evidence capture.
    await browser.evaluate(() => new Promise(resolve => setTimeout(() => resolve(null), 1000)));
    await app.screenshot(`${count}-unsaved-images-warning`);
    await expect(screen.getByText(count===1 ? "Прикрепите его снова, если оно ещё нужно." : "Прикрепите их снова, если они ещё нужны.", {exact:false})).toBeVisible();
    // Dismiss the toast before the next control run.
    await browser.evaluate(()=>{document.querySelectorAll('[data-slot="toast-close"]').forEach(b=>(b as HTMLButtonElement).click());return null;});
  }
});
