import { test, expect } from "@playwright/test";
import { authenticateViaApply, uniqueTestPhone } from "../helpers/wizard";

/** Target: wizard step interactive content visible within 2 seconds (T-024). */
const STEP_LOAD_BUDGET_MS = 2_000;

async function measureStepLoad(
  page: import("@playwright/test").Page,
  headingPattern: RegExp,
): Promise<number> {
  const start = Date.now();
  await expect(page.locator("h2")).toContainText(headingPattern, { timeout: STEP_LOAD_BUDGET_MS });
  return Date.now() - start;
}

test.describe("Wizard step load performance", () => {
  test("apply page loads within budget", async ({ page }) => {
    const start = Date.now();
    await page.goto("/farmers/apply");
    await expect(page.locator("#apply-phone")).toBeVisible({ timeout: STEP_LOAD_BUDGET_MS });
    const elapsed = Date.now() - start;
    expect(elapsed).toBeLessThan(STEP_LOAD_BUDGET_MS);
  });

  test("account step loads within budget after OTP", async ({ page }) => {
    const phone = uniqueTestPhone();
    await page.goto("/farmers/apply");
    await page.fill("#apply-phone", phone);
    await page.click("button:has-text('Send Verification Code')");
    await page.fill("#apply-otp", "1234");
    await page.click("button:has-text('Continue to Application')");
    await page.waitForURL("**/farmers/onboarding");

    const elapsed = await measureStepLoad(page, /Create your account|account/i);
    expect(elapsed).toBeLessThan(STEP_LOAD_BUDGET_MS);
  });

  test("consent step loads within budget", async ({ page }) => {
    const phone = uniqueTestPhone();
    await authenticateViaApply(page, phone);

    const continueBtn = page.getByRole("button", { name: "Continue", exact: true });
    if (await continueBtn.isVisible()) {
      await continueBtn.click();
    }

    const elapsed = await measureStepLoad(page, /Rozilik|Согласие|Consent/i);
    expect(elapsed).toBeLessThan(STEP_LOAD_BUDGET_MS);
  });

  test("login page loads within budget", async ({ page }) => {
    const start = Date.now();
    await page.goto("/farmers/login");
    await expect(page.locator("#login-phone")).toBeVisible({ timeout: STEP_LOAD_BUDGET_MS });
    expect(Date.now() - start).toBeLessThan(STEP_LOAD_BUDGET_MS);
  });
});
