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

test("Sending a draft's first message preserves the sidebar scroll position", WEB, async ({ t3, app, screen, browser }) => {
  await browser.setViewport({ width: 1280, height: 640 });
  const project = await t3.project("Sidebar demo");
  let thread;
  for (let i = 1; i <= 24; i++) {
    thread = await t3.thread({ project, title: `Earlier work ${String(i).padStart(2, "0")}`, messages: ["Prepare a short note"], model: "multi-turn" });
  }
  await t3.open(thread!);
  await screen.getByRole("button", "New thread", { exact: true }).tap();
  await screen.getByRole("textbox").fill("Explain the sidebar scroll behavior");
  const readScroll = () => browser.evaluate(() => {
    const row = document.querySelector('[data-sidebar-row]');
    const viewport = row?.closest('[data-slot="scroll-area-viewport"]') as HTMLElement | null;
    if (!viewport) throw new Error("Sidebar scroll viewport missing");
    return { top: viewport.scrollTop, range: viewport.scrollHeight - viewport.clientHeight };
  });
  await browser.evaluate(() => {
    document.querySelector('[data-sidebar-row]')?.closest('[data-slot="scroll-area-viewport"]')?.scrollTo({ top: 0, behavior: "instant" });
  });
  const initial = await readScroll();
  if (initial.range < 100) throw new Error("Fixture did not overflow the sidebar");
  await app.screenshot("before-first-send");
  await screen.getByRole("textbox").press("Enter");
  // Allow the real promotion and browser's smooth row reveal to finish before measuring.
  await browser.evaluate(() => new Promise<void>((resolve) => setTimeout(resolve, 1800)));
  await app.screenshot("after-first-send");
  expect((await readScroll()).top).toBe(initial.top);
});
