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

test("File previews restore reading positions after file and thread switches", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Reading", {
    "long.ts": Array.from({length: 5000}, (_, i) => `export const entry${i + 1} = "Reading line ${i + 1}";`).join("\n"),
    "data.csv": "id,description\n" + Array.from({length: 10000}, (_, i) => `${i + 1},Reading row ${i + 1}`).join("\n"),
    "nb.ipynb": JSON.stringify({nbformat: 4, nbformat_minor: 5, metadata: {language_info: {name: "python"}}, cells: Array.from({length: 60}, (_, i) => ({cell_type: "markdown", metadata: {}, source: [`# Reading cell ${i + 1}\n`, "Notebook reading text. ".repeat(20)]}))}),
  });
  const other = await t3.project("Other");
  const a = await t3.thread({project, title: "Chat A", messages: ["Start"]});
  await t3.thread({project: other, title: "Chat B", messages: ["Start"]});
  await browser.setViewport({width: 1440, height: 1000});
  await t3.open(a);
  await screen.getByText("first fixture turn complete", {exact: false}).waitFor();
  await screen.getByRole("button", "Toggle right panel").tap();
  await screen.getByText("Files", {exact: true}).tap();
  const open = async (name: string) => {
    await browser.evaluate(async (name) => {
      for (let i = 0; i < 600; i++) {
        for (const host of document.querySelectorAll("*")) {
          const row = host.shadowRoot?.querySelector<HTMLElement>(`[data-item-path="${name}"]`);
          if (row) { row.click(); return null; }
        }
        await new Promise(r => requestAnimationFrame(r));
      }
      throw new Error(`File tree row unavailable: ${name}`);
    }, name);
  };
  const switchTo = (name: string) => screen.getByRole("button", name, {exact: false}).tap();
  const position = (kind: string, top?: number) => browser.evaluate(async ({kind, top}) => {
    let node: HTMLElement | null = null;
    if (kind === "code") node = document.querySelector(".file-preview-virtualizer");
    else if (kind === "notebook") node = document.querySelector('[aria-label="Cell 1"]')?.closest(".scrollbar-gutter-both") ?? null;
    else {
      let current = document.querySelector("[data-preview-row]")?.parentElement;
      while (current) {
        if (getComputedStyle(current).overflowY === "auto") { node = current; break; }
        current = current.parentElement;
      }
    }
    if (!node) return -1;
    if (top !== null) node.scrollTop = top;
    await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
    return node.scrollTop;
  }, {kind, top: top ?? null});
  // Collect all outcomes before asserting so the base captures all three regressions.
  const outcomes: Record<string, boolean> = {};
  await open("long.ts");
  await browser.locator(".file-preview-virtualizer").waitFor();
  await position("code", 25000);
  await app.screenshot("code-before-thread-switch");
  await switchTo("Chat B");
  await switchTo("Chat A");
  await browser.locator(".file-preview-virtualizer").waitFor();
  await browser.evaluate(() => new Promise<null>(r => setTimeout(() => r(null), 3000)));
  outcomes.code = Math.abs((await position("code")) - 25000) < 100;
  await app.screenshot("code-after-thread-switch");

  await open("data.csv");
  await browser.locator("[data-preview-row]").first().waitFor();
  await browser.evaluate(() => new Promise<null>(r => setTimeout(() => r(null), 3000)));
  await position("table", 60000);
  await browser.evaluate(() => new Promise<null>(r => setTimeout(() => r(null), 3000)));
  if (Math.abs((await position("table")) - 60000) > 100) throw new Error("CSV did not reach the requested starting offset");
  await app.screenshot("csv-before-file-switch");
  await open("long.ts");
  await browser.locator(".file-preview-virtualizer").waitFor();
  await open("data.csv");
  await browser.locator("[data-preview-row]").first().waitFor();
  await browser.evaluate(() => new Promise<null>(r => setTimeout(() => r(null), 3000)));
  outcomes.csv = Math.abs((await position("table")) - 60000) < 100;
  await app.screenshot("csv-after-file-switch");

  await open("nb.ipynb");
  await screen.getByRole("button", "Show more cells", {exact: false}).tap();
  await browser.locator('[aria-label="Cell 38"]').waitFor({state: "attached"});
  const notebookTop = await browser.evaluate(() => {
    const cell = document.querySelector<HTMLElement>('[aria-label="Cell 38"]')!;
    const node = cell.closest<HTMLElement>(".scrollbar-gutter-both")!;
    node.scrollTop += cell.getBoundingClientRect().top - node.getBoundingClientRect().top;
    return node.scrollTop;
  });
  await position("notebook");
  await app.screenshot("notebook-before-thread-switch");
  await switchTo("Chat B");
  await switchTo("Chat A");
  await browser.locator('[aria-label="Cell 1"]').waitFor({state: "attached"});
  await browser.evaluate(() => new Promise<null>(r => setTimeout(() => r(null), 3000)));
  outcomes.notebook = Math.abs((await position("notebook")) - notebookTop) < 100 && await browser.evaluate(() => !!document.querySelector('[aria-label="Cell 38"]'));
  await app.screenshot("notebook-after-thread-switch");
  expect(outcomes).toEqual({code: true, csv: true, notebook: true});
});
