import { ready } from '@site/js/utils/dom.js';

/**
 * Stripe Checkout integration.
 *
 * The "Pay with Stripe" button opens the Stripe Checkout overlay. On token
 * receipt we append a hidden `stripeToken` input to the surrounding form
 * and submit it.
 */
ready(() => {
    const button = document.getElementById('payWithStripe');
    if (!button) {
        return;
    }

    button.addEventListener('click', (event) => {
        event.preventDefault();

        const form = button.closest('form');
        if (!form) {
            return;
        }

        // Stripe accepts `data-*` attributes on the button as its opts.
        const opts = {
            ...button.dataset,
            token(result) {
                const tokenInput = document.createElement('input');
                tokenInput.type = 'hidden';
                tokenInput.name = 'stripeToken';
                tokenInput.value = result.id;
                form.appendChild(tokenInput);
                form.submit();
            },
        };

        StripeCheckout.open(opts);
    });
});
