/* @testgen-package */
// Generated by testgen: rewritten every time tests are generated, do not edit.
// testgen (@xylentis/testgen), Copyright (C) 2026 Xylentis. Licensed under AGPL-3.0-only with an additional
// permission: as part of tests generated by testgen, this file may be used, modified and distributed under
// terms of your choice (see NOTICE in @xylentis/testgen).

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.Duration;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.openqa.selenium.Alert;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.ElementNotInteractableException;
import org.openqa.selenium.InvalidElementStateException;
import org.openqa.selenium.JavascriptException;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.NoSuchFrameException;
import org.openqa.selenium.NoSuchWindowException;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.safari.SafariOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

/**
 * Playwright-style locators for Selenium WebDriver, e.g. {@code page.getByRole("button", "Sign in").click()},
 * with Playwright-like auto-waiting. Locators are resolved inside the page by the testgen engine
 * ({@link #ENGINE}), so getByRole/getByText/getByLabel find the elements the Playwright recorder pointed at.
 *
 * <p>Environment variables: HEADED=1 shows the browser, SELENIUM_REMOTE_URL runs on a Selenium Grid,
 * TESTGEN_TIMEOUT sets the auto-wait timeout in milliseconds (default 10000). {@link #secret(String)} reads
 * a value typed into a password field, e.g. TEST_PASSWORD.
 */
public final class TestgenSupport {
  private TestgenSupport() {}

  static final Duration DEFAULT_TIMEOUT = Duration.ofMillis(Long.parseLong(env("TESTGEN_TIMEOUT", "10000")));
  private static final boolean MAC = System.getProperty("os.name", "").toLowerCase().contains("mac");

  private static String env(String name, String fallback) {
    String value = System.getenv(name);
    return value == null || value.isEmpty() ? fallback : value;
  }

  // Values returned by secret(), as typed and as written in logs: logs and errors show them as ***.
  private static final Set<String> SECRETS = ConcurrentHashMap.newKeySet();

  /**
   * Value of the environment variable (or system property) {@code name}, for a value typed into a password
   * field: the value typed while recording is not kept in the test. Logs and assertion messages show it as ***.
   */
  public static String secret(String name) {
    String value = System.getProperty(name, System.getenv(name));
    if (value == null)
      throw new IllegalStateException("testgen: set the environment variable " + name + ", the value to type into a password field");
    if (!value.isEmpty()) {
      SECRETS.add(value);
      String quoted = quote(value);
      SECRETS.add(quoted.substring(1, quoted.length() - 1));
    }
    return value;
  }

  static String mask(String text) {
    String result = text;
    for (String secret : SECRETS.stream().sorted((a, b) -> b.length() - a.length()).toList())
      result = result.replace(secret, "***");
    return result;
  }

  /** Starts "chrome", "edge", "firefox" or "safari", locally or on SELENIUM_REMOTE_URL; headless unless HEADED is set. */
  public static WebDriver createDriver(String browser, String... arguments) {
    boolean headed = !env("HEADED", "").isEmpty();
    Capabilities options;
    switch (browser) {
      case "firefox" -> {
        FirefoxOptions firefox = new FirefoxOptions().addArguments(arguments);
        options = headed ? firefox : firefox.addArguments("-headless");
      }
      case "edge" -> {
        EdgeOptions edge = new EdgeOptions();
        edge.addArguments(arguments);
        if (!headed)
          edge.addArguments("--headless=new");
        options = edge;
      }
      case "safari" -> options = new SafariOptions();
      default -> {
        ChromeOptions chrome = new ChromeOptions();
        chrome.addArguments(arguments);
        if (!headed)
          chrome.addArguments("--headless=new");
        options = chrome;
      }
    }
    String remote = env("SELENIUM_REMOTE_URL", "");
    if (!remote.isEmpty()) {
      try {
        RemoteWebDriver driver = new RemoteWebDriver(URI.create(remote).toURL(), options);
        driver.setFileDetector(new LocalFileDetector());
        return driver;
      } catch (MalformedURLException e) {
        throw new IllegalArgumentException("SELENIUM_REMOTE_URL is not a valid URL: " + remote, e);
      }
    }
    return switch (browser) {
      case "firefox" -> new FirefoxDriver((FirefoxOptions) options);
      case "edge" -> new EdgeDriver((EdgeOptions) options);
      case "safari" -> new SafariDriver((SafariOptions) options);
      default -> new ChromeDriver((ChromeOptions) options);
    };
  }

  /** Playwright viewports are inner sizes; WebDriver sizes the whole window. */
  public static void setViewportSize(WebDriver driver, int width, int height) {
    driver.manage().window().setSize(new Dimension(width, height));
    List<?> inner = (List<?>) ((JavascriptExecutor) driver).executeScript("return [window.innerWidth, window.innerHeight];");
    int innerWidth = ((Number) inner.get(0)).intValue();
    int innerHeight = ((Number) inner.get(1)).intValue();
    if (innerWidth != width || innerHeight != height)
      driver.manage().window().setSize(new Dimension(2 * width - innerWidth, 2 * height - innerHeight));
  }

