import { expect } from 'e2e';
import { fileURLToPath } from 'node:url';
import { writeFile,readFile } from 'node:fs/promises';
import { setTimeout as delay } from 'node:timers/promises';
import { test, WEB,makeState,runPromise } from './t3.ts';
import { T3_HOME } from '../e2e.config.ts';

test('Images opened by the agent remain available while choosing a layout',WEB,async ({t3,app,screen,browser})=>{
 const project=await t3.project('Layout study');
 const dir=fileURLToPath(new URL("./image-replay/",import.meta.url));
 for(const name of ['layout-a.png','layout-b.png']) await writeFile(project+'/'+name,await readFile(dir+'/'+name));
 const {cli}=makeState(T3_HOME);
 const shot=async(label:string)=>{
  await browser.mouse.move(1278,798);
  await browser.evaluate(async()=>{await document.fonts.ready;await Promise.all(Array.from(document.images).map(i=>i.decode().catch(()=>{})))});
  let stable=false;
  for(let i=0;i<5;i++){
   const a=await app.screenshot(label+'-probe-a-'+i);await delay(500);
   const b=await app.screenshot(label+'-probe-b-'+i);
   if((await readFile(a)).equals(await readFile(b))){stable=true;break;}
  }
  if(!stable)throw new Error('Capture did not stabilize: '+label);
  await app.screenshot(label);
 };
 await t3.open();
 await screen.getByRole('button','Settings').waitFor({state:'visible',timeout:120000});
 await browser.emulateMedia({reducedMotion:'reduce',colorScheme:'light'});
 await browser.evaluate(()=>{const s=document.createElement('style');s.textContent='*,*::before,*::after{animation:none!important;transition:none!important;caret-color:transparent!important}';document.head.append(s)});
 const info=await browser.evaluate(async()=>await (await fetch('/.well-known/t3/environment')).json());
 for(const [provider,label] of [['claudeAgent','claude'],['codex','codex']]){
  const started=await runPromise(cli(['thread','start',project,'Read both mockups, read layout A again, then ask which layout to implement. Do not embed images in your reply.','--title',label==='claude'?'Choose a layout':'Choose a layout again','--provider',provider!,'--model','layout-replay','--wait','--json'],[0,2]));
  await app.open('/'+info.environmentId+'/'+encodeURIComponent(JSON.parse(started.stdout).threadId));
  await screen.getByText('Which layout should I implement?',{exact:true}).waitFor({state:'visible',timeout:120000});
  // These are normal app controls, so unrelated sidebar state is absent from both sides.
  const sidebar=screen.getByRole('button','Toggle main sidebar');
  if(await sidebar.getAttribute('aria-pressed')==='true')await sidebar.tap();
  const details=screen.getByRole('button','Toggle thread details panel');
  if(await details.getAttribute('aria-pressed')==='true')await details.tap();
  const images=screen.getByRole('button',/^Preview layout-[ab]\.png$/);
  await shot(label+'-pending-collapsed');
  await expect.soft(images).toHaveCount(2,{timeout:1500});
  if(await images.count()===2){
   for(const name of ['layout-a.png','layout-b.png']){
    await screen.getByRole('button','Preview '+name).tap();
    await screen.getByRole('button','Close image preview').waitFor({state:'visible'});
    await shot(label+'-preview-'+name.replace('.png',''));
    await screen.getByRole('button','Close image preview').tap();
   }
  }
  await screen.getByRole('button',/^Layout A A compact/).tap();
  await screen.getByRole('button','Submit',{exact:true}).tap({timeout:1000}).catch(()=>{});
  await screen.getByText('I will implement the selected layout.',{exact:true}).waitFor({state:'visible',timeout:30000});
  const fold=screen.getByRole('button',/^Worked for/);
  if(provider==='claudeAgent')await fold.waitFor({state:'visible'});
  await shot(label+'-settled-fold-closed');
  await expect.soft(images).toHaveCount(0,{timeout:1500});
  if(!(await fold.count()))continue;
  await fold.tap();
  await shot(label+'-settled-fold-open');
  await expect.soft(images).toHaveCount(2,{timeout:1500});
  const reads=screen.getByRole('button',/^Read 3 files/);
  if(await reads.count()){
   await reads.tap();
   await shot(label+'-settled-read-group-expanded');
   const a=screen.getByRole('button',/^Read .*layout-a\.png$/).first();
   if(await a.count())await a.tap();
   await browser.setViewport({width:1280,height:1100});
   await shot(label+'-settled-read-row-expanded');
   await browser.setViewport({width:1280,height:800});
  }
 }
});
