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

test("TSV page boundaries preserve a literal BOM and quotes", WEB, async ({ t3, app, screen, browser }) => {
  const filler = Array.from({length: 80000}, (_, n) => `row${n}\tvalue${n}\n`).join("");
  const special = '\uFEFF"kept"\tlast\n';
  const project = await t3.project("TSV preview", {
    "nobom.tsv": "a\tb\n".repeat(32) + special + filler,
    "withbom.tsv": '\uFEFF"header"\tvalue\n' + "a\tb\n".repeat(31) + special + filler,
  });
  const thread = await t3.thread({project, title: "TSV page boundary", messages: ["Start"]});
  await browser.setViewport({width:1440,height:1000});
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByRole("button", "Files F").tap();
  const observed: {file:string; cell:string|null; header:string|null}[] = [];
  for (const file of ["nobom.tsv", "withbom.tsv"]) {
    await screen.getByRole("treeitem", file).tap();
    await screen.getByRole("table", file).waitFor({timeout:60000});
    await screen.getByText("80,032 rows · 2 columns", {exact:false}).waitFor({timeout:60000});
    await browser.evaluate((file) => {
      const table = document.querySelector(`[role="table"][aria-label="${file}"]`)!;
      const scroller = table.querySelector<HTMLElement>('[tabindex="0"]')!;
      scroller.scrollTop = 29 * 26;
      return null;
    }, file);
    const cell = browser.locator(`[role="table"][aria-label="${file}"] [data-preview-row="32"] [role="cell"][aria-colindex="1"]`);
    await cell.waitFor();
    await screen.getByText("last", {exact:true}).waitFor();
    await app.screenshot(file.replace(".tsv", "") + "-record-33");
    observed.push(await browser.evaluate((file) => {
      const table = document.querySelector(`[role="table"][aria-label="${file}"]`)!;
      return {file, cell: table.querySelector('[data-preview-row="32"] [role="cell"]')?.textContent ?? null,
        header: table.querySelector('[role="columnheader"]')?.textContent ?? null};
    }, file));
  }
  expect(observed).toEqual([
    {file:"nobom.tsv", cell:'\uFEFF"kept"', header:"a"},
    {file:"withbom.tsv", cell:'\uFEFF"kept"', header:"header"},
  ]);
});
