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

test("Scroll to end queued in B preserves A's reading position", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Scroll reading proof");
  const messages = Array.from({ length: 10 }, (_, i) => `Reading checkpoint ${i + 1}: explain the next part of this project.`);
  const a = await t3.thread({ project, title: "Conversation A", messages });
  await t3.thread({ project, title: "Conversation B", messages });
  await t3.open(a);
  const distance = () => browser.evaluate(() => {
    const el = document.querySelector<HTMLElement>(".messages-timeline-scroll");
    if (!el) throw new Error("Timeline missing");
    return Math.round(el.scrollHeight - el.clientHeight - el.scrollTop);
  });
  const settle = () => browser.evaluate(() => new Promise<void>(resolve => {
    let count = 0;
    const frame = () => { if (++count === 90) resolve(); else requestAnimationFrame(frame); };
    requestAnimationFrame(frame);
  }));
  const switchTo = (name: string) => screen.getByRole("button", name, { exact: false }).tap();
  await settle();
  await screen.getByTestId("composer-editor").tap();
  await screen.getByTestId("composer-editor").press("PageUp");
  await settle();
  const aDistance = await distance();
  if (aDistance < 100) throw new Error(`A did not scroll up: ${aDistance}`);
  await switchTo("Conversation B");
  await settle();
  await screen.getByTestId("composer-editor").tap();
  await screen.getByTestId("composer-editor").press("PageUp");
  await screen.getByTestId("composer-editor").press("PageUp");
  await settle();
  const bDistance = await distance();
  if (bDistance < 100) throw new Error(`B did not scroll up: ${bDistance}`);
  for (const name of ["Conversation A", "Conversation B", "Conversation A", "Conversation B"]) {
    await switchTo(name);
    await settle();
    const expected = name === "Conversation A" ? aDistance : bDistance;
    if (Math.abs(await distance() - expected) > 10) throw new Error("Control did not restore reading position");
  }
  await app.screenshot("before-race-B-reading");
  await browser.evaluate(() => new Promise<void>((resolve, reject) => requestAnimationFrame(() => {
    const end = document.querySelector<HTMLButtonElement>("[data-scroll-to-end]");
    const a = [...document.querySelectorAll<HTMLElement>('[data-sidebar-row]')].find(el => el.textContent?.includes("Conversation A") && !el.textContent?.includes("Conversation B"));
    if (!end || !a) { reject(new Error("Race controls missing")); return; }
    end.click();
    a.click();
    resolve();
  })));
  await settle();
  await app.screenshot("A-after-B-scroll-to-end-and-immediate-switch");
  await expect.poll(distance).toBeGreaterThan(aDistance - 10);
});
