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

test("Large CR-only Markdown renders bounded chunks and copies original separators", WEB, async ({t3, app, browser, screen}) => {
  const cr = 'first\r\r# ' + 'x\r\r# '.repeat(30000) + 'end';
  const lf = cr.replaceAll('\r', '\n');
  const project = await t3.project('Markdown evidence', {'cr-only.md':cr, 'lf-only.md':lf});
  const thread = await t3.thread({project, title:'Line ending preview', messages:['See :codex-file-citation{path="cr-only.md"} and :codex-file-citation{path="lf-only.md"}']});
  await t3.open(thread);
  await screen.getByRole('button', /^Agent See/).tap();
  const observations: unknown[] = [];
  for (const name of ['lf-only.md','cr-only.md']) {
    await screen.getByRole('link', new RegExp('^'+name.replace('.','\\.'))).tap();
    if (name === 'lf-only.md') await screen.getByRole('button','Show rendered markdown').tap();
    // The preview focuses itself on pointer input; Ctrl+A is handled by the app.
    await browser.locator('.scrollbar-gutter-both').last().tap();
    await browser.keyboard.press('ControlOrMeta+A');
    await browser.evaluate(() => {
      (window as any).__copied = null;
      document.addEventListener('copy', e => { (window as any).__copied = e.clipboardData?.getData('text/plain') ?? null; }, {once:true});
      return null;
    });
    await browser.keyboard.press('ControlOrMeta+C');
    const observed = await browser.evaluate(() => {
      const roots = [...document.querySelectorAll<HTMLElement>('[tabindex="-1"]')];
      const root = roots.find(e => e.className.includes('outline-none') && e.querySelector('.scrollbar-gutter-both'));
      let chunks: any[] = [];
      if (root) {
        const key = Object.keys(root).find(k => k.startsWith('__reactFiber$'));
        let fiber = key ? (root as any)[key] : null;
        while (fiber) { if (Array.isArray(fiber.memoizedProps?.chunks)) { chunks = fiber.memoizedProps.chunks; break; } fiber = fiber.return; }
      }
      const copied = (window as any).__copied as string | null;
      return {headings: root?.querySelectorAll('h1').length ?? 0, raw: root?.querySelectorAll('pre').length ?? 0,
        chunks: chunks.length, maxChunkChars: Math.max(0,...chunks.map(c=>c.text.length)),
        copyChars: copied?.length, copyCR: copied?.split('\r').length! - 1, copyLF:copied?.split('\n').length! - 1,
        copied};
    });
    observations.push({name,...observed,copied:undefined, exactCopy:observed.copied === (name==='cr-only.md'?cr:lf)});
    await app.screenshot(name === 'cr-only.md' ? 'cr-rendered-select-all-copy' : 'lf-control-select-all-copy');
    await browser.keyboard.press('ArrowRight');
  }
  console.log('RUNTIME OBSERVATIONS',JSON.stringify(observations));
  const result = observations as any[];
  expect(result[1].headings).toBeGreaterThan(0);
  expect(result[1].raw).toBe(0);
  expect(result[1].chunks).toBeGreaterThan(1);
  expect(result[1].maxChunkChars).toBeLessThanOrEqual(131072);
  expect(result[1].exactCopy).toBe(true);
  expect(result[0].headings).toBeGreaterThan(0);
  expect(result[0].exactCopy).toBe(true);
});
