/**
 * WalletUp Stripe Card Payment — WooCommerce Blocks Integration
 * Renders a Stripe Elements card form inside the blocks-based checkout.
 *
 * IMPORTANT: Stripe Elements allows exactly ONE Element of type 'card' per elements()
 * instance. Blocks checkout may re-render the payment method component multiple times
 * (shipping change, address change, cart recalc…), so we keep the Stripe instance,
 * elements, and cardElement at module scope and REUSE them — never call create('card')
 * more than once. On React unmount we detach from the DOM via element.unmount(); the
 * Element itself persists for the lifetime of the page.
 */
(function () {
    'use strict';

    var el = window.wp.element.createElement;
    var useState = window.wp.element.useState;
    var useEffect = window.wp.element.useEffect;
    var useRef = window.wp.element.useRef;
    var registerPaymentMethod = window.wc.wcBlocksRegistry.registerPaymentMethod;
    var getSetting = window.wc.wcSettings.getSetting;

    var settings = getSetting('wallet_up_card_data', {});
    var publishableKey = settings.publishableKey || '';
    var title = settings.title || 'Credit/Debit Card';
    var description = settings.description || '';
    var testMode = settings.testMode || false;

    if (!publishableKey) {
        return;
    }

    // Module-scope singletons. Survive React remounts.
    var stripe = null;
    var elements = null;
    var cardElement = null;
    var cardCreationError = null;

    function getCardElement() {
        if (cardCreationError) {
            return null;
        }
        if (!window.Stripe) {
            cardCreationError = 'Stripe.js failed to load. Please refresh the page.';
            return null;
        }
        try {
            if (!stripe) {
                stripe = window.Stripe(publishableKey);
            }
            if (!elements) {
                elements = stripe.elements();
            }
            if (!cardElement) {
                cardElement = elements.create('card', {
                    style: {
                        base: {
                            fontSize: '16px',
                            color: '#32325d',
                            fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
                            '::placeholder': { color: '#aab7c4' }
                        },
                        invalid: { color: '#fa755a' }
                    }
                });
            }
            return cardElement;
        } catch (e) {
            cardCreationError = e && e.message ? e.message : String(e);
            return null;
        }
    }

    function getStripe() {
        return stripe;
    }

    function StripeCardContent(props) {
        var eventRegistration = props.eventRegistration;
        var emitResponse = props.emitResponse;
        var cardElementRef = useRef(null);
        var errorState = useState('');
        var error = errorState[0];
        var setError = errorState[1];

        // Mount (or re-mount) the singleton card Element into this component's DOM node.
        useEffect(function () {
            var element = getCardElement();
            if (!element) {
                setError(cardCreationError || 'Card form unavailable. Please refresh the page.');
                return;
            }

            var changeHandler = function (event) {
                setError(event.error ? event.error.message : '');
            };

            var interval = setInterval(function () {
                var container = document.getElementById('walletup-stripe-card-block');
                if (!container) {
                    return;
                }
                clearInterval(interval);
                try {
                    // Detach from any previous mount point before re-mounting into the
                    // fresh DOM node from this component instance.
                    try { element.unmount(); } catch (e) { /* wasn't mounted yet */ }
                    element.mount(container);
                    cardElementRef.current = element;
                    element.on('change', changeHandler);
                } catch (e) {
                    setError('Failed to attach card form: ' + (e && e.message ? e.message : e));
                }
            }, 100);

            return function () {
                clearInterval(interval);
                // Detach from THIS component's DOM node. The Element itself is preserved
                // at module scope so the next remount reuses it without hitting the
                // "Can only create one Element of type card" error.
                try { element.off('change', changeHandler); } catch (e) {}
                try { element.unmount(); } catch (e) {}
            };
        }, []);

        useEffect(function () {
            if (!eventRegistration || !emitResponse) return;

            var unsubscribe = eventRegistration.onPaymentSetup(function () {
                var s = getStripe();
                if (!cardElementRef.current || !s) {
                    return {
                        type: emitResponse.responseTypes.ERROR,
                        message: 'Card form not ready. Please wait and try again.'
                    };
                }

                return s.createPaymentMethod({
                    type: 'card',
                    card: cardElementRef.current,
                }).then(function (result) {
                    if (result.error) {
                        return {
                            type: emitResponse.responseTypes.ERROR,
                            message: result.error.message
                        };
                    }
                    return {
                        type: emitResponse.responseTypes.SUCCESS,
                        meta: {
                            paymentMethodData: {
                                walletup_stripe_payment_method_id: result.paymentMethod.id
                            }
                        }
                    };
                });
            });

            return function () { unsubscribe(); };
        }, [eventRegistration, emitResponse]);

        var children = [];

        if (description) {
            children.push(el('p', { key: 'desc', style: { marginBottom: '12px' } }, description));
        }

        if (testMode) {
            children.push(el('p', {
                key: 'test',
                style: {
                    background: '#fff3cd',
                    border: '1px solid #ffc107',
                    padding: '8px 12px',
                    borderRadius: '4px',
                    fontSize: '13px',
                    marginBottom: '12px',
                    color: '#856404'
                }
            }, 'TEST MODE — Use card 4242 4242 4242 4242, any future date, any CVC.'));
        }

        children.push(el('div', {
            key: 'card',
            id: 'walletup-stripe-card-block',
            style: {
                padding: '12px',
                border: '1px solid #d9d9d9',
                borderRadius: '4px',
                background: '#fff',
                minHeight: '24px'
            }
        }));

        if (error) {
            children.push(el('div', {
                key: 'error',
                style: { color: '#fa755a', marginTop: '8px', fontSize: '14px' },
                role: 'alert'
            }, error));
        }

        return el('div', { className: 'walletup-stripe-card-block' }, children);
    }

    registerPaymentMethod({
        name: 'wallet_up_card',
        label: el('span', null, title),
        content: el(StripeCardContent),
        edit: el('div', null, 'WalletUp Card Payments (Stripe)'),
        canMakePayment: function () { return true; },
        ariaLabel: title,
        supports: {
            features: settings.supports || ['products']
        }
    });
})();