  /** A chain of Playwright-style locator steps; nothing is looked up until an action or assertion runs. */
  public static class Locator {
    private final Page page;
    final List<Map<String, Object>> steps;
    private final String description;

    Locator(Page page, List<Map<String, Object>> steps, String description) {
      this.page = page;
      this.steps = steps;
      this.description = description;
    }

    Page page() {
      return this instanceof Page self ? self : page;
    }

    @Override
    public String toString() {
      return description;
    }

    private Locator with(Map<String, Object> step, String call) {
      List<Map<String, Object>> next = new ArrayList<>(steps);
      next.add(step);
      return new Locator(page(), next, description + "." + call);
    }

    private static Map<String, Object> step(String type) {
      Map<String, Object> step = new LinkedHashMap<>();
      step.put("t", type);
      return step;
    }

    public Locator getByRole(String role) {
      return role(role, Map.of(), quote(role));
    }

    public Locator getByRole(String role, String name) {
      return role(role, Map.of("name", name), quote(role) + ", " + quote(name));
    }

    /** Options: name (String or Pattern), exact, checked, disabled, expanded, includeHidden, level, pressed, selected. */
    public Locator getByRole(String role, Map<String, ?> options) {
      return role(role, options, quote(role) + ", " + format(options));
    }

    private Locator role(String role, Map<String, ?> options, String arguments) {
      Map<String, Object> step = step("role");
      step.put("role", role);
      Map<String, Object> attrs = new TreeMap<>();
      for (Map.Entry<String, ?> option : options.entrySet()) {
        switch (option.getKey()) {
          case "name" -> step.put("name", matcher(option.getValue()));
          case "exact" -> step.put("exact", option.getValue());
          case "checked", "disabled", "expanded", "includeHidden", "level", "pressed", "selected" -> attrs.put(option.getKey(), option.getValue());
          default -> throw new IllegalArgumentException("Unknown getByRole option: " + option.getKey());
        }
      }
      if (!attrs.isEmpty())
        step.put("attrs", attrs);
      return with(step, "getByRole(" + arguments + ")");
    }

    public Locator getByText(String text) {
      return byText("text", "getByText", text, false);
    }

    public Locator getByText(String text, boolean exact) {
      return byText("text", "getByText", text, exact);
    }

    public Locator getByText(Pattern text) {
      return byText("text", "getByText", text, false);
    }

    public Locator getByLabel(String text) {
      return byText("label", "getByLabel", text, false);
    }

    public Locator getByLabel(String text, boolean exact) {
      return byText("label", "getByLabel", text, exact);
    }

    public Locator getByLabel(Pattern text) {
      return byText("label", "getByLabel", text, false);
    }

    public Locator getByPlaceholder(String text) {
      return byText("placeholder", "getByPlaceholder", text, false);
    }

    public Locator getByPlaceholder(String text, boolean exact) {
      return byText("placeholder", "getByPlaceholder", text, exact);
    }

    public Locator getByPlaceholder(Pattern text) {
      return byText("placeholder", "getByPlaceholder", text, false);
    }

    public Locator getByAltText(String text) {
      return byText("alt", "getByAltText", text, false);
    }

    public Locator getByAltText(String text, boolean exact) {
      return byText("alt", "getByAltText", text, exact);
    }

    public Locator getByAltText(Pattern text) {
      return byText("alt", "getByAltText", text, false);
    }

    public Locator getByTitle(String text) {
      return byText("title", "getByTitle", text, false);
    }

    public Locator getByTitle(String text, boolean exact) {
      return byText("title", "getByTitle", text, exact);
    }

    public Locator getByTitle(Pattern text) {
      return byText("title", "getByTitle", text, false);
    }

    private Locator byText(String type, String method, Object text, boolean exact) {
      Map<String, Object> step = step(type);
      step.put("v", matcher(text));
      step.put("exact", exact);
      return with(step, method + "(" + format(text) + (exact ? ", true" : "") + ")");
    }

    public Locator getByTestId(String testId) {
      return byTestId(testId);
    }

    public Locator getByTestId(Pattern testId) {
      return byTestId(testId);
    }

    private Locator byTestId(Object testId) {
      Map<String, Object> step = step("testid");
      step.put("attr", page().testIdAttribute);
      step.put("v", matcher(testId));
      return with(step, "getByTestId(" + format(testId) + ")");
    }

    /** CSS by default; also "xpath=...", "//...", "css=..." and Playwright's internal:has-text selectors. */
    public Locator locator(String selector) {
      return with(selectorStep(selector), "locator(" + quote(selector) + ")");
    }

    public Locator locator(Locator inner) {
      List<Map<String, Object>> next = new ArrayList<>(steps);
      next.addAll(inner.steps);
      return new Locator(page(), next, description + ".locator(" + inner + ")");
    }

    public Locator frameLocator(String selector) {
      return locator(selector).contentFrame();
    }

    public Locator contentFrame() {
      return with(step("frame"), "contentFrame()");
    }

    public Locator filterHasText(String text) {
      return hasText(text, false, "filterHasText");
    }

    public Locator filterHasText(Pattern text) {
      return hasText(text, false, "filterHasText");
    }

