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

test("Inline machine load fits at 20px interface font size", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo");
  const input = { project, title: "Machine load layout", model: "showcase", messages: ["Start"] };
  let thread;
  for (let attempt = 0; attempt < 4; attempt++) {
    try {
      thread = await t3.thread(input);
      break;
    } catch (error) {
      if (!String(error).includes("not advertised") || attempt === 3) throw error;
    }
  }
  if (!thread) throw new Error("Replay thread was not created");
  await t3.open("/settings/appearance");
  await screen.getByLabel("Interface font size", { exact: true }).tap();
  await screen.getByRole("option", "20 px", { exact: true }).tap();
  await browser.keyboard.press("Tab");
  await screen.getByRole("button", /^Thread details: \d+ of \d+ on$/).tap();
  await screen.getByRole("menuitemcheckbox", "Machine load", { exact: true }).tap();
  await browser.keyboard.press("Escape");
  await t3.open(thread);
  await screen.getByRole("region", "Machine load", { exact: true }).waitFor();
  await browser.locator("pre").filter({ hasText: "clamp(12" }).waitFor();
  await screen.getByText(/^Syncing messages/).waitFor({ state: "hidden" });
  await browser.evaluate(() => document.fonts.ready.then(() => null));
  await app.screenshot("machine-load-20px");
  const layout = await browser.evaluate(() => {
    const section = document.querySelector('section[aria-label="Machine load"]')!;
    const rows = [...section.querySelectorAll<HTMLElement>('[tabindex="0"]')];
    return {
      fontSize: getComputedStyle(document.documentElement).fontSize,
      rows: rows.map(row => {
        const label = row.children[0] as HTMLElement;
        const value = row.children[2] as HTMLElement;
        return { label: label.textContent, labelFits: label.scrollWidth <= label.clientWidth,
          valueFits: value.getBoundingClientRect().height <= parseFloat(getComputedStyle(value).lineHeight) + 1 };
      }),
    };
  });
  console.log(JSON.stringify(layout));
  expect(layout.fontSize).toBe("20px");
  expect(layout.rows.length).toBe(3);
  expect(layout.rows.every(row => row.labelFits && row.valueFits)).toBe(true);
});
