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

const source = String.raw`{\rtf1\ansi A\zwj B\zwnj C\ltrmark D\rtlmark E}`;
async function sidecar(dir: string): Promise<string | null> {
  for (const entry of await readdir(dir, { withFileTypes: true })) {
    const path = join(dir, entry.name);
    if (entry.isDirectory()) { const found = await sidecar(path); if (found !== null) return found; }
    else if (entry.name.endsWith('.rtf.txt') && !entry.name.startsWith('pending-')) return readFile(path, 'utf8');
  }
  return null;
}
test("Fresh RTF attachment preserves named joiners and direction marks", WEB, async ({t3, app, browser, screen}) => {
  const project = await t3.project("RTF proof");
  const thread = await t3.thread({project, title: "RTF named controls", messages: ["Ready for attachment"]});
  await t3.open(thread);
  await screen.getByRole('textbox').fill('Inspect the attached RTF.');
  await browser.evaluate((rtf) => {
    const input = document.querySelector<HTMLInputElement>('input[type="file"]')!;
    const data = new DataTransfer();
    data.items.add(new File([rtf], 'named-controls.rtf', {type: 'application/rtf'}));
    input.files = data.files;
    input.dispatchEvent(new Event('change', {bubbles: true}));
  }, source);
  await screen.getByRole('button', 'Submit message', {exact: true}).tap();
  // Wait for extraction, independent of the characters under investigation.
  let extracted: string | null = null;
  await expect.poll(async () => { extracted = await sidecar(T3_HOME); return extracted !== null; }).toBe(true);
  await screen.getByText('second fixture turn complete', {exact: false}).waitFor();
  await screen.getByText('Sending…', {exact: true}).waitFor({state: 'hidden'});
  const text = extracted!.trim();
  const points = Array.from(text).map(c => `U+${c.codePointAt(0)!.toString(16).toUpperCase().padStart(4, '0')}`).join(' ');
  await browser.evaluate(({source, text, points}) => {
    const panel = document.createElement('section');
    panel.style.cssText = 'position:fixed;bottom:24px;left:280px;right:24px;z-index:99999;background:#101827;color:#fff;border:2px solid #94a3b8;border-radius:12px;padding:24px;font:16px/1.7 monospace;white-space:pre-wrap';
    panel.textContent = `SERVER SIDECAR INSPECTION (read from generated .rtf.txt)\n\nInput: ${source}\n\nExtracted: ${text}\nCode points:\n${points}\n\nExpected: U+0041 U+200D U+0042 U+200C U+0043 U+200E U+0044 U+200F U+0045`;
    document.body.append(panel);
  }, {source, text, points});
  await app.screenshot('rtf-sidecar-codepoints');
  expect(text).toBe('A\u200DB\u200CC\u200ED\u200FE');
});