    public Locator filterHasNotText(String text) {
      return hasText(text, true, "filterHasNotText");
    }

    public Locator filterHasNotText(Pattern text) {
      return hasText(text, true, "filterHasNotText");
    }

    private Locator hasText(Object text, boolean not, String method) {
      Map<String, Object> step = step("hasText");
      step.put("v", matcher(text));
      step.put("not", not);
      return with(step, method + "(" + format(text) + ")");
    }

    public Locator filterHas(Locator inner) {
      return has(inner, false, "filterHas");
    }

    public Locator filterHasNot(Locator inner) {
      return has(inner, true, "filterHasNot");
    }

    private Locator has(Locator inner, boolean not, String method) {
      Map<String, Object> step = step("has");
      step.put("steps", inner.steps);
      step.put("not", not);
      return with(step, method + "(" + inner + ")");
    }

    public Locator filterVisible(boolean visible) {
      Map<String, Object> step = step("visible");
      step.put("v", visible);
      return with(step, "filterVisible(" + visible + ")");
    }

    public Locator nth(int index) {
      Map<String, Object> step = step("nth");
      step.put("v", index);
      return with(step, "nth(" + index + ")");
    }

    public Locator first() {
      return nth(0);
    }

    public Locator last() {
      return nth(-1);
    }

    public Locator and(Locator other) {
      Map<String, Object> step = step("and");
      step.put("steps", other.steps);
      return with(step, "and(" + other + ")");
    }

    public Locator or(Locator other) {
      Map<String, Object> step = step("or");
      step.put("steps", other.steps);
      return with(step, "or(" + other + ")");
    }

    /** Elements currently matching the locator (no waiting). */
    public List<WebElement> elements() {
      Page page = page();
      page.activate();
      page.driver.switchTo().defaultContent();
      List<Map<String, Object>> segment = new ArrayList<>();
      for (Map<String, Object> step : steps) {
        if (!"frame".equals(step.get("t"))) {
          segment.add(step);
          continue;
        }
        List<WebElement> frames = page.resolve(segment);
        if (frames.isEmpty())
          return List.of();
        page.driver.switchTo().frame(frames.get(0));
        segment = new ArrayList<>();
      }
      return page.resolve(segment);
    }

    public int count() {
      return elements().size();
    }

    /** Waits for the first matching element to be attached and returns it. */
    public WebElement element() {
      return query("element", element -> element, false, false);
    }

    // Waits for the first matching element to be ready, then runs `action` on it.
    private <T> T query(String name, Function<WebElement, T> action, boolean visible, boolean enabled) {
      Page page = page();
      long deadline = System.nanoTime() + page.timeout.toNanos();
      String reason;
      while (true) {
        try {
          List<WebElement> found = elements();
          if (found.isEmpty()) {
            reason = "no element matches";
          } else if (visible && !found.get(0).isDisplayed()) {
            reason = "element is not visible";
          } else if (enabled && !found.get(0).isEnabled()) {
            reason = "element is not enabled";
          } else {
            T result = action.apply(found.get(0));
            page.handleDialogs();
            return result;
          }
        } catch (WebDriverException e) {
          if (!isRetryable(e))
            throw e;
          reason = firstLine(e.getMessage());
        }
        if (System.nanoTime() > deadline)
          throw new TimeoutException(mask(name + ": timeout " + page.timeout.toMillis() + "ms exceeded waiting for " + this + " (" + reason + ")"));
        sleep(100);
      }
    }

    // Runs `action` on the first matching element once it is ready; `arguments` describe the call in the log.
    private void act(String name, String arguments, Consumer<WebElement> action, boolean visible, boolean enabled) {
      String call = this + "." + name + "(" + arguments + ")";
      page().log(call);
      try {
        query(name, element -> {
          action.accept(element);
          return null;
        }, visible, enabled);
      } catch (RuntimeException e) {
        page().log(call + " FAILED: " + firstLine(e.getMessage()));
        throw e;
      }
    }

    public void click() {
      act("click", "", WebElement::click, true, true);
    }

    public void click(ClickOptions options) {
      act("click", options.toString(), element -> options.perform(page().driver, element, true), true, true);
    }

    public void dblclick() {
      act("dblclick", "", element -> new Actions(page().driver).doubleClick(element).perform(), true, true);
    }

    public void hover() {
      act("hover", "", element -> new Actions(page().driver).moveToElement(element).perform(), true, false);
    }

    public void hover(ClickOptions options) {
      act("hover", options.toString(), element -> options.perform(page().driver, element, false), true, false);
    }

    public void fill(String value) {
      act("fill", quote(value), element -> {
        element.clear();
        if (!value.isEmpty())
          element.sendKeys(value);
      }, true, true);
    }

    public void press(String key) {
      act("press", quote(key), element -> element.sendKeys(keys(key)), true, false);
    }

    public void check() {
      setChecked(true);
    }

    public void uncheck() {
      setChecked(false);
    }

    private void setChecked(boolean checked) {
      act(checked ? "check" : "uncheck", "", element -> {
        if (isChecked(element) != checked)
          element.click();
      }, true, true);
    }

