jQuery(function ($) {

    function isValidPhone(phone) {
        return /^[0-9]{8,15}$/.test(phone);
    }

    function initCashToCash() {

        // Évite les doubles événements
        $(document)
            .off('click.cashToCashPhone')
            .on('click.cashToCashPhone', '#cash_to_cash_phone_validate', function (e) {

                e.preventDefault();

                var phone = $('#cash_to_cash_phone').val().trim();

                if (!isValidPhone(phone)) {
                    $('#cash_to_cash_phone_error').show();
                    return;
                }

                $('#cash_to_cash_phone_error').hide();

                $('#cash-to-cash-step-1').removeClass('active');
                $('#cash-to-cash-step-2').addClass('active');

                setTimeout(function () {

                    $('#cash-to-cash-step-2').removeClass('active');
                    $('#cash-to-cash-step-3').addClass('active');

                }, 3000);

            });

        $(document)
            .off('click.cashToCashFinalize')
            .on('click.cashToCashFinalize', '#cash_to_cash_finalize_payment', function (e) {

                e.preventDefault();

                var button = $(this);

                $('#cash-to-cash-step-3-loader').fadeIn(200);

                button.prop('disabled', true);

                setTimeout(function () {

                    $('#cash-to-cash-step-3-loader').fadeOut(200, function () {

                        $('#cash-to-cash-step-3').removeClass('active');
                        $('#cash-to-cash-step-4-loader').addClass('active');

                        setTimeout(function () {

                            $('#cash-to-cash-step-4-loader').removeClass('active');
                            $('#cash-to-cash-step-4').addClass('active');

                            if ($('#cash-to-cash-step-4').length) {

                                $('html, body').animate({
                                    scrollTop: $('#cash-to-cash-step-4').offset().top - 100
                                }, 500);

                            }

                        }, 1000);

                    });

                }, 3000);

            });

        $(document)
            .off('input.cashToCashReference')
            .on('input.cashToCashReference', 'input[name="cash_to_cash_transaction_id"]', function () {

                var val = $(this).val().replace(/\D/g, '');

                if (val.length > 15) {
                    val = val.substring(0, 15);
                }

                $(this).val(val);

            });

    }

    // Initialisation
    initCashToCash();

    // WooCommerce recharge le checkout
    $(document.body).on('updated_checkout', function () {
        initCashToCash();
    });

});