import { expect } from "e2e";
import { readFile } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { test, WEB } from "./t3.ts";

test("A stopped target stays beside compact-history send controls",WEB,async({t3,app,screen,browser})=>{
  await t3.project("Compact demonstration");
  await browser.emulateMedia({reducedMotion:"reduce",colorScheme:"light"});
  await browser.addInitScript(() => {
    const Original=Date;
    class FixtureDate extends Original {
      constructor(...args:any[]) { super(...(args.length?args:[Original.now()+71*60000]) as [any]); }
      static now(){return Original.now()+71*60000;}
    }
    window.Date=FixtureDate as any;
  });
  await t3.open();
  await screen.getByRole("textbox").fill("Prepare a synthetic conversation.");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByText("A synthetic conversation is ready.", {exact:false}).waitFor({state:"visible"});
  await screen.getByRole("button","Stop generation").waitFor({state:"hidden"});
  await screen.getByRole("textbox").fill("Work on a larger change.");
  await screen.getByRole("textbox").press("Enter");
  await screen.getByRole("button","Stop generation").waitFor({state:"visible"});
  await screen.getByText("Working on the requested update.",{exact:false}).waitFor({state:"visible"});
  const point=await browser.evaluate(()=>{const r=document.querySelector('[aria-label="Stop generation"]')!.getBoundingClientRect();return{x:r.x+r.width/2,y:r.y+r.height/2};});
  await screen.getByRole("button","Stop generation").tap();
  await new Promise(r=>setTimeout(r,1800));
  await screen.getByRole("textbox").fill("Keep this compacted-history draft for later.");
  await browser.locator('[data-chat-composer-compact-send="true"]').waitFor({state:"visible"});
  const capture=async(label:string)=>{
    await browser.evaluate(()=>{(document.activeElement as HTMLElement)?.blur();document.getAnimations().forEach(a=>a.pause());});
    for(let n=0;n<8;n++){
      const a=await app.screenshot(`${label}-check-${n}`);await new Promise(r=>setTimeout(r,500));const b=await app.screenshot(label);
      const crop=(p:string)=>execFileSync("convert",[p,"-crop","740x320+270+480","+repage","rgba:-"]);
      if(crop(a).equals(crop(b)))return;
    }
    throw new Error("Composer did not settle");
  };
  await capture("compact-stopped-with-draft");
  await browser.mouse.move(point.x,point.y);for(let n=0;n<3;n++){await browser.mouse.down();await browser.mouse.up();}
  await new Promise(r=>setTimeout(r,1800));
  await capture("compact-after-repeat");
  const kept=await browser.evaluate(()=>document.querySelector('[data-testid="composer-editor"]')!.textContent!.includes("Keep this compacted-history draft for later."));
  expect(kept).toBe(true);
});