    public void selectOption(String... values) {
      act("selectOption", String.join(", ", Arrays.stream(values).map(TestgenSupport::quote).toList()), element -> {
        Select select = new Select(element);
        if (select.isMultiple())
          select.deselectAll();
        for (String value : values) {
          try {
            select.selectByValue(value);
          } catch (NoSuchElementException e) {
            select.selectByVisibleText(value);
          }
        }
      }, true, true);
    }

    public void setInputFiles(String... files) {
      List<String> paths = new ArrayList<>();
      for (String file : files)
        paths.add(Path.of(file).toAbsolutePath().toString());
      act("setInputFiles", String.join(", ", Arrays.stream(files).map(TestgenSupport::quote).toList()),
          element -> element.sendKeys(String.join("\n", paths)), false, false);
    }

    /** The text of the first matching element as the user sees it, like Playwright's innerText(). */
    public String innerText() {
      return read("innerText", "", WebElement::getText);
    }

    /** The value of the first matching input, textarea or select. */
    public String inputValue() {
      return read("inputValue", "", element -> element.getDomProperty("value"));
    }

    /** The attribute {@code name} of the first matching element, or null when it has none. */
    public String getAttribute(String name) {
      return read("getAttribute", quote(name), element -> element.getDomAttribute(name));
    }

    // Waits for the first matching element and returns what `read` reads from it; logs the call and the value.
    private String read(String name, String arguments, Function<WebElement, String> read) {
      String call = this + "." + name + "(" + arguments + ")";
      try {
        String value = query(name, read, false, false);
        page().log(call + " = " + quote(value));
        return value;
      } catch (RuntimeException e) {
        page().log(call + " FAILED: " + firstLine(e.getMessage()));
        throw e;
      }
    }

    public void shouldBeVisible() {
      expect("shouldBeVisible", null, WebElement::isDisplayed, element -> element.isDisplayed() ? "visible" : "hidden");
    }

    public void shouldHaveText(String expected) {
      expect("shouldHaveText", expected, element -> textOf(element).equals(normalize(expected)), TestgenSupport::textOf);
    }

    public void shouldContainText(String expected) {
      expect("shouldContainText", expected, element -> textOf(element).contains(normalize(expected)), TestgenSupport::textOf);
    }

    public void shouldHaveValue(String expected) {
      expect("shouldHaveValue", expected, element -> expected.equals(element.getDomProperty("value")), element -> element.getDomProperty("value"));
    }

    public void shouldBeEmpty() {
      expect("shouldBeEmpty", null, element -> valueOrText(element).isEmpty(), TestgenSupport::valueOrText);
    }

    public void shouldBeChecked() {
      expect("shouldBeChecked", null, TestgenSupport::isChecked, element -> isChecked(element) ? "checked" : "unchecked");
    }

    public void shouldNotBeChecked() {
      expect("shouldNotBeChecked", null, element -> !isChecked(element), element -> isChecked(element) ? "checked" : "unchecked");
    }

    // Polls until `check` passes for the first matching element.
    private void expect(String name, String expected, Predicate<WebElement> check, Function<WebElement, String> actual) {
      Page page = page();
      String call = this + "." + name + "(" + (expected == null ? "" : quote(expected)) + ")";
      long deadline = System.nanoTime() + page.timeout.toNanos();
      String received = "<element not found>";
      while (true) {
        try {
          List<WebElement> found = elements();
          if (!found.isEmpty()) {
            if (check.test(found.get(0))) {
              page.log(call + " passed");
              return;
            }
            received = actual.apply(found.get(0));
          }
        } catch (WebDriverException e) {
          if (!isRetryable(e)) {
            page.log(call + " FAILED: " + firstLine(e.getMessage()));
            throw e;
          }
          received = firstLine(e.getMessage());
        }
        if (System.nanoTime() > deadline) {
          page.log(call + " FAILED, received: " + received);
          throw new AssertionError(mask(call + " failed after " + page.timeout.toMillis() + "ms\nReceived: " + received));
        }
        sleep(100);
      }
    }
  }

  /** One browser window or tab, like Playwright's Page; actions switch WebDriver to it automatically. */
  public static final class Page extends Locator {
    private static final DateTimeFormatter LOG_TIME = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");

    final WebDriver driver;
    final String handle;
    String testIdAttribute = "data-testid";
    Duration timeout = DEFAULT_TIMEOUT;
    private Consumer<String> logger;
    // Pages opened later are named page1, page2, ... like the variables of the generated test.
    private final AtomicInteger opened;
    private final List<Consumer<Dialog>> dialogHandlers = new ArrayList<>();

    public Page(WebDriver driver) {
      this(driver, driver.getWindowHandle(), "page", new AtomicInteger());
    }

    private Page(WebDriver driver, String handle, String name, AtomicInteger opened) {
      super(null, List.of(), name);
      this.driver = driver;
      this.handle = handle;
      this.opened = opened;
    }

    public Page setTestIdAttribute(String attribute) {
      testIdAttribute = attribute;
      return this;
    }

