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

test("Usage keeps the hovered bucket when its period changes", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("usage-demo");
  await t3.open("/usage");
  const results: Array<{ metric: string; direction: string; marker: number | null; label: string | null }> = [];
  for (const metric of ["Cost", "Tokens"]) {
    await screen.getByRole("button", metric, { exact: true }).tap();
    await browser.keyboard.press("Control+Shift+4");
    const plot = browser.locator('svg[viewBox="0 0 960 260"]');
    await plot.waitFor();
    const point = await browser.evaluate(() => {
      const box = document.querySelector('svg[viewBox="0 0 960 260"]')!.getBoundingClientRect();
      return { x: box.left + box.width * 0.75, y: box.top + 100 };
    });
    await browser.mouse.move(point.x, point.y);
    await app.screenshot(`${metric}-90-days-hover`);
    for (const [key, direction] of [["2", "90-to-7"], ["4", "7-to-90"]]) {
      if (key === "4") {
        await browser.mouse.move(point.x - 50, point.y);
        await browser.mouse.move(point.x, point.y);
      }
      await browser.keyboard.press(`Control+Shift+${key}`);
      await browser.evaluate(() => new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))));
      await app.screenshot(`${metric}-${direction}-stationary`);
      results.push({ metric, direction, ...await browser.evaluate(() => {
        const svg = document.querySelector('svg[viewBox="0 0 960 260"]')!;
        const line = svg.querySelector('line[y1="8"][y2="260"]');
        return { marker: line ? Number(line.getAttribute("x1")) : null, label: svg.parentElement?.querySelector(":scope > div > div")?.textContent ?? null };
      }) });
    }
  }
  for (const result of results) {
    expect(result.label, `${result.metric} ${result.direction} tooltip visible`).not.toBeNull();
    expect(result.marker, `${result.metric} ${result.direction} crosshair at nearest bucket`).toBeCloseTo(result.direction === "90-to-7" ? 800 : 722.7, 0);
  }
});
