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

test("Resource History updates while Diagnostics stays open", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("Diagnostics demo");
  await t3.open();
  // Wait for pairing to finish before leaving the pairing route.
  await screen.getByText("Diagnostics demo", { exact: true }).first().textContent();
  await app.open("/settings/diagnostics");
  await screen.getByRole("heading", "Resource History", { exact: true }).textContent();
  const read = () => browser.evaluate(() => {
    const section = [...document.querySelectorAll("section")].find(s => s.querySelector("h2")?.textContent === "Resource History");
    const label = [...(section?.querySelectorAll("span") ?? [])].find(s => s.textContent === "Samples");
    const value = label?.parentElement?.nextElementSibling?.textContent?.replaceAll(",", "") ?? "";
    return { samples: /^\d+$/.test(value) ? Number(value) : -1, text: section?.textContent ?? "" };
  });
  await browser.evaluate(async () => {
    const heading = [...document.querySelectorAll("h2")].find(h => h.textContent === "Resource History");
    heading?.scrollIntoView({ block: "start" });
    await new Promise(resolve => setTimeout(resolve, 1000));
  });
  const initial = await read();
  if (initial.samples < 0 || initial.text.includes("binary was not found")) throw new Error("Native Resource History did not load");
  await app.screenshot("initial-history");
  for (let i = 0; i < 7; i++) {
    await browser.evaluate(async () => { await new Promise(resolve => setTimeout(resolve, 10_000)); });
    await read();
  }
  await app.screenshot("history-after-70-seconds");
  const final = await read();
  expect(final.samples).toBeGreaterThan(initial.samples);
});