    /**
     * Receives a line for every action, with its arguments, and for the result of every assertion, e.g.
     * {@code page.setLogger(System.out::println)} or {@code page.setLogger(message -> Reporter.log(message, true))}
     * with TestNG. Pages opened later log to it as well.
     */
    public Page setLogger(Consumer<String> logger) {
      this.logger = logger;
      return this;
    }

    void log(String message) {
      if (logger != null)
        logger.accept(LocalTime.now().format(LOG_TIME) + " " + mask(message));
    }

    public Page setDefaultTimeout(Duration timeout) {
      this.timeout = timeout;
      return this;
    }

    public void navigate(String url) {
      log(this + ".navigate(" + quote(url) + ")");
      activate();
      driver.get(url);
    }

    public void close() {
      log(this + ".close()");
      activate();
      driver.close();
    }

    /** Pauses the test for {@code millis} milliseconds, e.g. to watch the browser at that point. */
    public void waitForTimeout(long millis) {
      log(this + ".waitForTimeout(" + millis + ")");
      sleep(millis);
    }

    public String title() {
      activate();
      String title = driver.getTitle();
      log(this + ".title() = " + quote(title));
      return title;
    }

    public String url() {
      activate();
      String url = driver.getCurrentUrl();
      log(this + ".url() = " + quote(url));
      return url;
    }

    public void shouldHaveTitle(String expected) {
      expectPage("shouldHaveTitle", expected, driver::getTitle, title -> title.equals(normalize(expected)));
    }

    public void shouldContainTitle(String expected) {
      expectPage("shouldContainTitle", expected, driver::getTitle, title -> title.contains(normalize(expected)));
    }

    public void shouldHaveURL(String expected) {
      expectPage("shouldHaveURL", expected, driver::getCurrentUrl, url -> url.equals(expected));
    }

    public void shouldContainURL(String expected) {
      expectPage("shouldContainURL", expected, driver::getCurrentUrl, url -> url.contains(expected));
    }

    // Polls until `check` passes for what `actual` reads from this page.
    private void expectPage(String name, String expected, Supplier<String> actual, Predicate<String> check) {
      String call = this + "." + name + "(" + quote(expected) + ")";
      long deadline = System.nanoTime() + timeout.toNanos();
      String received = "";
      while (true) {
        try {
          activate();
          received = actual.get();
          if (check.test(received)) {
            log(call + " passed");
            return;
          }
        } catch (WebDriverException e) {
          if (!isRetryable(e)) {
            log(call + " FAILED: " + firstLine(e.getMessage()));
            throw e;
          }
          received = firstLine(e.getMessage());
        }
        if (System.nanoTime() > deadline) {
          log(call + " FAILED, received: " + received);
          throw new AssertionError(mask(call + " failed after " + timeout.toMillis() + "ms\nReceived: " + received));
        }
        sleep(100);
      }
    }

    /** Opens a new tab. */
    public Page newPage() {
      driver.switchTo().newWindow(WindowType.TAB);
      Page page = sibling(driver.getWindowHandle());
      log(page + " = " + this + ".newPage()");
      return page;
    }

    /** Runs `action` and returns the window it opens. */
    public Page waitForPopup(Runnable action) {
      activate();
      Set<String> before = driver.getWindowHandles();
      action.run();
      long deadline = System.nanoTime() + timeout.toNanos();
      while (true) {
        for (String candidate : driver.getWindowHandles()) {
          if (!before.contains(candidate)) {
            Page popup = sibling(candidate);
            log(popup + " opened as a popup of " + this);
            return popup;
          }
        }
        if (System.nanoTime() > deadline)
          throw new TimeoutException("waitForPopup: timeout " + timeout.toMillis() + "ms exceeded");
        sleep(100);
      }
    }

    /** The handler runs for the next alert/confirm/prompt opened by an action on this page. */
    public void onceDialog(Consumer<Dialog> handler) {
      dialogHandlers.add(handler);
    }

    void handleDialogs() {
      if (dialogHandlers.isEmpty())
        return;
      Alert alert;
      try {
        alert = new WebDriverWait(driver, Duration.ofSeconds(2)).until(ExpectedConditions.alertIsPresent());
      } catch (TimeoutException e) {
        return;
      }
      Dialog dialog = new Dialog(alert);
      log(this + " dialog " + quote(dialog.message()));
      dialogHandlers.remove(0).accept(dialog);
    }

    void activate() {
      String current;
      try {
        current = driver.getWindowHandle();
      } catch (NoSuchWindowException e) {
        current = null;
      }
      if (!handle.equals(current))
        driver.switchTo().window(handle);
    }

    List<WebElement> resolve(List<Map<String, Object>> steps) {
      Object result = ((JavascriptExecutor) driver).executeScript("return (" + ENGINE + ").apply(null, arguments);", json(steps));
      List<WebElement> elements = new ArrayList<>();
      if (result instanceof List<?> list) {
        for (Object item : list)
          elements.add((WebElement) item);
      }
      return elements;
    }

    private Page sibling(String handle) {
      Page page = new Page(driver, handle, "page" + opened.incrementAndGet(), opened);
      page.testIdAttribute = testIdAttribute;
      page.timeout = timeout;
      page.logger = logger;
      return page;
    }
  }

