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

const TABLE = '| Key | Pair | Note |\n| --- | --- | --- |\n| A1 | B1 | C1 |\n| A2 | B2 | C2 |';

test('Copying a partial Markdown table preserves all selected cells and columns', WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project('table-copy');
  const source = await t3.thread({ project, title: 'Original table', messages: [TABLE] });
  await t3.open(source);
  await screen.getByRole('button', /^Agent/).tap();
  await browser.locator('[data-user-message-body] td').filter({ hasText: 'C2' }).waitFor();
  await browser.evaluate(() => {
    const cells = [...document.querySelectorAll('[data-user-message-body] td')];
    const start = cells.find(cell => cell.textContent === 'B1')!;
    const end = cells.find(cell => cell.textContent === 'C2')!;
    const range = document.createRange();
    const firstText = (el: Element) => document.createTreeWalker(el, NodeFilter.SHOW_TEXT).nextNode()!;
    const a = firstText(start), b = firstText(end);
    range.setStart(a, 0); range.setEnd(b, b.textContent!.length);
    window.getSelection()!.removeAllRanges(); window.getSelection()!.addRange(range);
    document.addEventListener('copy', event => {
      Object.assign(window, { tableClipboard: { plain: event.clipboardData!.getData('text/plain'), html: event.clipboardData!.getData('text/html') } });
    });
    return null;
  });
  await app.screenshot('selected-five-cells');
  await browser.keyboard.press('ControlOrMeta+c');
  const copied = await browser.evaluate(() => (window as any).tableClipboard as { plain: string; html: string });
  const pasted = await t3.thread({ project, title: 'Pasted table', messages: [copied.plain] });
  await t3.open(pasted);
  await screen.getByRole('button', /^Agent/).tap();
  await browser.locator('[data-user-message-body] table').waitFor();
  await app.screenshot('pasted-partial-table');
  const rendered = await browser.evaluate(() => [...document.querySelectorAll('[data-user-message-body] tr')].map(row => [...row.querySelectorAll('th,td')].map(cell => cell.textContent?.trim())));
  expect(rendered, 'Pasted Markdown retains C2 and the empty A1 placeholder').toEqual([['', 'B1', 'C1'], ['A2', 'B2', 'C2']]);
  const htmlRows = await browser.evaluate(html => [...new DOMParser().parseFromString(html, 'text/html').querySelectorAll('tr')].map(row => [...row.querySelectorAll('th,td')].map(cell => cell.textContent?.trim())), copied.html);
  expect(htmlRows, 'Rich HTML keeps B1/C1 above B2/C2').toEqual([['', 'B1', 'C1'], ['A2', 'B2', 'C2']]);
});
