(function($) {

    if($('.ehx-datatable').length) {
        let table = new DataTable('.ehx-datatable');
    }

    if($('.ehx-select2').length) {
        $('.ehx-select2').select2();
    }

    $(document).on('submit', 'form#ehxme_form_submit', async function (e) {
        e.preventDefault();

        // Gather form data
        let form = $(this);
        let file = form.attr("enctype");
        let reset = form.data("reset");
        let submitBtn = form.find('button[type="submit"]');
        let btnLoaderEl = submitBtn.find('#ehx-loader');
        let btnTextEl = submitBtn.find('#ehx-btn-text');
        let btnLoaderCurrTxt = btnTextEl.text();
        let btnLoaderLoadTxt = submitBtn.data('submit');

        form.find('.ehx-input').removeClass('is-invalid');
        form.find('.invalid-feedback').text('');

        let options = {
            type: 'POST',
            url: ehxme_obj.ajax_url,
            dataType: "JSON",
        };

        if (typeof file == "undefined") {
            options.data = form.serialize();
        } else {
            options.data = new FormData(form[0]);
            options.contentType = false;
            options.enctype = file;
            options.processData = false;

            if (card) {
                let { token, error } = await stripe.createToken(card);
                if (typeof error != 'undefined') {
                    return;
                }
                options.data.append('stripe_token', JSON.stringify(token));
            }
        }

        $.ajax({
            ...options,
            beforeSend: () => {
                submitBtn.attr("disabled", true);
                btnLoaderEl.css("display", 'block');
                btnTextEl.text(btnLoaderLoadTxt);
            },
            success: (response) => {
                if(typeof reset == 'undefined') {
                    form.trigger("reset");
                }
                handleSuccess(response);
            },
            complete: () => {
                submitBtn.attr("disabled", false);
                btnLoaderEl.css("display", 'none');
                btnTextEl.text(btnLoaderCurrTxt);
            },
            error: function (e) {
                handleError(e);
            },
        });
    });

    // let cards;
    let card;
    let stripe;
    // Stripe API
    function initilizeCard(){
        stripe = Stripe($('#card_element').data('key'));
        var elements = stripe.elements();
        var style = {
            base: {
                color: "#32325d",
                fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
                fontSmoothing: "antialiased",
                fontSize: "16px",
                padding: '16px',
                "::placeholder": {
                    color: "#aab7c4",
                },
            },
            invalid: {
                color: "#fa755a",
                iconColor: "#fa755a",
            },
        };
        card = elements.create("card", { hidePostalCode: true, style: style });
        return card;
    };

    function waitForElm() {
        const element = document.querySelector('#card_element')
        return new Promise((resolve) => {
            if (element) {
                return resolve(element);
            }
            const observer = new MutationObserver((mutations) => {
                if (element) {
                    observer.disconnect();
                    resolve(element);
                }
            });
            observer.observe(document.body, {
                childList: true,
                subtree: true,
            });
        });
    }

    function renderStripeElement(){
        waitForElm().then((elm) => {
            let cardElement = document.getElementById('card_element');
            card = initilizeCard();
            card.mount(cardElement);
        });
    }

    if($('#card_element').length) {
        setTimeout(() => {
            renderStripeElement()
        }, 2000);
    }

    $('.ehx-container').on('click', '#ehx-tab-link', function(e) {
        e.preventDefault();

        $('.ehx-tabs .ehx-tab-link').removeClass('active');
        $(this).addClass('active');

        $('.ehx-tab-contents .ehx-tab-content').removeClass('active');
        $(`.ehx-tab-contents #tab-${$(this).data('tab')}`).addClass('active');
        
    });

})(jQuery);