  public static final class Dialog {
    private final Alert alert;
    private final String message;

    Dialog(Alert alert) {
      this.alert = alert;
      this.message = alert.getText();
    }

    public String message() {
      return message;
    }

    public void dismiss() {
      alert.dismiss();
    }

    public void accept() {
      alert.accept();
    }

    public void accept(String promptText) {
      alert.sendKeys(promptText);
      alert.accept();
    }
  }

  /** Mouse options of a recorded click: button, modifiers, click count, position from the top-left corner. */
  public static final class ClickOptions {
    private String button = "left";
    private int clickCount = 1;
    private String[] modifiers = {};
    private Double x;
    private Double y;

    public ClickOptions setButton(String button) {
      this.button = button;
      return this;
    }

    public ClickOptions setClickCount(int clickCount) {
      this.clickCount = clickCount;
      return this;
    }

    public ClickOptions setModifiers(String... modifiers) {
      this.modifiers = modifiers;
      return this;
    }

    public ClickOptions setPosition(double x, double y) {
      this.x = x;
      this.y = y;
      return this;
    }

    @Override
    public String toString() {
      StringBuilder result = new StringBuilder("new ClickOptions()");
      if (!"left".equals(button))
        result.append(".setButton(").append(quote(button)).append(")");
      if (modifiers.length > 0)
        result.append(".setModifiers(").append(String.join(", ", Arrays.stream(modifiers).map(TestgenSupport::quote).toList())).append(")");
      if (clickCount != 1)
        result.append(".setClickCount(").append(clickCount).append(")");
      if (x != null)
        result.append(".setPosition(").append(x).append(", ").append(y).append(")");
      return result.toString();
    }

    void perform(WebDriver driver, WebElement element, boolean click) {
      if ("middle".equals(button))
        throw new UnsupportedOperationException("testgen: middle click is not supported on Selenium");
      Actions actions = new Actions(driver);
      for (String modifier : modifiers)
        actions.keyDown(modifierKey(modifier));
      if (x != null) {
        // WebDriver offsets are relative to the element center.
        Rectangle rect = element.getRect();
        actions.moveToElement(element, (int) Math.round(x - rect.getWidth() / 2.0), (int) Math.round(y - rect.getHeight() / 2.0));
      } else {
        actions.moveToElement(element);
      }
      if (click && "right".equals(button))
        actions.contextClick();
      else if (click && clickCount == 2)
        actions.doubleClick();
      else if (click)
        for (int i = 0; i < clickCount; i++)
          actions.click();
      for (int i = modifiers.length - 1; i >= 0; i--)
        actions.keyUp(modifierKey(modifiers[i]));
      actions.perform();
    }
  }

