import type { Page } from "@playwright/test";

export class LoginPage {
  private page: Page;
  constructor(page: Page) {
    this.page = page;
  }

  async goto() {
    await this.page.goto("/");
  }

  private async openAuthPage() {
    // AuthGuard renders a loading spinner while useAuth() resolves on initial
    // load — the Sign in button only appears once isReady=true and the user
    // is unauthenticated. Wait for the button explicitly before clicking.
    const signIn = this.page.getByRole("button", { name: "Sign in" });
    await signIn.waitFor({ state: "visible" });
    await signIn.click();
    await this.page.getByLabel(/email/i).waitFor();
  }

  private async submitCredentials(email: string, password: string) {
    await this.page.getByLabel(/email/i).waitFor();
    await this.page.getByLabel(/email/i).fill(email);
    await this.page.getByPlaceholder("Password").fill(password);
    await this.page.getByPlaceholder("Password").press("Enter");
  }

  async login(email: string, password: string) {
    await this.goto();
    await this.openAuthPage();
    await this.submitCredentials(email, password);
    // Auth redirects through `/?code=...` before landing on the app root.
    // Waiting on networkidle is brittle here, so wait for the final app URL
    // and a stable post-login navigation element instead.
    await this.page.waitForURL((url) => url.pathname === "/" && !url.searchParams.has("code"), {
      waitUntil: "domcontentloaded",
    });
    await this.page.getByRole("link", { name: /products/i }).waitFor();
  }
}
