/// <reference lib="dom" />
import { expect } from "e2e";
import { readFile, writeFile } from "node:fs/promises";
import { test, WEB } from "./t3.ts";

const probe = String.raw`import { writeFileSync, existsSync } from 'node:fs';
process.stdout.write('\x1b[2J\x1b[H');
process.stdout.write('\x1b]0;' + '\u2500'.repeat(200000) + '\x1b]0;Build', () => {
  writeFileSync('paused', 'yes');
  const timer = setInterval(() => {
    if (!existsSync('continue')) return;
    clearInterval(timer);
    process.stdout.write('progress\x07ready\r\n', () => { writeFileSync('done', 'yes'); process.exit(0); });
  }, 50);
});`;

test('A terminal reconnect during an unfinished title hides its continuation', WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project('terminal-demo', { 'probe.mjs': probe });
  const thread = await t3.thread({ project, title: 'Terminal attach', messages: ['hello'] });
  await t3.open(thread);
  await screen.getByRole('button', 'Toggle terminal drawer').tap();
  const terminal = screen.getByLabel('Terminal input');
  const waitFile = async (name: string) => {
    const deadline = Date.now() + 30000;
    while (Date.now() < deadline) {
      if (await readFile(`${project}/${name}`, 'utf8').catch(() => '') === 'yes') return;
      await new Promise(resolve => setTimeout(resolve, 100));
    }
    throw new Error(`Timed out waiting for probe ${name}`);
  };
  await terminal.focus();
  await browser.keyboard.type(`unset PROMPT_COMMAND; PS1='$ '; node probe.mjs`);
  await browser.keyboard.press('Enter');
  await waitFile('paused');
  // A full reload creates a fresh terminal parser and attaches to the same running PTY.
  await browser.reload();
  await terminal.focus();
  await writeFile(`${project}/continue`, 'yes');
  await waitFile('done');
  const text = async () => {
    await browser.evaluate(() => {
      document.body.dataset.terminalCopy = '';
      window.addEventListener('copy', event => {
        document.body.dataset.terminalCopy = event.clipboardData?.getData('text/plain') ?? '';
      }, { once: true });
      return null;
    });
    await terminal.focus();
    await browser.keyboard.press('Control+Shift+A');
    await browser.keyboard.press('Control+Shift+C');
    return browser.evaluate(() => document.body.dataset.terminalCopy ?? '');
  };
  let output = '';
  const deadline = Date.now() + 15000;
  while (Date.now() < deadline) {
    output = await text();
    if (output.includes('ready')) break;
  }
  await browser.mouse.move(700, 650);
  await browser.mouse.down();
  await browser.mouse.up();
  await app.screenshot('reconnected-terminal');
  expect(output).toContain('ready');
  expect(output).not.toContain('progress');
});
