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

test("Enter saves retention days and keeps keyboard focus", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("retention-focus");
  await t3.open("/settings/maintenance");
  const focus = () => browser.evaluate(() => ({
    tag: document.activeElement?.tagName,
    label: document.activeElement?.getAttribute("aria-label"),
    value: (document.activeElement as HTMLInputElement)?.value ?? null,
  }));
  await screen.getByRole("switch", "Delete old browser artifacts", { exact: true }).tap();
  const artifacts = screen.getByLabel("Delete old browser artifacts in days", { exact: true });
  await artifacts.scrollIntoView();
  await artifacts.fill("14");
  await artifacts.press("Enter");
  await app.screenshot("artifacts-14-after-enter");
  const first = await focus();
  await screen.getByRole("switch", "Delete old rotated logs", { exact: true }).tap();
  const logs = screen.getByLabel("Delete old rotated logs in days", { exact: true });
  await logs.scrollIntoView();
  await logs.fill("14");
  await logs.press("Enter");
  await app.screenshot("logs-14-after-enter");
  const second = await focus();
  await artifacts.fill("21");
  await artifacts.press("Enter");
  await app.screenshot("artifacts-21-after-enter");
  const third = await focus();
  await t3.open("/settings/maintenance");
  await artifacts.waitFor();
  await logs.scrollIntoView();
  const saved = await browser.evaluate(() => Array.from(document.querySelectorAll('input[aria-label$="in days"]')).map((input) => ({ label: input.getAttribute("aria-label"), value: (input as HTMLInputElement).value })));
  await app.screenshot("retention-values-after-reload");
  expect({ first, second, third, saved }).toEqual({
    first: { tag: "INPUT", label: "Delete old browser artifacts in days", value: "14" },
    second: { tag: "INPUT", label: "Delete old rotated logs in days", value: "14" },
    third: { tag: "INPUT", label: "Delete old browser artifacts in days", value: "21" },
    saved: [ { label: "Delete old browser artifacts in days", value: "21" }, { label: "Delete old rotated logs in days", value: "14" } ],
  });
});
