/**
 * Radius Booking - Authentication Forms JavaScript
 *
 * Handles form interactions, validation, and AJAX submission.
 *
 * @package RadiusBooking
 * @version 1.0.0
 */

(function($) {
    'use strict';

    /**
     * Initialize auth forms functionality.
     *
     * @return {void}
     */
    function initAuthForms() {
        initPasswordToggles();
        initFormSwitching();
        initSignupValidation();
        initFormSubmission();
    }

    /**
     * Initialize password visibility toggles.
     *
     * @return {void}
     */
    function initPasswordToggles() {
        $('.radius-booking-password-toggle').on('click', handlePasswordToggle);
    }

    /**
     * Handle password toggle button click.
     *
     * @return {void}
     */
    function handlePasswordToggle() {
        var $button = $(this);
        var $wrapper = $button.closest('.radius-booking-password-wrapper');
        var $input = $wrapper.find('.radius-booking-input--password');
        var $eyeOpen = $button.find('.radius-booking-icon--eye-open');
        var $eyeClosed = $button.find('.radius-booking-icon--eye-closed');

        if ($input.attr('type') === 'password') {
            $input.attr('type', 'text');
            $eyeOpen.hide();
            $eyeClosed.show();
        } else {
            $input.attr('type', 'password');
            $eyeOpen.show();
            $eyeClosed.hide();
        }
    }

    /**
     * Initialize form switching between login and signup.
     *
     * @return {void}
     */
    function initFormSwitching() {
        $('.radius-booking-show-signup-form').on('click', handleShowSignup);
        $('.radius-booking-show-login-form').on('click', handleShowLogin);
    }

    /**
     * Handle show signup form link click.
     *
     * @param {Event} e - Click event.
     * @return {void}
     */
    function handleShowSignup(e) {
        e.preventDefault();
        $('.radius-booking-form-login').hide();
        $('.radius-booking-form-signup').show();
    }

    /**
     * Handle show login form link click.
     *
     * @param {Event} e - Click event.
     * @return {void}
     */
    function handleShowLogin(e) {
        e.preventDefault();
        $('.radius-booking-form-signup').hide();
        $('.radius-booking-form-login').show();
    }

    /**
     * Initialize signup form validation.
     *
     * @return {void}
     */
    function initSignupValidation() {
        var $signupForm = $('.radius-booking-form-signup');

        if (!$signupForm.length) {
            return;
        }

        var $submitButton = $signupForm.find('.radius-booking-button--signup');
        var $emailInput = $signupForm.find('input[name="email"]');
        var $passwordInput = $signupForm.find('input[name="password"]');
        var $confirmPasswordInput = $signupForm.find('input[name="confirm_password"]');
        var $termsCheckbox = $signupForm.find('input[name="terms_accepted"]');

        // Bind input events.
        $emailInput.on('input', function() {
            updateInputState($(this), isValidEmail($(this).val()));
            validateSignupForm($signupForm, $submitButton);
        });

        $passwordInput.on('input', function() {
            updateInputState($(this), isValidPassword($(this).val()));

            if ($confirmPasswordInput.val().length > 0) {
                updateInputState($confirmPasswordInput, doPasswordsMatch($passwordInput, $confirmPasswordInput));
            }

            validateSignupForm($signupForm, $submitButton);
        });

        $confirmPasswordInput.on('input', function() {
            updateInputState($(this), doPasswordsMatch($passwordInput, $confirmPasswordInput));
            validateSignupForm($signupForm, $submitButton);
        });

        $termsCheckbox.on('change', function() {
            validateSignupForm($signupForm, $submitButton);
        });
    }

    /**
     * Validate email format.
     *
     * @param {string} email - Email to validate.
     * @return {boolean} Whether email is valid.
     */
    function isValidEmail(email) {
        var pattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        return pattern.test(email);
    }

    /**
     * Validate password strength.
     *
     * @param {string} password - Password to validate.
     * @return {boolean} Whether password meets requirements.
     */
    function isValidPassword(password) {
        return password.length >= 8;
    }

    /**
     * Check if passwords match.
     *
     * @param {jQuery} $passwordInput        - Password input element.
     * @param {jQuery} $confirmPasswordInput - Confirm password input element.
     * @return {boolean} Whether passwords match.
     */
    function doPasswordsMatch($passwordInput, $confirmPasswordInput) {
        return $passwordInput.val() === $confirmPasswordInput.val();
    }

    /**
     * Update input validation state.
     *
     * @param {jQuery}  $input - Input element.
     * @param {boolean} valid  - Whether input is valid.
     * @return {void}
     */
    function updateInputState($input, valid) {
        $input.removeClass('is-valid is-invalid');

        if ($input.val().length > 0) {
            $input.addClass(valid ? 'is-valid' : 'is-invalid');
        }
    }

    /**
     * Validate the entire signup form and update submit button state.
     *
     * @param {jQuery} $form         - Form element.
     * @param {jQuery} $submitButton - Submit button element.
     * @return {void}
     */
    function validateSignupForm($form, $submitButton) {
        var $emailInput = $form.find('input[name="email"]');
        var $passwordInput = $form.find('input[name="password"]');
        var $confirmPasswordInput = $form.find('input[name="confirm_password"]');
        var $termsCheckbox = $form.find('input[name="terms_accepted"]');

        var isEmailValid = isValidEmail($emailInput.val());
        var isPasswordValid = isValidPassword($passwordInput.val());
        var passwordsMatch = doPasswordsMatch($passwordInput, $confirmPasswordInput);
        var termsAccepted = $termsCheckbox.is(':checked');

        var isFormValid = isEmailValid && isPasswordValid && passwordsMatch && termsAccepted;

        $submitButton.prop('disabled', !isFormValid);
    }

    /**
     * Initialize AJAX form submission.
     *
     * @return {void}
     */
    function initFormSubmission() {
        $('.radius-booking-form-login, .radius-booking-form-signup').on('submit', handleFormSubmit);
    }

    /**
     * Handle form submission.
     *
     * @param {Event} e - Submit event.
     * @return {void}
     */
    function handleFormSubmit(e) {
        e.preventDefault();

        var $form = $(this);
        var $submitButton = $form.find('button[type="submit"]');

        // Set loading state.
        $submitButton.addClass('is-loading').prop('disabled', true);

        // Clear previous errors.
        $form.find('.radius-booking-form-error').remove();
        console.log(window.radius_booking_auth_param.ajax_url)
        // Submit form via AJAX.
        $.ajax({
            url: window.radius_booking_auth_param.ajax_url,
            type: 'POST',
            data: $form.serialize(),
            dataType: 'json',
            success: function(response) {
                handleFormSuccess($form, $submitButton, response);
            },
            error: function(xhr, status, error) {
                handleFormError($form, $submitButton, error);
            }
        });
    }

    /**
     * Handle successful form submission response.
     *
     * @param {jQuery} $form         - Form element.
     * @param {jQuery} $submitButton - Submit button element.
     * @param {Object} response      - AJAX response.
     * @return {void}
     */
    function handleFormSuccess($form, $submitButton, response) {
        if (response.success) {
            // Redirect on success.
            if (response.data && response.data.redirect_url) {
                window.location.href = response.data.redirect_url;
            } else {
                window.location.reload();
            }
        } else {
            // Show error message.
            var message = (response.data && response.data.message)
                ? response.data.message
                : 'An error occurred. Please try again.';

            showFormError($form, message);

            // Reset button state.
            $submitButton.removeClass('is-loading').prop('disabled', false);
        }
    }

    /**
     * Handle form submission error.
     *
     * @param {jQuery} $form         - Form element.
     * @param {jQuery} $submitButton - Submit button element.
     * @param {string} error         - Error message.
     * @return {void}
     */
    function handleFormError($form, $submitButton, error) {
        console.error('Form submission error:', error);
        showFormError($form, 'An error occurred. Please try again.');

        $submitButton.removeClass('is-loading').prop('disabled', false);
    }

    /**
     * Display an error message in the form.
     *
     * @param {jQuery} $form   - Form element.
     * @param {string} message - Error message to display.
     * @return {void}
     */
    function showFormError($form, message) {
        var $errorDiv = $('<div>', {
            'class': 'radius-booking-form-error',
            'css': {
                'margin-bottom': '1rem',
                'padding': '0.75rem 1rem',
                'background': '#fef2f2',
                'border': '1px solid #fecaca',
                'border-radius': '8px',
                'color': '#dc2626',
                'font-size': '0.875rem'
            },
            'text': message
        });

        $form.prepend($errorDiv);
    }

    // Initialize when DOM is ready.
    $(document).ready(initAuthForms);

})(jQuery);