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

test("Device host limits stay empty when cleared and accept replacement numbers", WEB, async ({ t3, app, browser, screen }) => {
  const project = await t3.project("device-limit-demo");
  await t3.thread({ project, title: "Device limits", messages: ["Hello"] });
  await t3.open("/settings/labs");
  await screen.getByRole("switch", "Simlock device hosts", { exact: true }).tap();
  await t3.open("/settings/devices#device-sources");
  const observations: Array<{ label: string; cleared: string; disabled: boolean; replacement: string; enabled: boolean }> = [];
  const value = () => browser.evaluate(() => (document.activeElement as HTMLInputElement).value);
  const save = screen.getByRole("button", "Save host", { exact: true });
  const check = async (label: string, backspaces: number, replacement: string, capture: string) => {
    const field = screen.getByLabel(label, { exact: true });
    await field.tap();
    await field.press("End");
    for (let i = 0; i < backspaces; i++) await field.press("Backspace");
    const cleared = await value();
    const disabled = !(await save.isEnabled());
    await app.screenshot(`${capture}-cleared`);
    await browser.keyboard.type(replacement);
    const entered = await value();
    const enabled = await save.isEnabled();
    await app.screenshot(`${capture}-replacement`);
    observations.push({ label, cleared, disabled, replacement: entered, enabled });
  };
  await screen.getByRole("button", "Add source", { exact: true }).tap();
  await screen.getByRole("menuitem", "Expo Simulators", { exact: true }).tap();
  await check("Sessions at once", 1, "5", "expo-sessions");
  await check("Session minutes", 2, "45", "expo-session-minutes");
  await check("Idle minutes", 2, "7", "expo-idle-minutes");
  await screen.getByRole("button", "Cancel", { exact: true }).tap();
  await screen.getByRole("button", "Add source", { exact: true }).tap();
  await screen.getByRole("menuitem", "Simlock pool (alpha)", { exact: true }).tap();
  await screen.getByLabel("Gateway URL", { exact: true }).fill("https://gateway.example.ts.net:4700");
  await check("Devices at once", 2, "5", "simlock-devices");
  await check("Lease minutes", 2, "30", "simlock-lease-minutes");
  expect(observations).toEqual([
    { label: "Sessions at once", cleared: "", disabled: true, replacement: "5", enabled: true },
    { label: "Session minutes", cleared: "", disabled: true, replacement: "45", enabled: true },
    { label: "Idle minutes", cleared: "", disabled: true, replacement: "7", enabled: true },
    { label: "Devices at once", cleared: "", disabled: true, replacement: "5", enabled: true },
    { label: "Lease minutes", cleared: "", disabled: true, replacement: "30", enabled: true },
  ]);
});
