import { Page } from '@playwright/test';
import { BasePage } from './BasePage';

export class LoginPage extends BasePage {
    private readonly usernameField = '#user_login';
    private readonly passwordField = '#user_pass';
    private readonly loginButton = '#wp-submit';
    private readonly rememberMeCheckbox = '#rememberme';
    private readonly errorMessage = '.hvac-login-error';
    private readonly forgotPasswordLink = 'a:has-text("Lost your password")';

    constructor(page: Page) {
        super(page);
    }

    async navigate(): Promise<void> {
        const STAGING_URL = 'https://wordpress-974670-5399585.cloudwaysapps.com';
        await this.page.goto(`${STAGING_URL}/community-login/`);
        await this.page.waitForLoadState('networkidle');
    }
    
    async navigateToLogin(): Promise<void> {
        await this.navigate();
    }

    async login(username: string, password: string, rememberMe: boolean = false): Promise<void> {
        await this.fill(this.usernameField, username);
        await this.fill(this.passwordField, password);
        
        if (rememberMe) {
            await this.click(this.rememberMeCheckbox);
        }
        
        await this.click(this.loginButton);
        await this.waitForNavigation();
    }

    async getErrorMessage(): Promise<string> {
        if (await this.isVisible(this.errorMessage)) {
            return await this.getText(this.errorMessage);
        }
        return '';
    }

    async isLoginFormVisible(): Promise<boolean> {
        return await this.isVisible(this.usernameField) && 
               await this.isVisible(this.passwordField);
    }

    async clickForgotPassword(): Promise<void> {
        await this.click(this.forgotPasswordLink);
    }
}