import XCTest

/// Page object for the registration screen.
///
/// Uses accessibility identifiers from `AccessibilityIdentifiers.Authentication`
/// to locate registration form elements and perform sign-up actions.
class RegisterScreen: BaseScreen {

    // MARK: - Elements

    var usernameField: XCUIElement {
        app.textFields[AccessibilityIdentifiers.Authentication.registerUsernameField]
    }

    var emailField: XCUIElement {
        app.textFields[AccessibilityIdentifiers.Authentication.registerEmailField]
    }

    var passwordField: XCUIElement {
        app.secureTextFields[AccessibilityIdentifiers.Authentication.registerPasswordField]
    }

    var confirmPasswordField: XCUIElement {
        app.secureTextFields[AccessibilityIdentifiers.Authentication.registerConfirmPasswordField]
    }

    var registerButton: XCUIElement {
        app.buttons[AccessibilityIdentifiers.Authentication.registerButton]
    }

    var cancelButton: XCUIElement {
        app.buttons[AccessibilityIdentifiers.Authentication.registerCancelButton]
    }

    /// Fallback element lookup for the register/create account button using predicate
    var registerButtonByLabel: XCUIElement {
        app.buttons.containing(NSPredicate(format: "label CONTAINS[c] 'Register' OR label CONTAINS[c] 'Create Account'")).firstMatch
    }

    override var isDisplayed: Bool {
        // Registration screen is visible if any of the register-specific fields exist
        let usernameExists = usernameField.waitForExistence(timeout: timeout)
        let emailExists = emailField.exists
        return usernameExists || emailExists
    }

    // MARK: - Actions

    /// Fills in the registration form and submits it.
    /// Returns a MainTabScreen assuming successful registration leads to the main app.
    @discardableResult
    func register(username: String, email: String, password: String) -> MainTabScreen {
        waitForElement(usernameField)
        usernameField.focusAndType(username, app: app)

        emailField.focusAndType(email, app: app)

        passwordField.focusAndType(password, app: app)

        confirmPasswordField.focusAndType(password, app: app)

        // Try accessibility identifier first, fall back to label search
        if registerButton.exists {
            registerButton.tap()
        } else {
            registerButtonByLabel.tap()
        }

        return MainTabScreen(app: app)
    }

    /// Taps cancel to return to the login screen.
    @discardableResult
    func tapCancel() -> LoginScreen {
        if cancelButton.exists {
            cancelButton.tap()
        } else {
            // Fall back to navigation back button
            tapBackButton()
        }
        return LoginScreen(app: app)
    }
}
