class SellAuth {
    validateRegisterField(el) {
        const formDataArray = $('#form').serializeArray();
        const formDataObject = formDataArray.reduce(function (obj, item) {
            obj[item.name] = item.value;
            return obj;
        }, {});

        $.ajax({
            headers: {
                'X-CSRF-Token': $('meta[name="csrf_token"]').attr('content'),
            },
            url: ajaxUrl + '/auth/register/validate-form',
            type: 'POST',
            data: formDataObject,
            error: function (jqXHR, textStatus, errorThrown) {
                if (jqXHR.status !== 422) {
                    return;
                }

                const errors = JSON.parse(jqXHR.responseText).errors;
                const fieldId = $(el).attr('name');
                const fieldErrors = errors[fieldId] ?? [];

                if (fieldErrors.length > 0) {
                    $(el).addClass('error-highlight');
                    $(el).parent().find('.error-field').html(fieldErrors[0]);

                    // For Password Confirmation
                    if(fieldId === 'password' && fieldErrors[0].endsWith('do not match')) {
                        const elPswConf = $(el).closest('form').find('input[name="password_confirmation"]');
                        $(elPswConf).addClass('error-highlight');
                    }
                }
            },
        });
    }
    validateLoginField(el) {
        const errorMessages = {
            'existemail': 'Please enter email address',
            'existpassword': 'Please enter password',
        }

        const errorMsg = errorMessages[$(el).attr('id')] ?? 'This field is required';

        if ($(el).val() === '') {
            $(el).addClass("error-highlight");
            $(el).parent().find('.error-field').html(errorMsg);
        }
    }
}

const sellAuth = new SellAuth();

// Register - Hide errors when input fields loses focus and revalidate
$(document).on('focusout', 'form #register .input-field', function () {
    let el = $(this);

    // Clear errors
    el.removeClass('error-highlight');
    el.parent().find('.error-field').html('');

    // Do not validate if password_confirmation empty
    if (el.attr('name') === 'password') {
        const passwordConfEl = $('form#form input[name="password_confirmation"]');
        passwordConfEl.removeClass('error-highlight');
        passwordConfEl.parent().find('.error-field').html('');

        const elPassConfirmation = el.closest('form').find('input[name="password_confirmation"]');
        if (el.val() !== '' && elPassConfirmation.val() === '') {
            return;
        }
    }

    // Validate on password field
    if(el.attr('name') === 'password_confirmation') {
        sellAuth.validateRegisterField(el);
        el = $('form#form input[name="password"]');
        el.removeClass('error-highlight');
        el.parent().find('.error-field').html('');
    }

    sellAuth.validateRegisterField(el);
});

// Login - Hide errors when input fields loses focus and revalidate
$(document).on('focusout', 'form #login .input-field', function () {
    $(this).removeClass('error-highlight');
    $(this).parent().find('.error-field').html('');
    sellAuth.validateLoginField(this);
});