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

test("Usage chart keeps its screen-reader caption hidden in Firefox", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Usage demo");
  await t3.open("/usage");
  await screen.getByRole("button", "Tokens", { exact: true }).tap();
  await browser.locator("caption").waitFor({ state: "attached" });
  // Static rendering proof: capture only after two identical frames 500ms apart.
  await browser.evaluate(() => document.fonts.ready.then(() => true));
  let previous = await app.screenshot("settling");
  for (let attempt = 0; attempt < 20; attempt++) {
    await setTimeout(500);
    const current = await app.screenshot("usage-tokens-30-days");
    if ((await readFile(previous)).equals(await readFile(current))) break;
    previous = current;
    if (attempt === 19) throw new Error("Chart did not settle");
  }
  const captionPaintedOnTop = await browser.evaluate(() => {
    const caption = document.querySelector("caption");
    if (!caption) throw new Error("Usage chart caption is missing");
    const r = caption.getBoundingClientRect();
    const top = document.elementFromPoint(r.x + r.width / 2, r.y + r.height / 2);
    return top === caption || caption.contains(top);
  });
  expect(captionPaintedOnTop).toBe(false);
});
