(function($) {
    'use strict';

    if (typeof walletUpStripe === 'undefined' || !walletUpStripe.publishableKey) {
        return;
    }

    var stripe = Stripe(walletUpStripe.publishableKey);
    var elements = stripe.elements();
    var cardElement = elements.create('card', {
        style: {
            base: {
                fontSize: '16px',
                color: '#32325d',
                fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
                '::placeholder': { color: '#aab7c4' }
            },
            invalid: { color: '#e74c3c' }
        }
    });

    var mounted = false;

    function mountCard() {
        var container = document.getElementById('walletup-stripe-card-element');
        if (container && !mounted) {
            // Detach from any previous container (WC re-renders the payment section on
            // every updated_checkout, destroying the old DOM — Stripe's Element persists
            // at module scope and must be explicitly unmounted before re-mounting).
            try { cardElement.unmount(); } catch (e) { /* wasn't mounted */ }
            try {
                cardElement.mount('#walletup-stripe-card-element');
                mounted = true;
            } catch (e) {
                var errorEl = document.getElementById('walletup-stripe-card-errors');
                if (errorEl) {
                    errorEl.textContent = 'Failed to load card form. Please refresh the page.';
                }
            }
        }
    }

    $(document).ready(function() {
        mountCard();
    });

    $(document.body).on('updated_checkout', function() {
        mounted = false;
        mountCard();
    });

    cardElement.on('change', function(event) {
        var errorEl = document.getElementById('walletup-stripe-card-errors');
        if (errorEl) {
            errorEl.textContent = event.error ? event.error.message : '';
        }
    });

    var form = $('form.checkout, form#order_review');

    form.on('checkout_place_order_wallet_up_card', function() {
        var pmField = document.getElementById('walletup_stripe_payment_method_id');

        if (pmField && pmField.value) {
            return true;
        }

        stripe.createPaymentMethod({
            type: 'card',
            card: cardElement,
            billing_details: {
                name: ($('#billing_first_name').val() + ' ' + $('#billing_last_name').val()).trim(),
                email: $('#billing_email').val(),
                address: {
                    line1: $('#billing_address_1').val(),
                    city: $('#billing_city').val(),
                    state: $('#billing_state').val(),
                    postal_code: $('#billing_postcode').val(),
                    country: $('#billing_country').val()
                }
            }
        }).then(function(result) {
            if (result.error) {
                var errorEl = document.getElementById('walletup-stripe-card-errors');
                if (errorEl) {
                    errorEl.textContent = result.error.message;
                }
                form.removeClass('processing').unblock();
            } else {
                if (pmField) {
                    pmField.value = result.paymentMethod.id;
                }
                form.submit();
            }
        });

        return false;
    });

    var urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('walletup_stripe_3ds') === '1') {
        var clientSecret = urlParams.get('client_secret');
        if (clientSecret) {
            stripe.handleCardAction(clientSecret).then(function(result) {
                if (result.error) {
                    alert(result.error.message);
                    window.location.href = urlParams.get('return_url') || '/checkout/';
                } else {
                    $.post(walletUpStripe.ajaxUrl, {
                        action: 'wallet_up_stripe_confirm_payment',
                        nonce: walletUpStripe.nonce,
                        payment_intent_id: result.paymentIntent.id,
                        order_id: urlParams.get('order_id')
                    }, function(response) {
                        if (response.success) {
                            window.location.href = response.data.redirect;
                        } else {
                            alert(response.data.message || 'Payment confirmation failed');
                        }
                    });
                }
            });
        }
    }
})(jQuery);
