/// <reference lib="dom" />
import { expect } from "e2e";

import { test, WEB } from "./t3.ts";

// Logs above 64 MiB use the streamed preview. Keep the lines under review near the front.
const log = Array.from({ length: 1_200_000 }, (_, line) =>
  `Entry ${String(line + 1).padStart(7, "0")}: Synthetic diagnostic log message for reading position verification.\n`,
).join("");

test(
  "A large log opened at a cited line keeps its reading position when switching file tabs",
  WEB,
  async ({ t3, app, browser, screen }) => {
    const project = await t3.project("demo", { "big.log": log, "small.txt": "Review notes" });
    const thread = await t3.thread({
      project,
      title: "Review the log",
      messages: ['See :codex-file-citation{path="big.log" line_range_start="5000"}'],
    });
    await t3.open(thread);
    await browser.locator("button").filter({ hasText: "See :codex-file-citation" }).tap();
    await screen.getByRole("link", /^big\.log/).tap();
    const row = (index: number, text: string) =>
      browser.locator(`[data-preview-row="${index}"]`).filter({ hasText: text });
    await row(4999, "Entry 0005000:").waitFor({ timeout: 120_000 });

    await screen.getByText(/1,200,000 lines ·/).waitFor({ timeout: 120_000 });
    const point = await browser.evaluate(() => {
      const box = document.querySelector('[data-preview-row="4999"]')!
        .closest<HTMLElement>(".overflow-auto")!.getBoundingClientRect();
      return { x: box.left + box.width / 2, y: box.top + 150 };
    });
    await browser.mouse.move(point.x, point.y);
    await browser.mouse.wheel(0, 6000);
    await browser.evaluate(async () => {
      const scroller = document.querySelector("[data-preview-row]")!.closest<HTMLElement>(".overflow-auto")!;
      let previous = -1, stable = 0;
      while (stable < 15) {
        await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
        stable = previous === scroller.scrollTop ? stable + 1 : 0;
        previous = scroller.scrollTop;
      }
      return null;
    });
    const firstVisibleLine = () =>
      browser.evaluate(() => {
        const scroller = document
          .querySelector("[data-preview-row]")
          ?.closest<HTMLElement>(".overflow-auto");
        if (!scroller) return null;
        const bounds = scroller.getBoundingClientRect();
        const first = Array.from(scroller.querySelectorAll<HTMLElement>("[data-preview-row]")).find(
          (row) => row.getBoundingClientRect().bottom > bounds.top + 1,
        );
        return first ? Number(first.dataset.previewRow) + 1 : null;
      });
    const readingLine = await firstVisibleLine();
    if (readingLine === null || readingLine <= 5000) throw new Error("Wheel did not move past the citation");
    await app.screenshot("log-reading-before-tab-switch");

    await browser.keyboard.press("Control+p");
    await screen.getByPlaceholder("Search files…").fill("small.txt");
    await screen.getByRole("option", "small.txt", { exact: false }).tap();
    await screen.getByRole("button", "big.log", { exact: true }).tap();
    await screen.getByText(/1,200,000 lines ·/).waitFor({ timeout: 120_000 });
    try {
      await expect.poll(firstVisibleLine).toBe(readingLine);
    } finally {
      await app.screenshot("log-position-after-switching-back");
    }
  },
);
