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

const PROBE = String.raw`import { writeFileSync } from 'node:fs';
const logs = {legacy: [], sgr: [], disabled: []};
let phase = 'legacy';
process.stdin.setRawMode(true);
function draw() {
  writeFileSync('mouse-results.json', JSON.stringify({cols: process.stdout.columns, phase, logs}));
  let out = '\x1b[2J\x1b[HLEGACY MOUSE BYTE FIDELITY — real PTY stdin hex\r\n';
  out += 'Click targets: row 4 / columns 4, 96, 99, 128\r\n';
  out += 'Expected legacy presses: 1b5b4d202424 / 1b5b4d208024 / 1b5b4d208324 / 1b5b4d20a024\r\n';
  out += '\r\n';
  for (const name of ['legacy','sgr','disabled']) out += name.toUpperCase() + ': ' + logs[name].join(' | ') + '\r\n';
  out += 'Mode: ' + phase + '   Terminal columns: ' + process.stdout.columns;
  process.stdout.write(out + '\x1b[1;2H');
}
process.stdin.on('data', chunk => {
  const text = chunk.toString('latin1');
  for (const part of text.split(/(s|d|\x1b\[\?\d+;\d\$y)/)) {
    if (!part) continue;
    if (/^\x1b\[\?/.test(part)) {writeFileSync('mode-ready', phase); continue;}
    if (part === 's') {phase='sgr'; process.stdout.write('\x1b[?1006h\x1b[?1006$p');}
    else if (part === 'd') {phase='disabled'; process.stdout.write('\x1b[?1000l\x1b[?1006l\x1b[?1000$p');}
    else logs[phase].push(Buffer.from(part, 'latin1').toString('hex'));
  }
  draw();
});
process.stdout.write('\x1b[?1005l\x1b[?1006l\x1b[?1015l\x1b[?1000h\x1b[?1000$p');
draw();
`;

test('Legacy mouse coordinates reach the real PTY byte for byte', WEB, async ({t3, app, screen, browser}) => {
  const project = await t3.project('mouse-proof', {'probe.mjs': PROBE});
  const thread = await t3.thread({project, title: 'Mouse byte fidelity', messages: ['hello']});
  const read = async (file: string) => readFile(`${project}/${file}`, 'utf8').catch(() => '');
  await t3.open(thread);
  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(`'${process.execPath}' probe.mjs`);
  await browser.keyboard.press('Enter');
  await expect.poll(() => read('mode-ready')).toBe('legacy');
  const grid = await browser.evaluate(() => {
    const input = document.querySelector('textarea[aria-label="Terminal input"]') as HTMLTextAreaElement;
    const canvas = input.parentElement!.querySelector('canvas')!;
    const bounds = canvas.getBoundingClientRect();
    return {left: bounds.left, top: bounds.top, width: parseFloat(input.style.left) - 4, height: parseFloat(input.style.height), origin: parseFloat(input.style.top)};
  });
  const click = async (col: number) => {
    await browser.mouse.move(grid.left + 4 + (col - 0.5)*grid.width, grid.top + grid.origin + 3.5*grid.height);
    await browser.mouse.down();
    await browser.mouse.up();
  };
  for (const col of [4,96,99,128]) await click(col);
  await browser.keyboard.type('s');
  await expect.poll(() => read('mode-ready')).toBe('sgr');
  for (const col of [4,96,99,128]) await click(col);
  await browser.keyboard.type('d');
  await expect.poll(() => read('mode-ready')).toBe('disabled');
  for (const col of [4,96,99,128]) await click(col);
  await browser.keyboard.type('Hello');
  await expect.poll(async () => JSON.parse(await read('mouse-results.json')).logs.disabled.join('').includes('48656c6c6f')).toBe(true);
  await app.screenshot('mouse-byte-results');
  const result = JSON.parse(await read('mouse-results.json'));
  expect(result.logs.legacy.join('')).toBe('1b5b4d2024241b5b4d2324241b5b4d2080241b5b4d2380241b5b4d2083241b5b4d2383241b5b4d20a0241b5b4d23a024');
  expect(result.logs.sgr.join('')).toBe([4,96,99,128].map(col => Buffer.from(`\x1b[<0;${col};4M\x1b[<0;${col};4m`).toString('hex')).join(''));
  expect(result.logs.disabled.join('')).toBe(Buffer.from('Hello').toString('hex'));
});
