import { expect } from "e2e";

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

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

test(
  "Reopening a thread that finished while the page reloaded lands at its end without a slide",
  WEB,
  async ({ t3, app, screen, browser }) => {
    const project = await t3.project("demo", { "src/math.ts": "export const sum = 1 + 1;\n" });
    await t3.thread({ project, title: "Other work", messages: ["Hello"] });
    const longTask = await t3.thread({
      project,
      title: "Long task",
      messages: ["First", "Second", "Third"],
      model: "showcase",
    });
    await browser.setViewport({ width: 1280, height: 520 });
    await t3.open(longTask);
    const path = await browser.evaluate(() => location.pathname);

    await screen.getByRole("textbox").fill("Do the long task");
    await screen.getByRole("textbox").press("Enter");
    await expect(screen.getByRole("button", "Stop generation")).toBeVisible();
    await sleep(700);
    await app.screenshot("working-before-leave");
    await screen.getByRole("button", /^Other work,/).first().tap();
    await expect(browser).not.toHaveURL(path);
    await sleep(15_000);
    await browser.evaluate(() => {
      setTimeout(() => location.reload(), 50);
    });
    await sleep(8_000);
    await expect(screen.getByRole("button", /^Long task,/).first()).toBeVisible();
    await sleep(3_000);
    await app.screenshot("other-after-reload");

    await browser.evaluate(() => {
      const w = window as unknown as { __trace: unknown[] };
      w.__trace = [];
      const orig = Element.prototype.scrollTo;
      Element.prototype.scrollTo = function (this: Element, ...args: unknown[]) {
        if (this.classList.contains("messages-timeline-scroll"))
          w.__trace.push({ call: "scrollTo", opts: JSON.stringify(args[0]) });
        return (orig as (...a: unknown[]) => void).apply(this, args);
      };
      const start = performance.now();
      const sample = () => {
        const el = document.querySelector(".messages-timeline-scroll");
        w.__trace.push({
          t: Math.round(performance.now() - start),
          top: el ? Math.round(el.scrollTop) : null,
          max: el ? Math.round(el.scrollHeight - el.clientHeight) : null,
          working: /Working for/.test(document.body.innerText),
        });
        if (performance.now() - start < 3000) requestAnimationFrame(sample);
      };
      requestAnimationFrame(sample);
    });
    await browser.evaluate(() => {
      const row = Array.from(document.querySelectorAll<HTMLElement>('[role="button"]')).find((button) =>
        button.getAttribute("aria-label")?.startsWith("Long task,"),
      );
      if (!row) throw new Error("Long task sidebar row not found");
      row.click();
    });
    await sleep(3_200);
    await app.screenshot("settled");
    const trace = await browser.evaluate(() =>
      JSON.stringify((window as unknown as { __trace: unknown[] }).__trace),
    );
    console.log("TRACE", trace);
    const parsed = JSON.parse(trace) as Array<{ opts?: string }>;
    expect(parsed.filter((e) => e.opts?.includes("smooth")).length).toBe(0);
  },
);
