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

test("Escape discards font drafts and closes Settings when clean", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("demo");
  const thread = await t3.thread({ project, title: "Typography Escape", messages: ["Start"] });
  await t3.open(thread);
  const settle = () => browser.evaluate(async () => {
    for (let frame = 0; frame < 4; frame++) await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
    await Promise.all(document.getAnimations().map(animation => animation.finished.catch(() => {})));
    for (let frame = 0; frame < 4; frame++) await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
  });
  const results: Record<string, boolean> = {};
  const inSettings = () => browser.evaluate(() => location.pathname.includes("/settings/"));
  await t3.open("/settings/appearance");
  await screen.getByRole("textbox", "Interface font family").waitFor();
  await browser.evaluate(() => { (document.activeElement as HTMLElement)?.blur(); });
  await browser.keyboard.press("Escape");
  await settle();
    await app.screenshot("control-body-escape");
  results.bodyCloses = !(await inSettings());
  for (const title of ["Interface font", "Monospace font"]) {
    await t3.open("/settings/appearance");
    const field = screen.getByRole("textbox", `${title} family`);
    await field.tap();
    await browser.keyboard.press("Escape");
    await settle();
    await app.screenshot(`${title}-unchanged-escape`);
    results[`${title} clean closes`] = !(await inSettings());
    await t3.open("/settings/appearance");
    await field.tap();
    await field.fill("Georg");
    await browser.keyboard.press("Escape");
    await settle();
    await app.screenshot(`${title}-draft-discarded`);
    results[`${title} draft discarded without closing`] = await browser.evaluate((label) => {
      const input = document.querySelector<HTMLInputElement>(`input[aria-label="${label} family"]`);
      return location.pathname.includes("/settings/") && input?.value === "";
    }, title);
    await browser.keyboard.press("Escape");
    await settle();
    await app.screenshot(`${title}-second-escape`);
    results[`${title} second closes`] = !(await inSettings());
    await browser.keyboard.press("Escape");
    await settle();
    await app.screenshot(`${title}-third-escape`);
  }
  expect(results).toEqual({ bodyCloses: true, "Interface font clean closes": true, "Interface font draft discarded without closing": true, "Interface font second closes": true, "Monospace font clean closes": true, "Monospace font draft discarded without closing": true, "Monospace font second closes": true });
});
