import { readFile } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Clicking empty timeline padding keeps following a streaming reply", WEB, async ({ t3, app, screen, browser }) => {
  await browser.setViewport({ width: 840, height: 620 });
  const project = await t3.project("scroll-demo", { "src/math.ts": "export const sum = 1 + 1;\n" });
  await t3.thread({ project, title: "Streaming scroll demonstration", model: "showcase", messages: ["Tour one", "Tour two", "Tour three", "Tour four", "Tour five", "Tour six"] });
  await t3.open();
  await screen.getByRole("button", "Streaming scroll demonstration, Done, scroll-demo", { exact: true }).press("Enter");
  await browser.locator(".messages-timeline-scroll").waitFor();
  await browser.evaluate(() => {
    const node = document.querySelector<HTMLElement>(".messages-timeline-scroll")!;
    node.scrollTop = node.scrollHeight;
    node.dispatchEvent(new Event("scroll"));
  });
  const follow = screen.getByRole("button", "Scroll to end", { exact: false });
  if (await follow.isVisible()) await follow.tap();
  await screen.getByRole("textbox").fill("Seventh tour: keep the latest output in view");
  await screen.getByRole("textbox").press("Enter");
  const stop = screen.getByRole("button", "Stop generation");
  await stop.waitFor({ state: "visible" });
  const point = await browser.evaluate(() => {
    const node = document.querySelector<HTMLElement>(".messages-timeline-scroll")!;
    const rect = node.getBoundingClientRect();
    for (let x = rect.left + 24; x < rect.right - 24; x += 12) {
      for (let y = rect.top + 60; y < rect.bottom - 60; y += 12) {
        if (document.elementFromPoint(x, y) === node) return { x, y };
      }
    }
    throw new Error("No empty timeline padding found");
  });
  await browser.mouse.move(point.x, point.y);
  await browser.mouse.down();
  await browser.mouse.up();
  await app.screenshot("after-padding-click-streaming");
  await stop.waitFor({ state: "hidden", timeout: 90000 });
  await browser.evaluate(() => { (document.activeElement as HTMLElement)?.blur(); });
  let stable = false;
  for (let attempt = 0; attempt < 6; attempt++) {
    const first = await app.screenshot("finished-stability-a");
    await new Promise(resolve => setTimeout(resolve, 500));
    const second = await app.screenshot("finished-stability-b");
    if ((await readFile(first)).equals(await readFile(second))) { stable = true; break; }
  }
  if (!stable) throw new Error("Final view did not settle for capture");
  await app.screenshot("finished-after-padding-click");
  await expect(follow).toBeHidden();
  await expect.poll(() => browser.evaluate(() => {
    const node = document.querySelector<HTMLElement>(".messages-timeline-scroll")!;
    return node.scrollHeight - node.clientHeight - node.scrollTop;
  })).toBeLessThan(8);
});
