var stripe;
var elements;

export async function initCardElement(token) {
    if (!window.Stripe) {
        await loadStripe();
    }

    stripe = Stripe(token);
    elements = stripe.elements();

    var cardElement = elements.create('card', {
        hidePostalCode: true,
        style: {
            base: {
                fontSize: '16px',
                lineHeight: '1.5',
            }
        }
    });
    cardElement.mount('#card-element');

    cardElement.on('focus', function () {
        document.getElementById('stripe-card').classList.add('element-focused');
    });

    cardElement.on('blur', function () {
        document.getElementById('stripe-card').classList.remove('element-focused');
    });

    cardElement.on('change', function (event) {
        var displayError = document.getElementById('stripe-card-error');
        if (event.error) {
            displayError.textContent = event.error.message;
            document.getElementById('stripe-card').classList.add('invalid');
        } else {
            displayError.textContent = '';
            document.getElementById('stripe-card').classList.remove('invalid');
        }
    });
}

export function createCardToken(cardData) {
    var cardElement = elements.getElement('card');

    return stripe.createToken(cardElement, JSON.parse(cardData)).then((result) => {
        if (result.error) {
            return { error: result.error.message };
        } else {
            return { token: result.token.id };
        }
    });
}

async function loadStripe() {
    return new Promise((resolve, reject) => {
        if (window.Stripe) {
            resolve();
            return;
        }

        const script = document.createElement('script');
        script.src = "https://js.stripe.com/v3/";
        script.async = true;
        script.onload = () => {
            window.StripeInstance = Stripe;
            resolve();
        };
        script.onerror = () => reject(new Error("Failed to load Stripe.js"));

        document.head.appendChild(script);
    });
}