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

test("Restore device defaults includes and resets Font smoothing", WEB, async ({ t3, app, screen, browser }) => {
  await browser.addInitScript(() => Object.defineProperty(navigator, "platform", { get: () => "MacIntel" }));
  const capture = async (label: string) => {
    await browser.evaluate(async () => {
      await new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
      await Promise.all(document.getAnimations().map(a => a.finished.catch(() => {})));
    });
    await app.screenshot(label);
  };
  await t3.project("settings-demo");
  await t3.open("/settings/appearance");
  const advanced = () => browser.locator('#typography button').filter({ hasText: "Advanced" });
  await advanced().tap();
  await screen.getByRole("switch", "Font smoothing", { exact: true }).tap();
  await capture("font-smoothing-disabled");
  await t3.open("/settings/general");
  await screen.getByRole("switch", "In-app notifications", { exact: true }).waitFor();
  await capture("only-font-smoothing-changed");
  const enabledWhenOnlyChange = await browser.evaluate(() => {
    const button = Array.from(document.querySelectorAll("button")).find(b => b.textContent?.includes("Restore device defaults"));
    return button !== undefined && !button.disabled;
  });
  await screen.getByRole("switch", "In-app notifications", { exact: true }).tap();
  await screen.getByRole("button", "Restore device defaults", { exact: true }).tap();
  await screen.getByRole("alertdialog").waitFor();
  await capture("restore-confirmation");
  const includesFontSmoothing = await browser.evaluate(() => document.querySelector('[role="alertdialog"]')?.textContent?.includes("Font smoothing") ?? false);
  await screen.getByRole("alertdialog").getByRole("button", "Confirm", { exact: true }).tap();
  await t3.open("/settings/appearance");
  await advanced().tap();
  await screen.getByRole("switch", "Font smoothing", { exact: true }).waitFor();
  await screen.getByRole("switch", "Font smoothing", { exact: true }).scrollIntoView();
  await capture("font-smoothing-after-restore");
  const restored = await browser.evaluate(() => document.querySelector('[role="switch"][aria-label="Font smoothing"]')?.getAttribute("aria-checked") === "true");
  expect({ enabledWhenOnlyChange, includesFontSmoothing, restored }).toEqual({ enabledWhenOnlyChange: true, includesFontSmoothing: true, restored: true });
});
