/// <reference lib="dom" />
import { readFile, writeFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";
const PROGRAM = String.raw`import { writeFileSync, existsSync } from 'node:fs';
const state = new URL('state', import.meta.url);
const resume = new URL('resume', import.meta.url);
process.stdout.write('\x1b[2J\x1b[H\x1b]0;' + '─'.repeat(200000) + '\x1b]0;Build', () => {
 writeFileSync(state, 'paused');
 const timer = setInterval(() => {
  if (!existsSync(resume)) return;
  clearInterval(timer);
  process.stdout.write('progress\x07ready\r\n', () => { writeFileSync(state, 'done'); process.exit(0); });
 }, 50);
});`;
test('Joining during an unfinished title hides its continuation', WEB, async ({t3, app, browser, screen}) => {
 const project = await t3.project('terminal-proof', {'program.mjs': PROGRAM});
 const thread = await t3.thread({project, title: 'Terminal attach history', messages: ['hello']});
 const read = (name: string) => readFile(`${project}/${name}`, 'utf8').catch(() => '');
 const waitState = async (value: string) => { for(let i=0;i<300;i++){ if(await read('state')===value) return; await new Promise(r=>setTimeout(r,100)); } throw new Error(`Program did not reach ${value}`); };
 await t3.open(thread);
 await screen.getByRole('button', 'Toggle terminal drawer').tap();
 const terminal = screen.getByLabel('Terminal input');
 for(let i=0;i<30;i++) {
  await terminal.focus(); await browser.keyboard.type(`echo ready > '${project}/shell-ready'`); await browser.keyboard.press('Enter');
  await new Promise(r=>setTimeout(r,250)); if(await read('shell-ready')) break;
 }
 await terminal.focus(); await browser.keyboard.type(`PS1='$ '; '${process.execPath}' '${project}/program.mjs'`); await browser.keyboard.press('Enter');
 await waitState('paused');
 await browser.evaluate(() => {const f=document.createElement('iframe'); f.id='joining-client'; f.src=location.href; f.style.cssText='position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647';document.body.append(f);return null;});
 const other = browser.frameLocator('#joining-client');
 await other.getByLabel('Terminal input').waitFor();
 // Give the second real client time to receive and parse its attach history before continuing.
 await new Promise(r=>setTimeout(r,2000));
 await writeFile(`${project}/resume`, 'continue');
 await waitState('done');
 await new Promise(r=>setTimeout(r,1000));
 await app.screenshot('joined-terminal-after-title');
 await browser.evaluate(() => {const w=document.querySelector<HTMLIFrameElement>('#joining-client')!.contentWindow!; w.addEventListener('copy', (e: ClipboardEvent)=>{w.document.body.dataset.copied=e.clipboardData?.getData('text/plain')??'';},{once:true});return null;});
 await other.getByLabel('Terminal input').focus();
 await browser.keyboard.press('Control+Shift+A'); await browser.keyboard.press('Control+Shift+C');
 const text = await browser.evaluate(()=>document.querySelector<HTMLIFrameElement>('#joining-client')!.contentDocument!.body.dataset.copied??'');
 expect(text).toContain('ready');
 expect(text).not.toContain('progress');
});
