/// <reference lib="dom" />
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import { makeState, runPromise, test, WEB } from "./t3.ts";

import { T3_HOME } from "../e2e.config.ts";

const PROBE = String.raw`import {writeFileSync} from 'node:fs';
const results=[]; let buffer='';
const names=['U+2028 LINE SEPARATOR','U+2029 PARAGRAPH SEPARATOR','NO SEPARATOR CONTROL'];
const show=s=>[...s].map(c=>c==='\t'?'<TAB>':c===' '?'<SPACE>':c==='\u2028'?'<U+2028>':c==='\u2029'?'<U+2029>':c).join('');
process.stdin.setRawMode(true);
process.stdout.write('\x1b[2J\x1b[H\x1b[?2004hRendered inline code: select, copy, paste here\r\n');
writeFileSync('probe-ready','ready');
process.stdin.on('data',chunk=>{
 buffer+=chunk.toString();writeFileSync('probe-raw',buffer);
 let end;
 while((end=buffer.indexOf('\x1b[201~'))>=0){
  const start=buffer.indexOf('\x1b[200~');
  const text=buffer.slice(start+6,end); buffer=buffer.slice(end+6);
  process.stdout.write(names[results.length]+'\r\n'+show(text)+'\r\n');
  results.push(text);writeFileSync('probe-results.json',JSON.stringify(results));
  if(results.length===3){process.stdout.write('\x1b[?2004l');process.exit(0);}
 }
});`;

test('Rendered recovered-list code preserves copied tabs after Unicode separators', WEB,
async ({t3,app,browser,screen})=>{
 const project=await t3.project('whitespace-proof',{'inspect.mjs':PROBE});
 const message='U+2028 line separator\n\n-       `before\u2028\tafter`\n\nU+2029 paragraph separator\n\n-       `before\u2029\tafter`\n\nNo separator control\n\n-       `before\tafter`';
 const seed=async(input:{project:string,title:string,messages:string[],model:string})=>{
 const out=await runPromise(makeState(T3_HOME).cli(['thread','start',input.project,input.messages[0],'--title',input.title,'--provider','devReplay','--model',input.model,'--json']));return JSON.parse(out.stdout);};
 const thread=await seed({project,title:'Inline code whitespace',model:'showcase',messages:[message]});
 const continuation=await seed({project,title:'CR and LF continuation alignment',model:'showcase',messages:[
 'LF continuation: two preserved leading spaces before bar\n\n-     \tfoo\n          bar\n\nCRLF continuation: two preserved leading spaces before bar\n\n-     \tfoo\r\n          bar\n\nLF tab-stop continuation: bar aligns with foo\n\n-        foo\n      \tbar\n\nCRLF tab-stop continuation: bar aligns with foo\n\n-        foo\r\n      \tbar'
 ]});
 const read=(name:string)=>runPromise(Effect.gen(function*(){return yield* (yield* FileSystem.FileSystem).readFileString(`${project}/${name}`)}).pipe(Effect.orElseSucceed(()=>'')));
 await t3.open(thread);
 await screen.getByRole('button','Stop generation',{exact:true}).tap();
 await screen.getByRole('button','Force stop',{exact:true}).tap();
 await expect(screen.getByRole('button','Stop generation',{exact:true})).not.toBeVisible();
 await t3.open(continuation);
 await screen.getByRole('button',/^Agent LF continuation/).tap();
 await browser.evaluate(()=>{
  const paragraph=[...document.querySelectorAll('p')].find(p=>p.textContent?.startsWith('LF continuation:'));
  if(!paragraph)throw new Error('No rendered continuation sample');
  paragraph.scrollIntoView({block:'start'});return null;
 });
 await app.screenshot('CR-LF-continuation-alignment');
 await t3.open(thread);
 await screen.getByRole('button',/^Agent U\+2028/).tap();
 await screen.getByRole('button','Toggle terminal drawer').tap();
 const terminal=screen.getByLabel('Terminal input');
 await expect.poll(async()=>{await terminal.focus();await browser.keyboard.type("echo ready > shell-ready");await browser.keyboard.press('Enter');return read('shell-ready')},{timeout:30000}).toBe('ready\n');
 await terminal.focus();await browser.keyboard.type("PS1=''; node inspect.mjs");await browser.keyboard.press('Enter');
 await expect.poll(()=>read('probe-ready')).toBe('ready');
 for(let i=0;i<3;i++){
  await browser.evaluate((index)=>{
   const code=[...document.querySelectorAll('li code')].filter(e=>e.textContent?.startsWith('before'))[index];
   if(!code)throw new Error('No rendered inline code');
   if(document.activeElement instanceof HTMLElement) document.activeElement.blur();
   code.scrollIntoView({block:'center'});
   const range=document.createRange();range.selectNodeContents(code);
   const selection=window.getSelection();selection?.removeAllRanges();selection?.addRange(range);return null;
  },i);
  await browser.keyboard.press('ControlOrMeta+C');
  await terminal.focus();await browser.keyboard.press('Control+Shift+V');
  await expect.poll(async()=>{const s=await read('probe-results.json');return s?JSON.parse(s).length:0}).toBe(i+1);
 }
 await expect(screen.getByRole('button','Stop generation',{exact:true})).not.toBeVisible();
 await browser.evaluate(()=>{if(document.activeElement instanceof HTMLElement)document.activeElement.blur();return null;});
 await app.screenshot('copied-rendered-code-whitespace');
 await browser.evaluate(async()=>{await new Promise(r=>setTimeout(r,500));return null;});
 await app.screenshot('copied-rendered-code-whitespace-stability');
 const copied=JSON.parse(await read('probe-results.json'));
 await expect(copied).toEqual(['before\u2028\tafter','before\u2029\tafter','before\tafter']);
});
