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

const csv = (columns: number) => [
  Array.from({ length: columns }, (_, i) => `Column ${i + 1}`),
  ...Array.from({ length: 8 }, (_, row) => Array.from({ length: columns }, (_, col) =>
    col === columns - 1 ? `"Row ${row + 1}: multiline notes\nSecond line of notes\nThird line of notes\nFinal line"` :
    col === columns - 2 ? `"${"Wide wrapped text mmmmmmmmmmm WWWWWWWWW repeated. ".repeat(6)}"` : `${row + 1}-${col + 1}`)),
].map(row => row.join(",")).join("\n");

test("CSV rows retain heights and positions across horizontal scroll and panel resize", WEB, async ({ t3, app, browser, screen }) => {
  await browser.setViewport({ width: 1440, height: 1000 });
  const project = await t3.project("CSV demo", { "wide-12.csv": csv(12), "wide-40.csv": csv(40) });
  const thread = await t3.thread({ project, title: "CSV preview", messages: [
    'Inspect :codex-file-citation{path="wide-12.csv" line_range_start="1"} and :codex-file-citation{path="wide-40.csv" line_range_start="1"}',
  ] });
  await t3.open(thread);
  await screen.getByRole("button", /^Agent Inspect/).tap();
  const results: { file: string; width: number; left: number[][]; right: number[][]; returned: number[][] }[] = [];
  const settle = () => browser.evaluate(async () => { await document.fonts.ready; await new Promise(resolve => setTimeout(resolve, 700)); });
  const geometry = () => browser.evaluate(() => Array.from(document.querySelectorAll<HTMLElement>('[role="table"] [data-preview-row]')).slice(0, 4).map(row => { const r = row.getBoundingClientRect(); return [r.height, r.top]; }));
  const scroll = (right: boolean) => browser.evaluate((right) => {
    const table = document.querySelector('[role="table"]');
    if (!table?.parentElement) throw new Error("CSV table is not mounted");
    table.parentElement.scrollTo({ left: right ? table.parentElement.scrollWidth : 0, behavior: "instant" });
  }, right);
  for (const file of ["wide-12.csv", "wide-40.csv"]) {
    await screen.getByRole("link", new RegExp(`^${file.replace('.', '\\.')}`)).tap();
    await screen.getByRole("button", "Show table").tap();
    await browser.locator('[role="table"] [data-preview-row="1"]').waitFor({ state: "visible" });
    for (const width of [1440, 1120]) {
      await browser.setViewport({ width, height: 1000 });
      await scroll(false); await settle();
      const left = await geometry();
      await app.screenshot(`${file}-${width}-left`);
      await scroll(true); await settle();
      const right = await geometry();
      await app.screenshot(`${file}-${width}-right`);
      await scroll(false); await settle();
      const returned = await geometry();
      await app.screenshot(`${file}-${width}-returned`);
      results.push({ file, width, left, right, returned });
    }
  }
  // Capture every reproduction before asserting so both videos show the identical interaction.
  const shifts = results.map(({ file, width, left, right, returned }) => ({ file, width,
    maxShift: Math.max(...left.flatMap((row, i) => row.flatMap((value, j) => [Math.abs(value - right[i]![j]!), Math.abs(value - returned[i]![j]!)]))),
  }));
  console.log(JSON.stringify({ results, shifts }));
  expect(shifts.every(result => result.maxShift <= 1)).toBe(true);
});
