( function( $ ) {

    var form_completed = false,
        display_error = '',
        style = {
            base: { color: '#32325d', fontSmoothing: 'antialiased', fontSize: '16px', '::placeholder': { color: '#aab7c4' } },
            invalid: { color: '#fa755a', iconColor: '#fa755a' }
        };

    const tcstripe = {

        /**
         * Validate Payment
         */
        order_confirmation: function( result ) {
            $.post( tc_ajax.ajaxUrl, { action: 'order_confirmation', payment_result: result, nonce: tc_ajax.ajaxNonce },
                function( response ) {
                    if ( response != false ) {
                        window.location.assign( response );
                    } else {
                        tcstripe.form_loading( false );
                        let container = $( 'div#stripe-elements-3d-secure' ), maxHeight = container.find( '.inner-wrapper' ).outerHeight();
                        container.css( 'max-height', maxHeight + 'px' );
                    }
                }
            );
        },

        /**
         * Show/Hide elements
         *
         * @param attr_val
         */
        form_loading: function( attr_val ) {

            switch ( attr_val ) {
                case true:
                    $( '.StripeElement' ).css( 'pointer-events', 'none' );
                    $( '#stripe-submit' ).attr( 'disabled', true ).hide();
                    $( '#stripe-loading' ).show();
                    break;

                case false:
                    $( '.StripeElement' ).css( 'pointer-events', 'initial' );
                    $( '#stripe-submit' ).attr( 'disabled', false ).show();
                    $( '#stripe-loading' ).hide();
                    break;

                default:
                    $( '.StripeElement' ).css( 'pointer-events', 'none' );
                    $( '#stripe-submit' ).attr( 'disabled', true );
                    $( '#stripe-loading' ).show();
            }
        }
    };

    $( document ).ready( function() {

        display_error = document.getElementById( 'card-errors' );

        /**
         * Initialize Stripe Elements and Error handling
         */
        try {

            var stripe = Stripe( stripe_client.publishable_key ),
                elements = stripe.elements(),
                card = elements.create( "card", { hidePostalCode: true, style: style } );
            card.mount( "#card-element" );

        } catch ( err ) {
            display_error.textContent = err;
        }

        /**
         * Handle real-time validation errors from the card Element.
         */
        card.addEventListener( 'change', function( event ) {

            let cardContainer = $( '#card-element' ),
                formContainer = cardContainer.closest( '.tc_gateway_form' );

            if ( event.error ) {
                display_error.textContent = event.error.message;
                formContainer.css( { 'max-height': parseInt( cardContainer.closest( '.inner-wrapper' ).outerHeight() ) + 'px' } );
                form_completed = false;

            } else {
                display_error.textContent = '';
                form_completed = true;
            }
        } );

        /**
         * Process Payment when "Submit Payment" Button is clicked
         */
        $( '#stripe-submit' ).on( 'click', function( ev ) {
            ev.preventDefault();

            if ( form_completed ) {

                tcstripe.form_loading( true );
                $.post( tc_ajax.ajaxUrl, { action: "process_payment", nonce: tc_ajax.ajaxNonce }, function( response ) {

                    if ( typeof response.error === 'undefined' ) {
                        stripe.confirmCardPayment( response.client_secret, {
                            receipt_email: response.email,
                            payment_method: {
                                card: card,
                                billing_details: {
                                    name: response.customer_name,
                                    email: response.email
                                }
                            }
                        } ).then( function( result ) {

                            if ( typeof result.error !== 'undefined' ) {

                                /*
                                 * Payment intent request has failed
                                 * Allow the user to select another payment method
                                 */
                                display_error.textContent = result.error.message;
                                tcstripe.order_confirmation( result );

                            } else {

                                // The payment has been processed
                                switch ( result.paymentIntent.status ) {
                                    case 'succeeded':
                                    case 'requires_capture':
                                        display_error.textContent = '';
                                        tcstripe.order_confirmation( result.paymentIntent );
                                        break;
                                }
                            }
                        } );

                    } else {
                        display_error.textContent = response.error;
                    }
                } );
            }
        } );
    });

} )( jQuery );
