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

test("Usage view changes remeasure the scrollbar", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("Scrollbar demo");
  await t3.thread({ project, title: "Synthetic usage", messages: ["first"] });
  await browser.setViewport({ width: 1100, height: 800 });
  await t3.open("/usage");
  const metrics = () => browser.evaluate(() => {
    const viewport = [...document.querySelectorAll<HTMLElement>('[data-slot="scroll-area-viewport"]')].find(el => el.closest('[role="dialog"]')) ?? [...document.querySelectorAll<HTMLElement>('[data-slot="scroll-area-viewport"]')].at(-1)!;
    const root = viewport.parentElement!;
    const thumb = root.querySelector<HTMLElement>('[data-slot="scroll-area-thumb"]');
    return { height: viewport.clientHeight, content: viewport.scrollHeight, overflow: viewport.hasAttribute('data-has-overflow-y'), thumb: thumb?.getBoundingClientRect().height ?? 0 };
  });
  await screen.getByRole("button", "Cost", { exact: true }).tap();
  await screen.getByRole("heading", "Daily cost", { exact: true }).waitFor({ state: "visible" });
  await browser.mouse.move(1000, 400);
  await browser.mouse.wheel(0, 250);
  await browser.mouse.wheel(0, -250);
  await app.screenshot("cost-initial");
  await screen.getByRole("button", "Limits", { exact: true }).tap();
  await screen.getByText("No provider on the selected environments reports subscription limits.").waitFor({ state: "visible" });
  await browser.mouse.move(1000, 400);
  await app.screenshot("limits-after-cost");
  const limits = await metrics();
  await screen.getByRole("button", "Cost", { exact: true }).tap();
  await browser.mouse.move(1000, 400);
  await app.screenshot("cost-restored");
  const cost = await metrics();
  await screen.getByRole("button", "Tokens", { exact: true }).tap();
  await browser.mouse.move(1000, 400);
  await browser.mouse.wheel(0, 250);
  await browser.mouse.wheel(0, -250);
  await app.screenshot("tokens");
  await screen.getByRole("button", "Limits", { exact: true }).tap();
  await browser.mouse.move(1000, 400);
  await app.screenshot("limits-after-tokens");
  const limitsAgain = await metrics();
  expect(limits.overflow).toBe(false);
  expect(limitsAgain.overflow).toBe(false);
  expect(cost.overflow).toBe(cost.content > cost.height);
});
