import {
  expect,
  type Page,
  type Locator
} from '@playwright/test';

export class RegisterPage {
  readonly usernameInput: Locator;
  readonly displayNameInput: Locator;
  readonly passwordInput: Locator;
  readonly serverSelect: Locator;
  readonly submitButton: Locator;
  readonly errorText: Locator;
  readonly loginLink: Locator;

  constructor(private page: Page) {
    this.usernameInput = page.locator('#register-username');
    this.displayNameInput = page.locator('#register-display-name');
    this.passwordInput = page.locator('#register-password');
    this.serverSelect = page.locator('#register-server');
    this.submitButton = page.getByRole('button', { name: 'Create Account' });
    this.errorText = page.locator('.text-destructive');
    this.loginLink = page.getByRole('button', { name: 'Login' });
  }

  async goto() {
    await this.page.goto('/register', { waitUntil: 'domcontentloaded' });

    try {
      await expect(this.usernameInput).toBeVisible({ timeout: 10_000 });
    } catch {
      // Angular router may redirect to /login on first load; use the
      // visible login-form action instead of broad text matching.
      const registerButton = this.page.getByRole('button', { name: 'Register', exact: true }).last();

      await expect(registerButton).toBeVisible({ timeout: 10_000 });
      await registerButton.click();
      await expect(this.usernameInput).toBeVisible({ timeout: 30_000 });
    }

    await expect(this.submitButton).toBeVisible({ timeout: 30_000 });
  }

  async register(username: string, displayName: string, password: string) {
    await this.usernameInput.fill(username);
    await expect(this.usernameInput).toHaveValue(username);
    await this.displayNameInput.fill(displayName);
    await expect(this.displayNameInput).toHaveValue(displayName);
    await this.passwordInput.fill(password);
    await expect(this.passwordInput).toHaveValue(password);
    await this.submitButton.click();
  }
}
