import { expect } from "e2e";
import { test, WEB } from "./t3.ts";
import {readFileSync} from "node:fs";
const pause=(ms:number)=>new Promise(r=>setTimeout(r,ms));
test("Late async answer appears at its new run and is searchable", WEB, async ({t3,app,screen,browser})=>{
 const stable=async(label:string)=>{await browser.evaluate(()=>{(document.activeElement as HTMLElement)?.blur()});await pause(5000);let a=await app.screenshot(label);for(let i=0;i<10;i++){await pause(500);const b=await app.screenshot(label+"-stable-"+i);if(readFileSync(a).equals(readFileSync(b)))return;a=b;}throw new Error("Capture changed: "+label);};
 const composer=()=>screen.getByRole("textbox", {name:/^Message /});
 await browser.emulateMedia({reducedMotion:"reduce"});
 await t3.project("Answer demo"); await t3.open();
 await composer().fill("Start same: ask a color question and keep working while I answer.");await composer().press("Enter");
 await screen.getByText("Same-run color?",{exact:true}).waitFor({state:"visible"});
 await composer().fill("Green same-run probe");await screen.getByRole("button","Submit",{exact:true}).tap();
 await screen.getByText("Same-run answer acknowledged.",{exact:false}).waitFor({state:"visible"});
 await stable("same-run-folded");
 await expect(browser.locator('[data-message-id^="async-answer:"]')).toHaveCount(0);
 await screen.getByRole("button","New thread",{exact:true}).tap();
 await composer().fill("Start late: pause, then ask a color question while continuing.");await composer().press("Enter");
 await composer().fill("Queued follow-up");await composer().press("Control+Enter");
 await screen.getByText("Queued follow-up complete.", {exact:false}).waitFor({state:"visible"});
 await composer().fill("Blue late-answer probe");await screen.getByRole("button","Submit",{exact:true}).tap();
 await screen.getByText("Answer acknowledged.",{exact:true}).waitFor({state:"visible"});
 await stable("late-answer-run");
 await browser.keyboard.press("Control+f");await screen.getByRole("searchbox","Find in thread").fill("Blue late-answer probe");
 await pause(1500);await stable("find-late-answer");
 await expect(screen.getByRole("button","Next match")).toBeEnabled();
 await screen.getByRole("button","Close find").tap();
 await expect(browser.locator('[data-message-id^="async-answer:"]')).toHaveCount(1);
});