  /**
   * Rows of the CSV data file of a data-driven test, as test arguments in the order of {@code columns}.
   * The file is a classpath resource next to {@code testClass} (Maven: src/test/resources/<package>/).
   * It is UTF-8, with or without a BOM, separated by commas or semicolons (as Excel saves it in some
   * languages), and its first line names the columns; other columns are ignored, blank lines skipped.
   */
  public static Object[][] readCsv(Class<?> testClass, String resource, String... columns) {
    String text;
    try (InputStream input = testClass.getResourceAsStream(resource)) {
      if (input == null) {
        String folder = testClass.getPackageName().replace('.', '/');
        throw new IllegalStateException("testgen: data file " + resource + " not found next to " + testClass.getName()
            + " on the classpath (Maven: src/test/resources/" + (folder.isEmpty() ? "" : folder + "/") + resource + ")");
      }
      text = new String(input.readAllBytes(), StandardCharsets.UTF_8);
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
    if (text.startsWith("\uFEFF"))
      text = text.substring(1);
    String firstLine = text.split("\r?\n", 2)[0];
    char separator = firstLine.indexOf(',') < 0 && firstLine.indexOf(';') >= 0 ? ';' : ',';
    List<List<String>> rows = parseCsv(text, separator);
    if (rows.isEmpty())
      throw new IllegalStateException("testgen: data file " + resource + " is empty");

    List<String> header = rows.get(0).stream().map(String::trim).toList();
    int[] indexes = new int[columns.length];
    for (int i = 0; i < columns.length; i++) {
      indexes[i] = header.indexOf(columns[i]);
      if (indexes[i] < 0)
        throw new IllegalStateException("testgen: data file " + resource + " has no column \"" + columns[i] + "\" (it has " + String.join(", ", header) + ")");
    }
    List<Object[]> result = new ArrayList<>();
    for (List<String> row : rows.subList(1, rows.size())) {
      if (row.stream().allMatch(String::isBlank))
        continue;
      Object[] arguments = new Object[columns.length];
      for (int i = 0; i < columns.length; i++)
        arguments[i] = indexes[i] < row.size() ? row.get(indexes[i]) : "";
      result.add(arguments);
    }
    if (result.isEmpty())
      throw new IllegalStateException("testgen: data file " + resource + " has no data rows");
    return result.toArray(new Object[0][]);
  }

  // RFC 4180: quoted fields may contain separators, line breaks and doubled quotes.
  static List<List<String>> parseCsv(String text, char separator) {
    List<List<String>> rows = new ArrayList<>();
    List<String> row = new ArrayList<>();
    StringBuilder field = new StringBuilder();
    boolean quoted = false;
    for (int i = 0; i < text.length(); i++) {
      char c = text.charAt(i);
      if (quoted) {
        if (c == '"' && i + 1 < text.length() && text.charAt(i + 1) == '"') {
          field.append('"');
          i++;
        } else if (c == '"') {
          quoted = false;
        } else {
          field.append(c);
        }
      } else if (c == '"') {
        quoted = true;
      } else if (c == separator) {
        row.add(field.toString());
        field.setLength(0);
      } else if (c == '\n' || c == '\r') {
        if (c == '\r' && i + 1 < text.length() && text.charAt(i + 1) == '\n')
          i++;
        row.add(field.toString());
        field.setLength(0);
        rows.add(row);
        row = new ArrayList<>();
      } else {
        field.append(c);
      }
    }
    if (field.length() > 0 || !row.isEmpty()) {
      row.add(field.toString());
      rows.add(row);
    }
    return rows;
  }

  static boolean isChecked(WebElement element) {
    String type = String.valueOf(element.getDomAttribute("type")).toLowerCase();
    if ("input".equalsIgnoreCase(element.getTagName()) && (type.equals("checkbox") || type.equals("radio")))
      return element.isSelected();
    return "true".equals(element.getDomAttribute("aria-checked"));
  }

  static String textOf(WebElement element) {
    return normalize(element.getDomProperty("textContent"));
  }

  static String valueOrText(WebElement element) {
    String tag = element.getTagName().toLowerCase();
    if (tag.equals("input") || tag.equals("textarea"))
      return String.valueOf(element.getDomProperty("value"));
    return textOf(element);
  }

  static String normalize(String text) {
    return text == null ? "" : text.replace("​", "").trim().replaceAll("\\s+", " ");
  }

  static boolean isRetryable(WebDriverException e) {
    if (e instanceof StaleElementReferenceException || e instanceof ElementNotInteractableException
        || e instanceof NoSuchElementException || e instanceof NoSuchFrameException
        || e instanceof InvalidElementStateException || e instanceof NoSuchWindowException)
      return true;
    // Scripts fail while the page navigates; real script errors carry a testgen or syntax message.
    return e instanceof JavascriptException && !String.valueOf(e.getMessage()).matches("(?s).*(testgen:|SyntaxError|not a valid).*");
  }

  private static String firstLine(String message) {
    return message == null ? "" : message.split("\n", 2)[0];
  }

  private static void sleep(long millis) {
    try {
      Thread.sleep(millis);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
      throw new IllegalStateException(e);
    }
  }

  // Text value for the engine: a string, or {source, flags} for a regular expression.
  private static Object matcher(Object value) {
    if (!(value instanceof Pattern pattern))
      return String.valueOf(value);
    String flags = ((pattern.flags() & Pattern.CASE_INSENSITIVE) != 0 ? "i" : "")
        + ((pattern.flags() & Pattern.MULTILINE) != 0 ? "m" : "")
        + ((pattern.flags() & Pattern.DOTALL) != 0 ? "s" : "");
    Map<String, Object> regex = new LinkedHashMap<>();
    regex.put("source", pattern.pattern());
    regex.put("flags", flags);
    return regex;
  }

  // Text, label, placeholder, ... values of internal:has-text selectors: "text"i, "text"s or /regex/flags.
  private static Map<String, Object> selectorStep(String selector) {
    Map<String, Object> step = new LinkedHashMap<>();
    Matcher hasText = Pattern.compile("^internal:(has-text|has-not-text)=(.*)$", Pattern.DOTALL).matcher(selector);
    if (selector.startsWith("xpath=")) {
      step.put("t", "xpath");
      step.put("v", selector.substring("xpath=".length()));
    } else if (selector.startsWith("//") || selector.startsWith("..")) {
      step.put("t", "xpath");
      step.put("v", selector);
    } else if (selector.startsWith("css=")) {
      step.put("t", "css");
      step.put("v", selector.substring("css=".length()));
    } else if (hasText.matches()) {
      String body = hasText.group(2);
      Matcher regex = Pattern.compile("^/(.*)/([a-z]*)$", Pattern.DOTALL).matcher(body);
      step.put("t", "hasText");
      step.put("not", hasText.group(1).equals("has-not-text"));
      if (regex.matches()) {
        step.put("v", Map.of("source", regex.group(1), "flags", regex.group(2)));
      } else {
        boolean exact = !body.endsWith("\"i");
        step.put("v", unquote(exact && body.endsWith("\"s") ? body.substring(0, body.length() - 1) : exact ? body : body.substring(0, body.length() - 1)));
        step.put("exact", exact);
      }
    } else if (selector.startsWith("internal:") || selector.matches("^[a-zA-Z_0-9-]+=.*")) {
      throw new IllegalArgumentException("testgen: selector not supported on Selenium: " + selector);
    } else {
      step.put("t", "css");
      step.put("v", selector);
    }
    return step;
  }

  private static String unquote(String quoted) {
    if (!quoted.startsWith("\"") || !quoted.endsWith("\"") || quoted.length() < 2)
      return quoted;
    StringBuilder result = new StringBuilder();
    for (int i = 1; i < quoted.length() - 1; i++) {
      char c = quoted.charAt(i);
      if (c == '\\' && i + 1 < quoted.length() - 1) {
        char next = quoted.charAt(++i);
        result.append(switch (next) {
          case 'n' -> '\n';
          case 't' -> '\t';
          case 'r' -> '\r';
          default -> next;
        });
      } else {
        result.append(c);
      }
    }
    return result.toString();
  }

  private static final Map<String, CharSequence> NAMED_KEYS = Map.ofEntries(
      Map.entry("Enter", Keys.ENTER), Map.entry("Tab", Keys.TAB), Map.entry("Escape", Keys.ESCAPE),
      Map.entry("Backspace", Keys.BACK_SPACE), Map.entry("Delete", Keys.DELETE), Map.entry("Insert", Keys.INSERT),
      Map.entry("ArrowUp", Keys.ARROW_UP), Map.entry("ArrowDown", Keys.ARROW_DOWN),
      Map.entry("ArrowLeft", Keys.ARROW_LEFT), Map.entry("ArrowRight", Keys.ARROW_RIGHT),
      Map.entry("Home", Keys.HOME), Map.entry("End", Keys.END), Map.entry("PageUp", Keys.PAGE_UP),
      Map.entry("PageDown", Keys.PAGE_DOWN), Map.entry("Space", " "),
      Map.entry("F1", Keys.F1), Map.entry("F2", Keys.F2), Map.entry("F3", Keys.F3), Map.entry("F4", Keys.F4),
      Map.entry("F5", Keys.F5), Map.entry("F6", Keys.F6), Map.entry("F7", Keys.F7), Map.entry("F8", Keys.F8),
      Map.entry("F9", Keys.F9), Map.entry("F10", Keys.F10), Map.entry("F11", Keys.F11), Map.entry("F12", Keys.F12));

  static Keys modifierKey(String name) {
    return switch (name) {
      case "Alt" -> Keys.ALT;
      case "Control" -> Keys.CONTROL;
      case "Meta" -> Keys.META;
      case "Shift" -> Keys.SHIFT;
      case "ControlOrMeta" -> MAC ? Keys.META : Keys.CONTROL;
      default -> throw new IllegalArgumentException("testgen: unknown modifier " + name);
    };
  }

  /** Playwright key names ("Enter", "Shift+Tab", "ControlOrMeta+a") to WebDriver keys. */
  static CharSequence keys(String shortcut) {
    String[] parts = shortcut.split("\\+(?=.)");
    List<CharSequence> chord = new ArrayList<>();
    for (int i = 0; i < parts.length - 1; i++)
      chord.add(modifierKey(parts[i]));
    String key = parts[parts.length - 1];
    chord.add(NAMED_KEYS.getOrDefault(key, key));
    return chord.size() == 1 ? chord.get(0) : Keys.chord(chord);
  }

  static String quote(String text) {
    return json(text);
  }

  private static String format(Object value) {
    if (value instanceof Pattern pattern)
      return "Pattern.compile(" + quote(pattern.pattern()) + ")";
    if (value instanceof Map<?, ?> map) {
      List<String> entries = new ArrayList<>();
      for (Map.Entry<?, ?> entry : new TreeMap<>(map).entrySet())
        entries.add(quote(String.valueOf(entry.getKey())) + ", " + format(entry.getValue()));
      return "Map.of(" + String.join(", ", entries) + ")";
    }
    return value instanceof String text ? quote(text) : String.valueOf(value);
  }

  // Minimal JSON writer for engine steps (strings, numbers, booleans, lists and maps).
  static String json(Object value) {
    if (value == null)
      return "null";
    if (value instanceof Boolean || value instanceof Number)
      return value.toString();
    if (value instanceof Map<?, ?> map) {
      List<String> entries = new ArrayList<>();
      for (Map.Entry<?, ?> entry : map.entrySet())
        entries.add(json(String.valueOf(entry.getKey())) + ":" + json(entry.getValue()));
      return "{" + String.join(",", entries) + "}";
    }
    if (value instanceof List<?> list) {
      List<String> items = new ArrayList<>();
      for (Object item : list)
        items.add(json(item));
      return "[" + String.join(",", items) + "]";
    }
    String text = value.toString();
    StringBuilder result = new StringBuilder("\"");
    for (char c : text.toCharArray()) {
      switch (c) {
        case '"' -> result.append("\\\"");
        case '\\' -> result.append("\\\\");
        case '\n' -> result.append("\\n");
        case '\r' -> result.append("\\r");
        case '\t' -> result.append("\\t");
        default -> {
          if (c < 0x20)
            result.append(String.format("\\u%04x", (int) c));
          else
            result.append(c);
        }
      }
    }
    return result.append('"').toString();
  }

  /** The testgen locator engine, run in the page through executeScript. */
  static final String ENGINE = """
      @testgen-engine
      """;
}
