/**
 * ConvesioPay Unified WooCommerce Blocks Integration
 * Handles both card and BTCPay payments based on detected type
 */

(function() {
    'use strict';

    // Use the proper WooCommerce Blocks API with error handling
    const { registerPaymentMethod } = window.wc?.wcBlocksRegistry || {};
    const { createElement, useEffect, useState } = wp?.element || {};
    const { __ } = wp?.i18n || {};
    const getSetting = (window.wc?.wcSettings?.getSetting) || function(key, defaultValue) { return defaultValue; };

    // Check if required APIs are available
    if (!registerPaymentMethod) {
        return;
    }
    // Get ConvesioPay settings
    const settings = getSetting('peachpay_convesiopay_unified_data', {});
    
    // Get active payment methods from settings
    const activeMethods = settings.active_methods || [];

    // Helper: determine if BTCPay/crypto is enabled according to the
    // unified gateway configuration. This is the client-side source of
    // truth for deciding whether any BTCPay sessions/intents should be
    // created.
    // 
    // STRICT CHECK: Only returns true if 'crypto' is explicitly in active_methods,
    // which should only happen when the BTC Pay gateway is enabled in WooCommerce.
    const isBtcpayEnabled = () => {
        // Only return true if 'crypto' is explicitly in the array
        // This ensures BTC Pay is only enabled when the gateway is actually enabled
        const isEnabled = activeMethods.includes('crypto') || activeMethods.includes('btcpay');
        
        // Additional safety: if active_methods is empty or doesn't include crypto, BTC Pay is disabled
        if (activeMethods.length === 0) {
            return false;
        }
        
        return isEnabled;
    };

    const isGooglePayEnabled = () => {
        if (activeMethods.length === 0) {
            return false;
        }

        return activeMethods.includes('googlepay');
    };

    // Global state management
    let convesioPayComponent = null;
    let isComponentMounted = false;
    let btcPaySession = null;
    let isSessionCreated = false;
    let paymentConfirmedData = null;
    let currentPaymentMethod = null;
    let lastKnownCartTotal = 0;
    let applePayAuthorizedAmount = null;
    let googlePayAuthorizedAmount = null;
    let lastKnownCustomerEmail = '';

    // Debounce flag for cart refresh
    let cartRefreshTimeout = null;
    let isRefreshingCart = false;

    /**
     * Reset session state for new checkout
     */
    const resetSessionState = () => {
        convesioPayComponent = null;
        isComponentMounted = false;
        btcPaySession = null;
        isSessionCreated = false;
        paymentConfirmedData = null;
        currentPaymentMethod = null;
        lastKnownCustomerEmail = '';
    };

    /**
     * Calculate the correct order total for a specific payment method.
     * Uses the base cart total (without gateway fee) and adds the correct fee for the method.
     * 
     * @param {string} method - The payment method (card, applepay, btcpay)
     * @returns {number} The correct total in cents for ConvesioPay
     */
    const calculateCorrectTotalForMethod = (method) => {
        const feeConfig = settings.fee_config || window.peachpay_convesiopay_unified_data?.fee_config || {};
        
        // Get current cart total from WooCommerce Blocks store (includes coupons, shipping, tax)
        let currentTotalInCents = 0;
        if (window.wp && window.wp.data && window.wp.data.select) {
            try {
                const store = window.wp.data.select('wc/store/cart');
                const cartTotals = store.getCartTotals();
                if (cartTotals && cartTotals.total_price) {
                    currentTotalInCents = parseInt(cartTotals.total_price);
                }
            } catch (e) {
                // Fallback below
            }
        }
        
        // Convert to dollars and use as base (this is the live total with coupons applied)
        let baseCartTotal = currentTotalInCents / 100;
        
        // Fallback to PHP-provided value if blocks store read fails
        if (baseCartTotal <= 0) {
            baseCartTotal = parseFloat(settings.cart_total || window.peachpay_convesiopay_unified_data?.cart_total || 0) || 0;
        }
        
        // Get fee config for the requested method
        const methodConfig = feeConfig[method] || {};
        
        // Calculate fee for this method
        let feeAmount = 0;
        if (methodConfig.enabled) {
            const feePercent = parseFloat(methodConfig.amount) || 0;
            if (methodConfig.type === 'percent' || methodConfig.type === 'percentage') {
                feeAmount = baseCartTotal * (feePercent / 100);
            } else {
                feeAmount = feePercent;
            }
            feeAmount = Math.round((feeAmount + 0.00000001) * 100) / 100;
        }
        
        // Calculate total and convert to cents
        const totalAmount = baseCartTotal + feeAmount;
        return Math.round(totalAmount * 100);
    };

    /**
     * Update the fee display on the checkout page without triggering a full refresh.
     * This uses the fee configuration passed from PHP.
     * Creates the fee row if it doesn't exist, or updates existing fee rows.
     * IMPORTANT: Removes duplicate fee rows to prevent multiple fee lines.
     * 
     * @param {string} method - The selected payment method (card, applepay, btcpay)
     */
    const updateFeeDisplay = (method) => {
        // Get fee config from settings or window
        const feeConfig = settings.fee_config || window.peachpay_convesiopay_unified_data?.fee_config || {};
        const methodConfig = feeConfig[method] || feeConfig['card'] || {};
        
        // Get current cart total from WooCommerce Blocks store (includes coupons)
        let baseCartTotal = 0;
        if (window.wp && window.wp.data && window.wp.data.select) {
            try {
                const store = window.wp.data.select('wc/store/cart');
                const cartTotals = store.getCartTotals();
                if (cartTotals && cartTotals.total_price) {
                    baseCartTotal = parseInt(cartTotals.total_price) / 100;
                }
            } catch (e) {
                // Fallback below
            }
        }
        
        // Fallback to PHP-provided value if blocks store read fails
        if (baseCartTotal <= 0) {
            baseCartTotal = parseFloat(settings.cart_total || window.peachpay_convesiopay_unified_data?.cart_total || 0);
        }
        
        // Calculate fee based on method config
        let feeAmount = 0;
        if (methodConfig.enabled) {
            const configAmount = parseFloat(methodConfig.amount || 0);
            if (methodConfig.type === 'percent' || methodConfig.type === 'percentage') {
                feeAmount = baseCartTotal * (configAmount / 100);
            } else {
                feeAmount = configAmount;
            }
        }
        
        // Get the fee label from config
        const feeLabel = methodConfig.label || 'Payment gateway fee';
        
        
        // Find existing fee rows - update them for immediate visual feedback
        // Don't remove WooCommerce's fee rows - let server-side refresh handle authoritative values
        const allFeeRows = document.querySelectorAll('.wc-block-components-totals-fees');
        const subtotalRow = document.querySelector('.wc-block-components-totals-subtotal');
        const shippingRow = document.querySelector('.wc-block-components-totals-shipping');
        const orderTotalRow = document.querySelector('.wc-block-components-totals-footer-item');
        
        // Use the first fee row for updates (WooCommerce's row)
        let primaryFeeRow = allFeeRows.length > 0 ? allFeeRows[0] : null;
        
        if (feeAmount > 0) {
            if (!primaryFeeRow) {
                // Create fee row if none exists
                primaryFeeRow = document.createElement('div');
                primaryFeeRow.className = 'wc-block-components-totals-item wc-block-components-totals-fees';
                primaryFeeRow.setAttribute('data-convesiopay-fee', 'true');
                primaryFeeRow.innerHTML = `
                    <span class="wc-block-components-totals-item__label">${feeLabel}</span>
                    <span class="wc-block-components-totals-item__value"><span class="wc-block-formatted-money-amount wc-block-components-formatted-money-amount wc-block-components-totals-item__value">$${feeAmount.toFixed(2)}</span></span>
                `;
                
                // Insert after subtotal
                if (subtotalRow && subtotalRow.parentElement) {
                    subtotalRow.parentElement.insertBefore(primaryFeeRow, subtotalRow.nextSibling);
                } else if (shippingRow && shippingRow.parentElement) {
                    shippingRow.parentElement.insertBefore(primaryFeeRow, shippingRow);
                } else if (orderTotalRow && orderTotalRow.parentElement) {
                    orderTotalRow.parentElement.insertBefore(primaryFeeRow, orderTotalRow);
                }
            } else {
                // Update existing fee row
                const feeLabelEl = primaryFeeRow.querySelector('.wc-block-components-totals-item__label');
                const feeValueEl = primaryFeeRow.querySelector('.wc-block-components-totals-item__value');
                
                if (feeLabelEl) {
                    feeLabelEl.textContent = feeLabel;
                }
                if (feeValueEl) {
                    // Check if there's a nested span for the value
                    const innerValue = feeValueEl.querySelector('.wc-block-formatted-money-amount');
                    if (innerValue) {
                        innerValue.textContent = '$' + feeAmount.toFixed(2);
                    } else {
                        feeValueEl.textContent = '$' + feeAmount.toFixed(2);
                    }
                }
            }
            
            // Make sure fee row is visible
            primaryFeeRow.style.display = '';
        } else {
            // No fee - hide or remove fee row if it exists
            if (primaryFeeRow) {
                primaryFeeRow.style.display = 'none';
            }
        }
        
        // NOTE: Don't update total here - let WooCommerce's server-side refresh handle it
        // via storeMethodAndRefreshCart() -> triggerBlocksCartRefresh()
        // This ensures correct calculation with taxes, coupons, shipping, etc.
    };

    /**
     * Store the selected ConvesioPay method in WC session and refresh the Blocks cart store.
     * This ensures the fee row is properly rendered by WooCommerce.
     * 
     * @param {string} method - The selected payment method (card, applepay, btcpay)
     */
    const storeMethodAndRefreshCart = (method) => {
        
        // Get AJAX URL from settings or fallback to wc_checkout_params
        const ajaxUrl = settings.ajax_url || window.wc_checkout_params?.ajax_url || '/wp-admin/admin-ajax.php';
        
        // Store method in WC session via AJAX
        const formData = new FormData();
        formData.append('action', 'peachpay_store_convesiopay_method');
        formData.append('convesiopay_selected_method', method);
        
        fetch(ajaxUrl, {
            method: 'POST',
            credentials: 'same-origin',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            
            // Update the DOM directly for immediate visual feedback
            updateFeeDisplay(method);
            
            // Trigger a debounced cart refresh to update the total
            // This calls the Store API and updates total from response (without component remount)
            debouncedCartRefresh();
        })
        .catch(() => {
            // Handle error silently - still update DOM as fallback
            updateFeeDisplay(method);
        });
    };
    
    /**
     * Debounced cart refresh - prevents multiple rapid calls.
     * Calls the Store API and updates the total from the response.
     */
    const debouncedCartRefresh = () => {
        // Clear any pending refresh
        if (cartRefreshTimeout) {
            clearTimeout(cartRefreshTimeout);
        }
        
        // Prevent re-entry
        if (isRefreshingCart) {
            return;
        }
        
        // Debounce: wait 500ms before refreshing
        cartRefreshTimeout = setTimeout(() => {
            refreshCartAndUpdateTotal();
        }, 500);
    };
    
    /**
     * Call the Store API to get updated cart totals and update the DOM.
     * Does NOT trigger component remount - only updates the total display.
     */
    const refreshCartAndUpdateTotal = () => {
        if (isRefreshingCart) {
            return;
        }
        
        isRefreshingCart = true;
        
        // Call the WooCommerce Store API to get updated cart
        const storeApiUrl = '/wp-json/wc/store/v1/cart';
        
        fetch(storeApiUrl, {
            method: 'GET',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/json',
                'Nonce': window.wcBlocksMiddlewareConfig?.storeApiNonce || ''
            }
        })
        .then(response => response.json())
        .then(cart => {
            
            // Update the total from the cart response
            if (cart && cart.totals) {
                const totalPrice = parseInt(cart.totals.total_price) / 100; // Convert from cents
                const currencySymbol = cart.totals.currency_symbol || '$';
                
                // Find and update the total display
                const orderTotalRow = document.querySelector('.wc-block-components-totals-footer-item');
                if (orderTotalRow) {
                    const totalValueEl = orderTotalRow.querySelector('.wc-block-components-totals-item__value');
                    if (totalValueEl) {
                        const innerValue = totalValueEl.querySelector('.wc-block-formatted-money-amount');
                        if (innerValue) {
                            innerValue.textContent = currencySymbol + totalPrice.toFixed(2);
                        } else {
                            totalValueEl.textContent = currencySymbol + totalPrice.toFixed(2);
                        }
                    }
                }
                
                // Also check if fees are in the response and update fee display
                if (cart.fees && cart.fees.length > 0) {
                    const fee = cart.fees[0];
                    // Use parseFloat instead of parseInt to preserve decimal precision
                    const feeAmount = parseFloat(fee.totals.total) / 100;
                    
                    // Update fee row from API response
                    const feeRow = document.querySelector('.wc-block-components-totals-fees');
                    if (feeRow) {
                        const feeValueEl = feeRow.querySelector('.wc-block-components-totals-item__value');
                        const feeLabelEl = feeRow.querySelector('.wc-block-components-totals-item__label');
                        
                        if (feeValueEl) {
                            const innerFeeValue = feeValueEl.querySelector('.wc-block-formatted-money-amount');
                            if (innerFeeValue) {
                                innerFeeValue.textContent = currencySymbol + feeAmount.toFixed(2);
                            } else {
                                feeValueEl.textContent = currencySymbol + feeAmount.toFixed(2);
                            }
                        }
                        if (feeLabelEl && fee.name) {
                            feeLabelEl.textContent = fee.name;
                        }
                    }
                }
            }
            
            isRefreshingCart = false;
        })
        .catch(error => {
            isRefreshingCart = false;
        });
    };

    /**
     * Bind click handlers to accordion/tab containers for immediate fee updates in Blocks checkout.
     * Uses event delegation to catch clicks on dynamically rendered elements.
     */
    const bindAccordionFeeUpdates = () => {
        
        // Try multiple possible container selectors for blocks checkout
        const possibleContainers = [
            document.getElementById('convesiopay-unified-component-container'),
            document.querySelector('.wc-convesiopay-unified-blocks-content'),
            document.querySelector('[class*="adyen-payment"]'),
            document.querySelector('[class*="adyen-checkout"]')
        ];
        
        let container = null;
        for (const c of possibleContainers) {
            if (c) {
                container = c;
                break;
            }
        }
        
        if (!container) {
            // Retry after component renders
            setTimeout(bindAccordionFeeUpdates, 1000);
            return;
        }
        
        // Avoid binding multiple times
        if (container.dataset.feeBindingAdded) {
            return;
        }
        container.dataset.feeBindingAdded = 'true';
        
        
        /**
         * Safely get className as string (handles SVG elements which have SVGAnimatedString)
         */
        const getClassName = (element) => {
            if (!element) return '';
            const cn = element.className;
            if (typeof cn === 'string') return cn;
            if (cn && typeof cn.baseVal === 'string') return cn.baseVal; // SVGAnimatedString
            return '';
        };
        
        /**
         * Check if an element is within an accordion header
         */
        const isWithinAccordionHeader = (element) => {
            let current = element;
            let depth = 0;
            const maxDepth = 10;
            
            while (current && depth < maxDepth) {
                const className = getClassName(current);
                // Check for accordion-header class
                if (className.includes('accordion-header')) {
                    return true;
                }
                current = current.parentElement;
                depth++;
            }
            return false;
        };
        
        /**
         * Find payment method from accordion-header element by checking its parent accordion-item
         * and the text content of the header. This is more reliable than checking the clicked element.
         */
        const detectPaymentMethodFromAccordionHeader = (accordionHeader) => {
            if (!accordionHeader) return null;
            
            // Method 1: Check the parent accordion-item for payment method classes
            const accordionItem = accordionHeader.closest('.accordion-item');
            if (accordionItem) {
                const itemClassName = getClassName(accordionItem);
                const itemOuterHtml = accordionItem.outerHTML.toLowerCase().substring(0, 500);
                
                // Check class and HTML for BTCPay indicators
                if (itemClassName.includes('btc-pay') || itemClassName.includes('btcpay') || itemClassName.includes('crypto')
                    || itemOuterHtml.includes('btc-pay') || itemOuterHtml.includes('btcpay')) {
                    return 'btcpay';
                }
                
                // Check for Apple Pay
                if (itemClassName.includes('apple-pay') || itemClassName.includes('applepay')
                    || itemOuterHtml.includes('apple-pay') || itemOuterHtml.includes('applepay')) {
                    return 'applepay';
                }
                if (itemClassName.includes('google-pay') || itemClassName.includes('googlepay')
                    || itemOuterHtml.includes('google-pay') || itemOuterHtml.includes('googlepay')) {
                    return 'googlepay';
                }
                
                // Check for Card (but not if it's apple or btc)
                if ((itemClassName.includes('new-card') || itemClassName.includes('card-container') || itemClassName.includes('card'))
                    && !itemClassName.includes('apple') && !itemClassName.includes('btc')) {
                    return 'card';
                }
            }
            
            // Method 2: Check accordion-header's own classes and parent classes
            let current = accordionHeader;
            let depth = 0;
            while (current && depth < 5) {
                const className = getClassName(current);
                
                if (className.includes('btc-pay') || className.includes('btcpay') || className.includes('crypto')) {
                    return 'btcpay';
                }
                if (className.includes('apple-pay') || className.includes('applepay')) {
                    return 'applepay';
                }
                if (className.includes('google-pay') || className.includes('googlepay')) {
                    return 'googlepay';
                }
                if ((className.includes('new-card') || className.includes('card-container'))
                    && !className.includes('apple') && !className.includes('btc')) {
                    return 'card';
                }
                
                current = current.parentElement;
                depth++;
            }
            
            // Method 3: Check text content of the accordion header (most reliable fallback)
            const headerText = (accordionHeader.textContent || '').toLowerCase();
            
            if (headerText.includes('crypto') || headerText.includes('bitcoin') || headerText.includes('btc')) {
                return 'btcpay';
            }
            if (headerText.includes('apple')) {
                return 'applepay';
            }
            if (headerText.includes('google')) {
                return 'googlepay';
            }
            // For card, check that it doesn't mention apple or crypto
            if ((headerText.includes('card') || headerText.includes('credit') || headerText.includes('debit') || headerText.includes('pay'))
                && !headerText.includes('apple') && !headerText.includes('crypto') && !headerText.includes('bitcoin')) {
                return 'card';
            }
            
            return null;
        };
        
        // Use event delegation - respond to clicks within payment method headers
        // Adyen uses various class names, so we check multiple selectors
        container.addEventListener('click', function(e) {
            const target = e.target;
            
            // Log all clicks for debugging
            const targetClass = getClassName(target);
            
            // Find payment method header - check multiple possible class names
            // Adyen uses: adyen-checkout__payment-method__header, adyen-checkout__payment-method
            // Our custom: accordion-header
            const headerSelectors = [
                '.accordion-header',
                '.adyen-checkout__payment-method__header',
                '.adyen-checkout__payment-method',
                '[class*="payment-method"]'
            ];
            
            let accordionHeader = null;
            for (const selector of headerSelectors) {
                accordionHeader = target.closest(selector);
                if (accordionHeader) {
                    break;
                }
            }
            
            if (!accordionHeader) {
                // Still no header found - try to detect method from clicked element directly
                let detectedMethod = null;
                const clickedText = (target.textContent || '').toLowerCase().substring(0, 50);
                const clickedHtml = target.outerHTML?.toLowerCase().substring(0, 200) || '';
                
                if (clickedText.includes('apple') || clickedHtml.includes('apple')) {
                    detectedMethod = 'applepay';
                } else if (clickedText.includes('google') || clickedHtml.includes('google')) {
                    detectedMethod = 'googlepay';
                } else if (clickedText.includes('crypto') || clickedText.includes('bitcoin') || clickedText.includes('btc') 
                    || clickedHtml.includes('btcpay') || clickedHtml.includes('crypto')) {
                    detectedMethod = 'btcpay';
                } else if ((clickedText.includes('card') || clickedText.includes('credit')) 
                    && !clickedText.includes('apple')) {
                    detectedMethod = 'card';
                }
                
                if (detectedMethod && detectedMethod !== currentPaymentMethod) {
                    currentPaymentMethod = detectedMethod;
                    
                    // CRITICAL: If switching to Apple Pay, recreate the session with correct amount
                    if (detectedMethod === 'applepay' && convesioPayComponent) {
                        recreateApplePaySessionWithCorrectAmount();
                    } else if (detectedMethod === 'googlepay' && convesioPayComponent) {
                        recreateGooglePaySessionWithCorrectAmount();
                    }
                    
                    storeMethodAndRefreshCart(detectedMethod);
                }
                return;
            }
            
            
            // Detect method from the header (not the target)
            let detectedMethod = detectPaymentMethodFromAccordionHeader(accordionHeader);
            
            if (!detectedMethod) {
            }
            
            if (detectedMethod && detectedMethod !== currentPaymentMethod) {
                currentPaymentMethod = detectedMethod;
                
                // CRITICAL: If switching to Apple Pay, recreate the session with correct amount
                if (detectedMethod === 'applepay' && convesioPayComponent) {
                    recreateApplePaySessionWithCorrectAmount();
                } else if (detectedMethod === 'googlepay' && convesioPayComponent) {
                    recreateGooglePaySessionWithCorrectAmount();
                }
                
                // Store method in session and refresh cart to show fee row
                storeMethodAndRefreshCart(detectedMethod);
            }
        }, true);
        
    };

    /**
     * Label component for ConvesioPay
     * Uses customizable label from admin settings
     */
    const ConvesioPayLabel = () => {
        // Get label from settings (set in admin dashboard), fallback to 'Credit Card'
        const label = settings.label || settings.title || 'Credit Card';
        return createElement('span', { 
            className: 'wc-block-components-payment-method-label' 
        }, 
            label
        );
    };

    /**
     * Recreate Apple Pay session with the correct amount (including Apple Pay fee)
     * Called when user switches to Apple Pay to ensure the authorized amount is correct
     */
    const recreateApplePaySessionWithCorrectAmount = async () => {
        if (!convesioPayComponent) return;
        
        try {
            const correctApplePayAmount = calculateCorrectTotalForMethod('applepay');
            const orderData = getOrderData();
            const integrationName = settings.integration_name || window.peachpayConvesioPayUnified?.integration_name || 'PeachPay';
            
            await convesioPayComponent.createApplePaySession({
                integration: integrationName,
                returnUrl: window.location.href,
                amount: correctApplePayAmount,
                currency: orderData.currency,
                email: orderData.email,
                name: orderData.name
            });
            
            applePayAuthorizedAmount = correctApplePayAmount;
            window.convesiopayApplePayAuthorizedAmount = correctApplePayAmount;
        } catch (error) {
            // Apple Pay session recreation failed - will use existing session
        }
    };

    const recreateGooglePaySessionWithCorrectAmount = async () => {
        if (!convesioPayComponent) return;

        try {
            const correctGooglePayAmount = calculateCorrectTotalForMethod('googlepay');
            const orderData = getOrderData();
            const integrationName = settings.integration_name || window.peachpayConvesioPayUnified?.integration_name || 'PeachPay';

            await convesioPayComponent.createGooglePaySession({
                integration: integrationName,
                returnUrl: window.location.href,
                amount: correctGooglePayAmount,
                currency: orderData.currency,
                email: orderData.email,
                name: orderData.name
            });

            googlePayAuthorizedAmount = correctGooglePayAmount;
            window.convesiopayGooglePayAuthorizedAmount = correctGooglePayAmount;
        } catch (error) {
            // Google Pay session recreation failed - will use existing session
        }
    };

    /**
     * Detect payment method based on ConvesioPay events and validation data
     *
     * @param {Object} event ConvesioPay component event
     * @return {string} Detected payment method (card, btcpay, applepay, etc.)
     */
    const detectPaymentMethod = (event) => {
        // Method 1: Check explicit payment method in event
        if (event.type) {
            return event.type;
        }
        if (event.data?.paymentMethod) {
            return event.data.paymentMethod;
        }
        // Default fallback
        return 'unknown';
    };

    /**
     * Create PeachPay transaction for ConvesioPay (unified version)
     * Exact copy of createPeachPayTransaction from checkout.js
     */
    const createPeachPayTransactionUnified = () => {
        // Check if we have the AJAX configuration
        if (typeof window.peachpayConvesioPayAjax === 'undefined') {
            return;
        }

        // Prepare transaction data for centralized PeachPay endpoint
        const transactionData = {
            gateway_id: 'peachpay_convesiopay_card',
            checkout_location: 'checkout-blocks' // Always blocks for unified
        };

        // Debug: Check what URL we're using
        const transactionUrl = window.peachpayConvesioPayAjax.create_transaction_url || window.peachpayConvesioPayAjax.ajax_url;

        // Prepare FormData based on endpoint type
        const formData = new FormData();

        // Check if we're using the centralized endpoint or falling back to AJAX
        if (window.peachpayConvesioPayAjax.create_transaction_url &&
            !window.peachpayConvesioPayAjax.create_transaction_url.includes('admin-ajax.php')) {

            // Use centralized PeachPay endpoint
            formData.append('gateway_id', transactionData.gateway_id);
            formData.append('checkout_location', transactionData.checkout_location);

        } else {
            // Fallback to standard AJAX with action parameter
            formData.append('action', 'pp-create-transaction');
            formData.append('gateway_id', transactionData.gateway_id);
            formData.append('checkout_location', transactionData.checkout_location);
            formData.append('nonce', window.peachpayConvesioPayAjax.nonce);
        }

        // Send the request
        fetch(transactionUrl, {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
            } else {
            }
        })
        .catch(error => {
        });
    };

    /**
     * Store payment token in form (unified blocks version)
     */
    const storePaymentTokenUnified = (token) => {
        // Store in hidden field for traditional checkout
        const tokenField = document.getElementById('convesiopay-payment-token');
        if (tokenField) {
            tokenField.value = token;
        }

        // Store globally for WooCommerce Blocks
        window.convesiopayPaymentToken = token;

    };

    /**
     * Enable submit button (unified blocks version)
     */
    const enableSubmitButtonUnified = () => {
        // For WooCommerce Blocks
        const submitButton = document.querySelector('.wc-block-components-checkout-place-order-button');
        if (submitButton) {
            submitButton.disabled = false;
        }

        // For traditional checkout (fallback)
        const checkoutForm = document.querySelector('form.checkout');
        if (checkoutForm) {
            const submitBtn = checkoutForm.querySelector('#place_order');
            if (submitBtn) {
                submitBtn.disabled = false;
            }
        }
    };

    /**
     * Disable submit button (unified blocks version)
     */
    const disableSubmitButtonUnified = () => {
        // For WooCommerce Blocks
        const submitButton = document.querySelector('.wc-block-components-checkout-place-order-button');
        if (submitButton) {
            submitButton.disabled = true;
        }

        // For traditional checkout (fallback)
        const checkoutForm = document.querySelector('form.checkout');
        if (checkoutForm) {
            const submitBtn = checkoutForm.querySelector('#place_order');
            if (submitBtn) {
                submitBtn.disabled = true;
            }
        }
    };


    /**
     * Show error message (unified blocks version)
     */
    const showErrorUnified = (message) => {

        // Skip WordPress notices system - it's causing compatibility issues
        // Show error directly in checkout validation area
        try {
            const checkoutContainer = document.querySelector('.wc-block-checkout') ||
                                      document.querySelector('.wp-block-woocommerce-checkout') ||
                                      document.querySelector('#convesiopay-unified-component-container');

            if (checkoutContainer) {
                // Remove existing error
                const existingError = checkoutContainer.querySelector('.convesiopay-unified-error');
                if (existingError) {
                    existingError.remove();
                }

                // Add new error message
                const errorDiv = document.createElement('div');
                errorDiv.className = 'convesiopay-unified-error wc-block-components-notice-banner is-error';
                errorDiv.style.cssText = 'margin: 10px 0; padding: 12px; background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; border-radius: 4px; font-family: inherit;';
                errorDiv.innerHTML = `<strong>Payment Error:</strong> ${message}`;

                // Insert at top of checkout container
                checkoutContainer.insertBefore(errorDiv, checkoutContainer.firstChild);

                // Auto-remove after 8 seconds
                setTimeout(() => {
                    if (errorDiv && errorDiv.parentNode) {
                        errorDiv.remove();
                    }
                }, 8000);
            }
        } catch (error) {
            // Last resort: alert (for critical errors)
            if (message.includes('token') || message.includes('payment')) {
                alert('Payment Error: ' + message);
            }
        }
    };

    /**
     * Hide error message (unified blocks version)
     */
    const hideErrorUnified = () => {
        // Skip WordPress notices system - it's causing compatibility issues
        // Just clear our custom error messages
        try {
            const customErrors = document.querySelectorAll('.convesiopay-unified-error');
            customErrors.forEach(error => {
                if (error.parentNode) {
                    error.remove();
                }
            });
        } catch (error) {
        }
    };

    /**
     * Check if any payment methods are available in the ConvesioPay component
     * @returns {boolean} True if payment methods are available
     */
    const hasPaymentMethodsAvailable = () => {
        // Check if component is mounted
        if (!convesioPayComponent || !isComponentMounted) {
            return false;
        }

        // Check if payment container exists
        const container = document.getElementById('convesiopay-unified-component-container');
        if (!container) {
            return false;
        }

        // Check if container has content (more lenient check)
        const hasContent = container.innerHTML.trim().length > 10; // Reduced threshold
        
        // Check for various payment method indicators
        const hasCardFields = container.querySelector('input[type="text"], input[type="tel"], input[type="password"]') !== null;
        const hasIframe = container.querySelector('iframe') !== null;
        const hasDivs = container.querySelector('div') !== null;
        const hasChildren = container.children.length > 0;
        
        // Check for ConvesioPay specific classes/elements
        const hasConvesioPayElement = container.querySelector('.convesiopay-component, [class*="convesiopay"], [id*="convesiopay"]') !== null;
        
        // Payment methods are available if:
        // - Container has meaningful content AND
        // - Has any of: card fields, iframe, children, or ConvesioPay elements
        const isAvailable = hasContent && (hasCardFields || hasIframe || hasChildren || hasConvesioPayElement || hasDivs);
        
        return isAvailable;
    };

    /**
     * Update submit button state based on payment method availability
     * Only controls button when ConvesioPay unified gateway is selected
     * For other payment methods (like Cash on Delivery), enables the button
     */
    const updateSubmitButtonState = () => {
        // Check if any payment method is selected
        const paymentMethodRadio = document.querySelector('input[name="payment_method"]:checked');
        
        if (!paymentMethodRadio) {
            // No payment method selected, don't interfere
            return;
        }
        
        const selectedMethod = paymentMethodRadio.value;
        
        // If ConvesioPay unified is selected, check payment method availability
        if (selectedMethod === 'peachpay_convesiopay_unified') {
            const hasMethods = hasPaymentMethodsAvailable();
            
            if (hasMethods) {
                enableSubmitButtonUnified();
            } else {
                disableSubmitButtonUnified();
            }
        } else {
            // Other payment methods selected (Cash on Delivery, etc.) - enable button
            // This matches the behavior where other payment methods work normally
            enableSubmitButtonUnified();
        }
    };

    /**
     * Handle card payment using peachpay_convesiopay_card functions (when event.type === 'card')
     * This mimics what happens when peachpay_convesiopay_card is selected
     */
    const handleCardPaymentWithPeachPayFunctions = async (event, component) => {

        // STEP 1: Call createPeachPayTransaction() (what peachpay_convesiopay_card does)
        createPeachPayTransactionUnified();

        // STEP 2: Handle component change validation (like checkout.js handleComponentChange)
        if (event.isValid) {
            // All component fields are valid and we can get the token
            try {
                const tokenResult = component.createToken();

                // Handle both Promise and direct string return
                let token;
                if (tokenResult && typeof tokenResult.then === 'function') {
                    // It's a Promise, await it
                    token = await tokenResult;
                } else {
                    // It's a direct value
                    token = tokenResult;
                }

                if (token) {
                    // Store payment token (exactly like checkout.js storePaymentToken function)
                    storePaymentTokenUnified(token);
                }

                // Get order data
                const orderData = getOrderData();

                if (!orderData.isValid) {
                    throw new Error('Invalid order data');
                }

                // Store payment data for blocks processing
                paymentConfirmedData = {
                    paymentId: 'card_' + Date.now(),
                    status: 'succeeded',
                    paymentMethod: 'card',
                    amount: orderData.amount,
                    currency: orderData.currency,
                    orderNumber: orderData.orderNumber,
                    token: token
                };

                currentPaymentMethod = 'card';

                // Component is valid, enable checkout (exactly like checkout.js enableSubmitButton)
                enableSubmitButtonUnified();
                hideErrorUnified();
                
                // Also update button state to ensure it's enabled
                updateSubmitButtonState();


            } catch (error) {
                showErrorUnified('Failed to create payment token');
                disableSubmitButtonUnified();
            }
        } else {
            // Handle errors, one or more component fields are not valid (like checkout.js)
            showErrorUnified('Please complete all required payment fields');
            disableSubmitButtonUnified();
        }
    };

    /**
     * Handle card payment using component.createToken() and ConvesioPay API
     */
    const handleCardPayment = async (component, event) => {
        try {
            
            // Create payment token using component (following checkout.js pattern)
            const tokenResult = component.createToken();
            
            // Handle both Promise and direct string return
            let token;
            if (tokenResult && typeof tokenResult.then === 'function') {
                // It's a Promise, await it
                token = await tokenResult;
            } else {
                // It's a direct value
                token = tokenResult;
            }
            
            if (!token) {
                throw new Error('Failed to create payment token');
            }
            
            
            // Get order data
            const orderData = getOrderData();
            
            if (!orderData.isValid) {
                throw new Error('Invalid order data');
            }
                
                // Store payment data but DON'T auto-click - let user click Place Order
                paymentConfirmedData = {
                    paymentId: 'card_' + Date.now(),
                    status: 'succeeded',
                    paymentMethod: 'card',
                    amount: orderData.amount,
                    currency: orderData.currency,
                    orderNumber: orderData.orderNumber,
                    token: token
                };
            
            currentPaymentMethod = 'card';
            
            // Show success message instead of auto-clicking
            
        } catch (error) {
        }
    };

    /**
     * Handle BTCPay payment (following BTCPay blocks pattern)
     */
    const handleBTCPayPayment = (event) => {
        
        // For BTCPay, only proceed if status is 'Processing' (not 'Pending')
        if (event.paymentData && event.paymentData.status === 'Processing') {
            
            // Store payment data and trigger auto-click
            paymentConfirmedData = {
                paymentId: event.paymentData.paymentId,
                invoiceId: event.paymentData.paymentId,
                status: event.paymentData.status,
                amount: event.paymentData.amount,
                currency: event.paymentData.currency,
                orderNumber: event.paymentData.orderNumber,
                paymentMethod: 'btcpay'
            };
            
            currentPaymentMethod = 'btcpay';
            
            setTimeout(() => {
                autoClickPlaceOrderButton();
            }, 500);
        } else if (event.paymentData) {
        }
    };

    /**
     * Handle Apple Pay payment success with auto-submit (NEW TOKEN-BASED FLOW)
     * After user authorizes payment on device, we receive a token (NOT a paymentId)
     * Backend will create the payment using secret key AFTER WC order is created
     */
    const handleApplePayPaymentSuccess = async (component, event) => {
        try {
            // Get order data
            const orderData = getOrderData();

            if (!orderData.isValid) {
                showErrorUnified('Invalid order data');
                return;
            }

            // NEW FLOW: Extract token from event (SDK provides this after device authorization)
            // Payment does NOT exist yet - it will be created by backend with secret key
            const paymentToken = event.token
                ?? event.paymentData?.token
                ?? event.data?.token
                ?? null;

            if (!paymentToken) {
                showErrorUnified('Apple Pay authorization successful but token is missing. Please try again.');
                return;
            }

            // Store ApplePay payment data globally for use in checkout submission
            // NOTE: No paymentId yet - that will be created by backend
            paymentConfirmedData = {
                paymentId: null, // Will be created by backend
                status: 'authorized', // Device authorized, payment will be created by backend
                paymentMethod: 'applepay',
                amount: event.paymentData?.amount || orderData.amount,
                currency: event.paymentData?.currency || orderData.currency,
                orderNumber: orderData.orderNumber,
                token: paymentToken
            };

            currentPaymentMethod = 'applepay';

            // Store token globally for backend processing
            if (typeof storePaymentTokenUnified === 'function') {
                storePaymentTokenUnified(paymentToken);
            }
            window.convesiopayPaymentToken = paymentToken;
            window.convesiopayApplePayPaymentData = paymentConfirmedData;

            // Enable the Place Order button and auto-click it
            setTimeout(() => {
                let placeOrderButton = document.querySelector('.wc-block-components-checkout-place-order-button') ||
                                      document.querySelector('.wp-element-button.wc-block-components-checkout-place-order-button') ||
                                      document.querySelector('button[type="submit"]');

                if (placeOrderButton) {
                    placeOrderButton.disabled = false;
                    placeOrderButton.removeAttribute('aria-disabled');
                    placeOrderButton.style.opacity = '1';
                    placeOrderButton.style.cursor = 'pointer';
                    placeOrderButton.style.pointerEvents = 'auto';

                    // Force a reflow to ensure styles are applied
                    placeOrderButton.offsetHeight;

                    // Auto-click the button to complete the order
                    placeOrderButton.click();
                }
            }, 500);

        } catch (error) {
            showErrorUnified('Apple Pay failed: ' + error.message);
        }
    };

    const handleGooglePayPaymentSuccess = async (component, event) => {
        try {
            const orderData = getOrderData();

            if (!orderData.isValid) {
                showErrorUnified('Invalid order data');
                return;
            }

            const paymentToken = event.token
                ?? event.paymentData?.token
                ?? event.data?.token
                ?? null;

            if (!paymentToken) {
                showErrorUnified('Google Pay authorization successful but token is missing. Please try again.');
                return;
            }

            paymentConfirmedData = {
                paymentId: null,
                status: 'authorized',
                paymentMethod: 'googlepay',
                amount: event.paymentData?.amount || orderData.amount,
                currency: event.paymentData?.currency || orderData.currency,
                orderNumber: orderData.orderNumber,
                token: paymentToken
            };

            currentPaymentMethod = 'googlepay';

            if (typeof storePaymentTokenUnified === 'function') {
                storePaymentTokenUnified(paymentToken);
            }
            window.convesiopayPaymentToken = paymentToken;
            window.convesiopayGooglePayPaymentData = paymentConfirmedData;

            setTimeout(() => {
                let placeOrderButton = document.querySelector('.wc-block-components-checkout-place-order-button') ||
                                      document.querySelector('.wp-element-button.wc-block-components-checkout-place-order-button') ||
                                      document.querySelector('button[type="submit"]');

                if (placeOrderButton) {
                    placeOrderButton.disabled = false;
                    placeOrderButton.removeAttribute('aria-disabled');
                    placeOrderButton.style.opacity = '1';
                    placeOrderButton.style.cursor = 'pointer';
                    placeOrderButton.style.pointerEvents = 'auto';
                    placeOrderButton.offsetHeight;
                    placeOrderButton.click();
                }
            }, 500);
        } catch (error) {
            showErrorUnified('Google Pay failed: ' + error.message);
        }
    };

    /**
     * Handle Apple Pay payment (LEGACY - requires manual click)
     */
    const handleApplePayPayment = async (component, event) => {
        try {

            // Store payment data and trigger auto-click
            paymentConfirmedData = {
                paymentId: event.paymentData.paymentId,
                status: event.paymentData.status,
                paymentMethod: 'applepay',
                amount: event.paymentData.amount,
                currency: event.paymentData.currency,
                orderNumber: event.paymentData.orderNumber
            };

            currentPaymentMethod = 'applepay';

            setTimeout(() => {
                autoClickPlaceOrderButton();
            }, 500);

        } catch (error) {
        }
    };

    /**
     * Listen for postMessage events from BTCPay iframe
     */
    const setupBTCPayMessageListener = () => {
        // If BTCPay is disabled, do not attach any listeners.
        if (!isBtcpayEnabled()) {
            return;
        }

        window.addEventListener('message', (event) => {
            // Verify the origin is from BTCPay
            if (!event.origin.includes('btcpay') && !event.origin.includes('convesiopay')) {
                return;
            }
            
            try {
                let messageData;
                
                // Handle both string and object message data
                if (typeof event.data === 'string') {
                    try {
                        messageData = JSON.parse(event.data);
                    } catch (e) {
                        messageData = { type: event.data };
                    }
            } else {
                    messageData = event.data;
                }
                
                // Check for payment status messages - 'Processing' means payment received
                if (messageData.status === 'Processing') {
                    
                    // Extract payment details from the message
                    const extractedData = {
                        invoiceId: messageData.invoiceId,
                        status: 'Processing',
                        paymentId: messageData.invoiceId,
                        paymentMethod: 'btcpay'
                    };
                    
                    paymentConfirmedData = extractedData;
                    
                    // Trigger auto-click of place order button
                    setTimeout(() => {
                        autoClickPlaceOrderButton();
                    }, 500);
            }
            
        } catch (error) {
            }
        });
    };

    /**
     * Auto-click the place order button for WooCommerce Blocks checkout
     */
    const autoClickPlaceOrderButton = () => {

        // Use stored payment data
        if (!paymentConfirmedData) {

            // Disable the place order button
            const placeOrderButton = document.querySelector('.components-button.wc-block-components-button.wp-element-button.wc-block-components-checkout-place-order-button.contained');
            if (placeOrderButton) {
                // placeOrderButton.disabled = true;
                placeOrderButton.style.opacity = '0.5';
                placeOrderButton.style.cursor = 'not-allowed';
            }
            return;
        }


        // Reset session state after successful payment
        setTimeout(() => {
            resetSessionState();
        }, 5000);

        // Find the place order button
        let placeOrderButton = document.querySelector('.components-button.wc-block-components-button.wp-element-button.wc-block-components-checkout-place-order-button.contained');

        if (!placeOrderButton) {
            // Try alternative selectors
            placeOrderButton = document.querySelector('.wc-block-components-checkout-place-order-button') ||
                              document.querySelector('[data-block-name="woocommerce/checkout-order-summary-block"] button') ||
                              document.querySelector('button[type="submit"]');
        }

        if (placeOrderButton) {

            // IMPORTANT: Enable the button before clicking
            placeOrderButton.disabled = false;
            // placeOrderButton.removeAttribute('aria-disabled');
            placeOrderButton.style.opacity = '1';
            placeOrderButton.style.cursor = 'pointer';
            placeOrderButton.style.pointerEvents = 'auto';

            // Force reflow
            placeOrderButton.offsetHeight;

            // Click the button
            placeOrderButton.click();
        }
    };

    /**
     * Get current cart total from WooCommerce Blocks store
     * @returns {number} Current cart total in cents
     */
    const getCurrentCartTotal = () => {
        // Try to get cart total from blocks store
        if (window.wp && window.wp.data && window.wp.data.select) {
            try {
                const store = window.wp.data.select('wc/store/cart');
                const cartTotals = store.getCartTotals();

                if (cartTotals && cartTotals.total_price) {
                    return parseInt(cartTotals.total_price);
                }
            } catch (error) {
                // Fallback to DOM
            }
        }

        // Fallback: Try to get from DOM
        const totalElement = document.querySelector('.wc-block-components-totals-item__value');
        if (totalElement) {
            const totalText = totalElement.textContent.replace(/[^\d.]/g, '');
            const amount = parseFloat(totalText);
            if (!isNaN(amount)) {
                return Math.round(amount * 100); // Convert to cents
            }
        }

        return 0;
    };

    /**
     * Monitor cart total changes and update component amount for ApplePay/GooglePay
     */
    const setupCartTotalMonitoring = () => {
        // Listen for WooCommerce Blocks cart updates
        if (window.wp && window.wp.data && window.wp.data.subscribe) {
            let previousTotal = getCurrentCartTotal();

            window.wp.data.subscribe(() => {
                const currentTotal = getCurrentCartTotal();

                // Check if total has changed
                if (currentTotal !== previousTotal && currentTotal > 0) {
                    previousTotal = currentTotal;
                    lastKnownCartTotal = currentTotal;

                    // Update component amount if component exists
                    if (convesioPayComponent) {
                        updateComponentAmount(currentTotal);
                    }
                }

                // Update component email when billing email changes (no remount)
                if (convesioPayComponent) {
                    applyRuntimeEmailUpdate();
                }
            });
        }

        // Also monitor checkout form changes as a fallback
        const observer = new MutationObserver(() => {
            const currentTotal = getCurrentCartTotal();

            if (currentTotal !== lastKnownCartTotal && currentTotal > 0) {
                lastKnownCartTotal = currentTotal;

                // Update component amount if component exists
                if (convesioPayComponent) {
                    updateComponentAmount(currentTotal);
                }
            }
        });

        // Observe the totals section for changes
        const totalsElement = document.querySelector('.wc-block-components-totals-wrapper');
        if (totalsElement) {
            observer.observe(totalsElement, {
                childList: true,
                subtree: true,
                characterData: true
            });
        }
    };

    /**
     * Update component customer email without remounting.
     * Only updates when email value actually changes (no fallback email).
     */
    const applyRuntimeEmailUpdate = () => {
        if (!convesioPayComponent || typeof convesioPayComponent.updateEmail !== 'function') {
            return;
        }
        const orderData = getOrderData();
        const email = orderData.email ? String(orderData.email).trim() : '';
        if (email === lastKnownCustomerEmail) {
            return;
        }
        try {
            convesioPayComponent.updateEmail(email);
            lastKnownCustomerEmail = email;
        } catch (err) {
            // Ignore; component may not support updateEmail in all contexts
        }
    };

    /**
     * Update component amount when cart total changes
     * Recreates the ApplePay session with new amount
     */
    const updateComponentAmount = async (newAmountInCents) => {
        try {

            // Step 1: Unmount and destroy the old component
            if (convesioPayComponent) {
                try {
                    // Unmount the component if it has an unmount method
                    if (typeof convesioPayComponent.unmount === 'function') {
                        await convesioPayComponent.unmount();
                    }

                    // Destroy the component if it has a destroy method
                    if (typeof convesioPayComponent.destroy === 'function') {
                        convesioPayComponent.destroy();
                    }
                } catch (unmountError) {
                    // Error during unmount/destroy
                }

                // Clear the component reference
                convesioPayComponent = null;
                isComponentMounted = false;

                // Clear the container
                const componentContainer = document.querySelector('#convesiopay-unified-component-container');
                if (componentContainer) {
                    componentContainer.innerHTML = '';
                }
            }

            // Step 2: Clear session state
            isSessionCreated = false;
            const hadBtcPaySession = btcPaySession !== null;
            btcPaySession = null;

            // Step 3: Create and mount new component
            const componentResult = await createAndMountConvesioPayComponent();

            if (!componentResult.success) {
                return;
            }

            // Mount the component in the container
            const componentContainer = document.querySelector('#convesiopay-unified-component-container');
            if (componentContainer) {
                componentContainer.innerHTML = '';
                await convesioPayComponent.mount('#convesiopay-unified-component-container');
                
                /**
                 * Disable submit button immediately after component mount to prevent premature checkout.
                 * 
                 * Reason: When the ConvesioPay component first mounts, payment methods (card fields, 
                 * BTCPay, Apple Pay) may not be immediately rendered or available. We disable the 
                 * submit button here as a safety measure, and it will be automatically enabled by 
                 * updateSubmitButtonState() once payment methods are confirmed to be available and 
                 * rendered in the container. This prevents users from attempting checkout before 
                 * payment methods are ready, which could result in errors or incomplete payment data.
                 */
                disableSubmitButtonUnified();
            }

            // Step 4: Get fresh order data with updated amount
            const orderData = getOrderData();

            // Override with the new amount (in case getOrderData() hasn't updated yet)
            orderData.amount = newAmountInCents;

            // Step 5: Create ApplePay session with new amount (NEW FLOW - no orderNumber)
            try {
                await convesioPayComponent.createApplePaySession({
                    integration: settings.integration_name || window.peachpayConvesioPayUnified?.integration_name || 'PeachPay',
                    returnUrl: window.location.href,
                    // orderNumber: REMOVED - new flow creates payment after order exists
                    amount: orderData.amount,
                    currency: orderData.currency,
                    email: orderData.email,
                    name: orderData.name
                });
            } catch (applePayError) {
                // ApplePay session creation failed (might not be available)
            }

            if (isGooglePayEnabled()) {
                try {
                    await convesioPayComponent.createGooglePaySession({
                        integration: settings.integration_name || window.peachpayConvesioPayUnified?.integration_name || 'PeachPay',
                        returnUrl: window.location.href,
                        amount: orderData.amount,
                        currency: orderData.currency,
                        email: orderData.email,
                        name: orderData.name
                    });
                } catch (googlePayError) {
                    // GooglePay session creation failed (might not be available)
                }
            }

            // Step 6: Create BTCPay session and intent if it was previously active (only if BTC Pay is enabled)
            // GUARD: Only create BTC Pay session and intent if BTC Pay is enabled
            if (hadBtcPaySession && isBtcpayEnabled()) {
                try {
                    // Create new BTCPay session with updated amount
                    const sessionResult = await createBTCPaySession();

                    // Only proceed if session creation was successful
                    // If disabled or failed, continue without BTC Pay session
                    if (sessionResult.success && sessionResult.session && !sessionResult.disabled) {
                        // Update the global session variable
                        btcPaySession = sessionResult.session;

                        // Prepare BTCPay intent data
                        const btcPayIntentData = {
                            session: btcPaySession
                        };

                        // Create the BTCPay intent with the new session
                        await convesioPayComponent.createBTCPayIntent(btcPayIntentData);

                        // Re-setup the message listener
                        setupBTCPayMessageListener();
                    } else if (sessionResult.disabled) {
                        // BTC Pay is disabled - continue without BTC Pay session
                        // Component will work with Card and Apple Pay only
                    } else {
                        // Session creation failed but BTC Pay should be enabled
                        // BTCPay session creation failed during amount update - component will work without BTC Pay
                    }
                } catch (btcPayError) {
                    // Silently fail if BTC Pay intent creation fails when BTC Pay is disabled
                    // Only log error if BTC Pay should be enabled
                    // BTCPay session/intent recreation failed - handled silently
                }
            } else if (hadBtcPaySession && !isBtcpayEnabled()) {
                // BTC Pay was previously active but is now disabled - skip session/intent creation
            }

        } catch (error) {
            // Error updating component amount
        }
    };

    /**
     * Get order data for ConvesioPay including required address fields
     */
    const getOrderData = () => {
        const orderData = {
            isValid: false,
            orderNumber: getOrderNumber(),
            amount: 0,
            currency: 'USD',
            email: '',
            name: 'Customer',
            // Required address fields for ConvesioPay API
            billingAddress: {
                street: '123 Default Street', // Must be at least 1 character
                city: 'Default City',
                state: 'CA',
                postalCode: '90210',
                country: 'US'
            },
            shippingAddress: {
                street: '123 Default Street', // Must be at least 1 character
                city: 'Default City',
                state: 'CA',
                postalCode: '90210',
                country: 'US'
            }
        };

        // Try to get cart total from blocks store
        if (window.wp && window.wp.data && window.wp.data.select) {
            try {
                const store = window.wp.data.select('wc/store/cart');
                const cartTotals = store.getCartTotals();

                if (cartTotals && cartTotals.total_price) {
                    orderData.amount = parseInt(cartTotals.total_price);
                }

                if (cartTotals && cartTotals.currency_code) {
                    orderData.currency = cartTotals.currency_code;
                }

                // Try to get billing address from checkout store
                try {
                    const checkoutStore = window.wp.data.select('wc/store/checkout');
                    if (checkoutStore) {
                        const billingData = checkoutStore.getBillingData();
                        const shippingData = checkoutStore.getShippingData();

                        if (billingData) {
                            orderData.email = billingData.email || orderData.email;
                            orderData.name = (billingData.first_name + ' ' + billingData.last_name).trim() || orderData.name;

                            if (billingData.address_1 && billingData.address_1.trim()) {
                                orderData.billingAddress = {
                                    street: billingData.address_1.trim() + (billingData.address_2 ? ' ' + billingData.address_2.trim() : ''),
                                    city: billingData.city || 'Default City',
                                    state: billingData.state || 'CA',
                                    postalCode: billingData.postcode || '90210',
                                    country: billingData.country || 'US'
                                };
                            }
                        }

                        if (shippingData && shippingData.address_1 && shippingData.address_1.trim()) {
                            orderData.shippingAddress = {
                                street: shippingData.address_1.trim() + (shippingData.address_2 ? ' ' + shippingData.address_2.trim() : ''),
                                city: shippingData.city || 'Default City',
                                state: shippingData.state || 'CA',
                                postalCode: shippingData.postcode || '90210',
                                country: shippingData.country || 'US'
                            };
                        } else {
                            // Use billing address as shipping if shipping is empty
                            orderData.shippingAddress = { ...orderData.billingAddress };
                        }
                    }
                } catch (checkoutError) {
                }
            } catch (error) {
            }
        }

        // Try to get amount from DOM if store failed
        if (orderData.amount === 0) {
            const totalElement = document.querySelector('.wc-block-components-totals-item__value');
            if (totalElement) {
                const totalText = totalElement.textContent.replace(/[^\d.]/g, '');
                const amount = parseFloat(totalText);
                if (!isNaN(amount)) {
                    orderData.amount = Math.round(amount * 100); // Convert to cents
                }
            }
        }

        // Try to get customer data from checkout form fields if store failed (no fallback email)
        if (orderData.email === '') {
            const emailField = document.querySelector('input[type="email"]');
            if (emailField && emailField.value) {
                orderData.email = emailField.value.trim();
            }
        }

        // Ensure we have valid data and valid street addresses (ConvesioPay requirement)
        orderData.isValid = orderData.amount > 0;

        // Final validation - ensure street addresses are never empty
        if (!orderData.billingAddress.street || orderData.billingAddress.street.trim().length === 0) {
            orderData.billingAddress.street = '123 Default Street';
        }
        if (!orderData.shippingAddress.street || orderData.shippingAddress.street.trim().length === 0) {
            orderData.shippingAddress.street = '123 Default Street';
        }


        return orderData;
    };

    /**
     * Get order number
     */
    const getOrderNumber = () => {
        // Try to get order number from blocks checkout store
        if (window.wp && window.wp.data && window.wp.data.select) {
            try {
                const checkoutStore = window.wp.data.select('wc/store/checkout');

                if (checkoutStore) {
                    const orderId = checkoutStore.getOrderId();

                    if (orderId) {
                        return orderId.toString();
                    }
                }
            } catch (e) {
                // Error accessing checkout store
            }
        }

        // Fallback: Try to get from URL parameters
        const urlParams = new URLSearchParams(window.location.search);
        const orderId = urlParams.get('order');

        if (orderId) {
            return orderId;
        }

        // Generate session-based identifier
        const timestamp = Date.now();
        const random = Math.floor(Math.random() * 10000);
        return `SESSION-${timestamp}-${random}`;
    };

    /**
     * Create BTCPay session via AJAX call
     * 
     * STRICT GUARD: Returns early with success:false (not an error) when disabled
     * to prevent any error messages from being shown.
     */
    const createBTCPaySession = async () => {
        // STRICT CHECK: Do not create BTCPay sessions when the method is disabled in
        // PeachPay/WooCommerce settings. This prevents unnecessary
        // ConvesioPay API calls and avoids leaking BTCPay behaviour
        // into sites that have explicitly disabled crypto.
        if (!isBtcpayEnabled()) {
            // Return success:false with a message indicating it's disabled
            // This is NOT an error - it's expected behavior when disabled
            return { success: false, message: 'BTCPay payment method is disabled', disabled: true };
        }

        // If session already created and exists, return it
        if (isSessionCreated && btcPaySession) {
            return { success: true, session: btcPaySession };
        }
        
        try {
            const orderData = getOrderData();
            if (!orderData.isValid) {
                throw new Error('Unable to get order details');
            }
            
            const requestData = {
                action: 'peachpay_convesiopay_create_btcpay_session',
                nonce: settings.nonce || '',
                integration: settings.integration_name,
                returnUrl: window.location.href,
                orderNumber: orderData.orderNumber,
                amount: orderData.amount,
                currency: orderData.currency,
                email: orderData.email,
                name: orderData.name,
                // Include required address fields for ConvesioPay API
                billingAddress: JSON.stringify(orderData.billingAddress),
                shippingAddress: JSON.stringify(orderData.shippingAddress)
            };

            
            const response = await fetch(settings.ajax_url || '/wp-admin/admin-ajax.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams(requestData).toString()
            });
            
            const sessionResponse = await response.json();
            
            if (!sessionResponse.success || !sessionResponse.data?.session) {
                // Extract message from WordPress AJAX response structure
                // WordPress error responses have message in data.message or directly in message
                const errorMessage = sessionResponse.data?.message || sessionResponse.message || 'Failed to create BTCPay session';
                
                // Check if the error is because BTC Pay is disabled
                const isDisabled = errorMessage.toLowerCase().includes('disabled') || 
                                 errorMessage.toLowerCase().includes('btcpay payment method is disabled');
                
                // Return with disabled flag so error won't be shown
                return { 
                    success: false, 
                    message: errorMessage,
                    disabled: isDisabled
                };
            }
            
            // Store session
            btcPaySession = sessionResponse.data.session;
            isSessionCreated = true;
            
            return { success: true, session: btcPaySession };
            
        } catch (error) {
            // On error, check if BTC Pay is still enabled before reporting error
            // If disabled, this is expected behavior
            const isDisabled = !isBtcpayEnabled();
            return { 
                success: false, 
                message: error.message,
                disabled: isDisabled
            };
        }
    };

    /**
     * Create and mount ConvesioPay component
     */
    const createAndMountConvesioPayComponent = async () => {
        if (isComponentMounted && convesioPayComponent) {
            return { success: true, component: convesioPayComponent };
        }
        
        try {
            // Check if ConvesioPay SDK is available
            if (typeof window.ConvesioPay === 'undefined') {
                throw new Error('ConvesioPay SDK not available');
            }

            // Get ConvesioPay configuration
            const config = settings.convesiopay_config || {};
            const clientKey = config.clientKey;
            const apiKey = config.apiKey;
            const integrationName = settings.integration_name;
            
            if (!apiKey) {
                throw new Error('ConvesioPay api key not available');
            }
            
            // Create ConvesioPay instance
            const cpay = window.ConvesioPay(apiKey);
            
            // Get order data for customer email (no fallback; only attach when present, like classic)
            const orderData = getOrderData();
            const customerEmail = orderData.email && String(orderData.email).trim() !== '' ? String(orderData.email).trim() : null;
            const componentConfig = {
                environment: config.api_url?.includes('qa') ? 'test' : 'live',
                clientKey: clientKey,
                integration: settings.integration_name,
                theme: settings.checkout_theme || 'light'
            };
            if (customerEmail) {
                componentConfig.customerEmail = customerEmail;
            }
            // Initialize component
            const component = cpay.component(componentConfig);

            // Store globally
            convesioPayComponent = component;
            isComponentMounted = true;
            lastKnownCustomerEmail = customerEmail !== null ? customerEmail : '';
            
            // Set up event listeners
            component.on('change', (event) => {
                
                // Update submit button state when component changes
                updateSubmitButtonState();
                
                // Update fee display when payment method changes
                if (event.type && event.type !== currentPaymentMethod) {
                    currentPaymentMethod = event.type;
                    
                    // Store method in session and refresh cart to show fee row
                    storeMethodAndRefreshCart(event.type);
                } else if (event.type) {
                }
                
                // Check if this is a card payment event based on event.type
                if (event.type === 'card') {
                    handleCardPaymentWithPeachPayFunctions(event, component);
                } else if (event.type === 'btcpay') {
                    // Handle BTCPay payments directly when event.type is btcpay
                    // GUARD: Only handle BTC Pay events if BTC Pay is enabled
                    if (isBtcpayEnabled()) {
                        handleBTCPayPayment(event);
                    } else {
                        // BTC Pay is disabled - ignore BTC Pay events
                    }
                } else if (event.type === 'applepay') {
                    // Handle ApplePay payments with auto-submit when successful
                    if (event.isSuccessful) {
                        // ApplePay payment intent was successfully authorized
                        handleApplePayPaymentSuccess(component, event);
                    } else if (event.errors) {
                        // Handle ApplePay errors
                        const errorMessage = event.errors[0]?.message || 'ApplePay payment failed';
                        showErrorUnified(errorMessage);
                    }
                } else if (event.type === 'googlepay') {
                    if (event.isSuccessful) {
                        handleGooglePayPaymentSuccess(component, event);
                    } else if (event.errors) {
                        const errorMessage = event.errors[0]?.message || 'Google Pay payment failed';
                        showErrorUnified(errorMessage);
                    }
                } else {
                    // Detect payment method type and handle accordingly for other methods
                    const paymentMethod = detectPaymentMethod(event);

                    // Only process payment when user explicitly submits/confirms, not on input change
                    if (paymentMethod === 'card' && event.isValid === true && event.isSuccessful === true) {
                        handleCardPayment(component, event);
                    } else if (paymentMethod === 'btcpay' && event.isValid === true && event.isSuccessful === true) {
                        // GUARD: Only handle BTC Pay payments if BTC Pay is enabled
                        if (isBtcpayEnabled()) {
                            handleBTCPayPayment(event);
                        } else {
                            // BTC Pay is disabled - ignore BTC Pay payment events
                        }
                    } else if (paymentMethod === 'applepay' && event.isValid === true && event.isSuccessful === true) {
                        handleApplePayPayment(component, event);
                    } else if (paymentMethod === 'googlepay' && event.isValid === true && event.isSuccessful === true) {
                        handleGooglePayPaymentSuccess(component, event);
                    } else {
                    }
                }
            });
            
            return { success: true, component: component };
            
        } catch (error) {
            return { success: false, message: error.message };
        }
    };

    /**
     * Mount ConvesioPay component directly in the content div (following BTCPay blocks pattern)
     */
    const CONVESIOPAY_LOADER_HTML = '<div class="convesiopay-custom-loader" style="display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;padding:24px;color:#666;">' +
        '<div class="convesiopay-loader-spinner" style="width:32px;height:32px;border:3px solid #e0e0e0;border-top-color:#0073aa;border-radius:50%;animation:convesiopay-spin 0.8s linear infinite;"></div>' +
        '<span style="font-size:14px;">Loading payment form...</span></div>';

    const mountConvesioPayComponent = async () => {
        // Check if component is already mounted in the content
        const componentContainer = document.querySelector('#convesiopay-unified-component-container');
        const existingComponent = componentContainer?.querySelector('.convesiopay-component');
        if (existingComponent) {
            return;
        }

        if (componentContainer) {
            componentContainer.classList.add('loading-in-progress');
            componentContainer.innerHTML = CONVESIOPAY_LOADER_HTML;
            if (!document.getElementById('convesiopay-loader-styles')) {
                const style = document.createElement('style');
                style.id = 'convesiopay-loader-styles';
                style.textContent = '@keyframes convesiopay-spin { to { transform: rotate(360deg); } }';
                document.head.appendChild(style);
            }
        }
        
        try {
            // Create and mount the component
            const componentResult = await createAndMountConvesioPayComponent();
            
            if (componentResult.success) {
                // Find the content container
                const contentContainer = document.querySelector('.wc-convesiopay-unified-blocks-content');
                if (!contentContainer) {
                    throw new Error('Content container not found');
                }
                
                // The component container already exists (we got it at start, or get again)
                const container = contentContainer.querySelector('#convesiopay-unified-component-container') || componentContainer;
                if (!container) {
                    throw new Error('Component container not found in content');
                }
                
                // Mount the component in the container (replaces loader)
                await convesioPayComponent.mount('#convesiopay-unified-component-container');
                
                // Bind accordion fee updates after component mounts
                setTimeout(() => {
                    bindAccordionFeeUpdates();
                }, 500);
                
                // Monitor container for payment method availability and update submit button
                const containerObserver = new MutationObserver(() => {
                    // Small delay to ensure DOM is updated
                    setTimeout(() => {
                        updateSubmitButtonState();
                    }, 100);
                });
                
                containerObserver.observe(container, {
                    childList: true,
                    subtree: true,
                    attributes: true,
                    characterData: true
                });
                
                // Initial check after component mounts - use multiple checks with increasing delays
                // This ensures we catch the component even if it renders slowly
                setTimeout(() => {
                    updateSubmitButtonState();
                }, 300);
                
                setTimeout(() => {
                    updateSubmitButtonState();
                }, 800);
                
                setTimeout(() => {
                    updateSubmitButtonState();
                }, 1500);
                
                setTimeout(() => {
                    updateSubmitButtonState();
                }, 2500);
                
                // Ensure the mounted ConvesioPay component takes full width
                const mountedComponent = document.querySelector('#convesiopay-unified-component-container .convesiopay-component, #convesiopay-unified-component-container iframe, #convesiopay-unified-component-container > div');
                if (mountedComponent) {
                    mountedComponent.style.width = '100%';
                    mountedComponent.style.maxWidth = '100%';
                    mountedComponent.style.minWidth = '100%';
                }
                
                // Add CSS to ensure ConvesioPay component takes full width
                const styleId = 'convesiopay-full-width-styles';
                if (!document.getElementById(styleId)) {
                    const style = document.createElement('style');
                    style.id = styleId;
                    style.textContent = `
                        #convesiopay-unified-component-container.loading-in-progress {
                            min-height: 300px !important;
                            min-width: 100% !important;
                            display: flex !important;
                            align-items: center !important;
                            justify-content: center !important;
                        }
                        #convesiopay-unified-component-container {
                            width: 100% !important;
                            min-height: 300px !important;
                            min-width: 100% !important;
                        }
                        #convesiopay-unified-component-container .convesiopay-component,
                        #convesiopay-unified-component-container iframe,
                        #convesiopay-unified-component-container > div {
                            width: 100% !important;
                            max-width: 100% !important;
                            min-width: 100% !important;
                        }
                        .convesiopay-component-container {
                            width: 100% !important;
                            min-height: 300px !important;
                        }
                        /* Hide radio button when ConvesioPay is the only payment method */
                        .wc-block-components-radio-control-accordion-option:only-child .wc-block-components-radio-control__option {
                            display: none !important;
                        }
                        /* Remove padding from accordion content */
                        .wc-block-components-radio-control-accordion-content {
                            padding: 0 !important;
                        }
                    `;
                    document.head.appendChild(style);
                }
                
                const orderData = getOrderData();

                // Prepare the request body for createBTCPayIntent
                const btcPayIntentData = {
                    session: btcPaySession,
                    integration: settings.integration_name,
                    returnUrl: window.location.href,
                    orderNumber: orderData.orderNumber,
                    amount: orderData.amount,
                    currency: orderData.currency,
                    email: orderData.email,
                    name: orderData.name,
                    billingAddress: orderData.billingAddress,
                    shippingAddress: orderData.shippingAddress
                };

                if (activeMethods.includes('applepay')) {
                    await convesioPayComponent.createApplePaySession({
                        integration: settings.integration_name,
                        returnUrl: window.location.href,
                        amount: orderData.amount,
                        currency: orderData.currency,
                        email: orderData.email,
                        name: orderData.name
                    });
                }

                if (isGooglePayEnabled()) {
                    await convesioPayComponent.createGooglePaySession({
                        integration: settings.integration_name,
                        returnUrl: window.location.href,
                        amount: orderData.amount,
                        currency: orderData.currency,
                        email: orderData.email,
                        name: orderData.name
                    });
                }


                // Create BTCPay intent using the mounted component (following BTCPay blocks pattern)
                // Include required address fields for ConvesioPay API. Only do this
                // when BTCPay is actually enabled for the site and we have a session.
                // GUARD: Check if BTC Pay is enabled and we have a session before attempting to create intent
                if (isBtcpayEnabled() && btcPaySession) {
                    try {
                        await convesioPayComponent.createBTCPayIntent(btcPayIntentData);
                        
                        // Set up postMessage listener for iframe communication
                        setupBTCPayMessageListener();

                        // Check again after BTCPay intent is created
                        setTimeout(() => {
                            updateSubmitButtonState();
                        }, 1000);
                    } catch (error) {
                        // Silently fail if BTC Pay intent creation fails when BTC Pay is disabled
                        // Only log error if BTC Pay should be enabled
                        // BTCPay intent creation failed - handled silently
                    }
                } else {
                    // BTC Pay is disabled or no session - do not create intent or set up listeners
                    // Component will work with Card and Apple Pay only
                }
                
                
            } else {
                throw new Error(componentResult.message || 'Failed to create component');
            }
            
        } catch (error) {
            // Failed to create ConvesioPay payment
        } finally {
            setTimeout(() => {
                const el = document.querySelector('#convesiopay-unified-component-container');
                if (el) el.classList.remove('loading-in-progress');
            }, 800);
        }
    };

    /**
     * Content component for ConvesioPay Unified (following BTCPay blocks pattern)
     */
    const ConvesioPayUnifiedContent = (props) => {
        const { eventRegistration, emitResponse } = props;

        // Create session and mount component when radio button is selected (following BTCPay pattern)
        useEffect(() => {
            // Disable submit button initially until payment methods are confirmed available
            disableSubmitButtonUnified();

            // If BTCPay is disabled in the unified configuration, skip the
            // BTCPay session entirely and just mount the component for
            // card/Apple Pay.
            if (!isBtcpayEnabled()) {
                // BTC Pay is disabled - mount component without BTC Pay session
                setTimeout(() => {
                    mountConvesioPayComponent();
                }, 100);
                return;
            }
            
            // Create BTCPay session immediately when radio button is selected
            // Only attempt session creation if BTC Pay is enabled
            if (isBtcpayEnabled()) {
                createBTCPaySession().then(sessionResult => {
                    if (sessionResult.success) {
                        // After session is created, mount the ConvesioPay component
                        setTimeout(() => {
                            mountConvesioPayComponent();
                        }, 100); // Small delay to ensure DOM is ready
                    } else {
                        // BTC Pay session creation failed - mount component anyway so Card and Apple Pay can work
                        // Only show a warning (not blocking error) if BTC Pay was supposed to be enabled
                        // The component will work with Card and Apple Pay even without BTC Pay session
                        if (sessionResult.disabled || sessionResult.message?.toLowerCase().includes('disabled')) {
                            // BTC Pay is intentionally disabled - this is expected, don't log as error
                        } else if (isBtcpayEnabled() && sessionResult.message && !sessionResult.disabled) {
                            // BTC Pay session failed but it should be enabled - still mount for Card/Apple Pay
                        }
                        // Always mount the component so Card and Apple Pay can work
                        // BTC Pay will simply not be available if session creation failed
                        setTimeout(() => {
                            mountConvesioPayComponent();
                        }, 100);
                    }
                }).catch(error => {
                    // BTC Pay session creation error - mount component anyway so Card and Apple Pay can work
                    // Log the error but don't block the component from mounting
                    // BTC Pay session creation error - still mount for Card/Apple Pay
                    // Always mount the component so Card and Apple Pay can work
                    // BTC Pay will simply not be available if session creation failed
                    setTimeout(() => {
                        mountConvesioPayComponent();
                    }, 100);
                });
            } else {
                // Double-check: if somehow we got here but BTC Pay is disabled, just mount
                mountConvesioPayComponent();
            }
        }, []);

        // Handle payment setup (when Place Order is clicked) - USE EXISTING SESSION
        useEffect(() => {
            if (eventRegistration && eventRegistration.onPaymentSetup) {
                const unsubscribe = eventRegistration.onPaymentSetup(async () => {

                    // For ApplePay and Card, we don't need btcPaySession - only check for BTCPay
                    if (!btcPaySession && currentPaymentMethod === 'btcpay') {
                        return {
                            type: emitResponse.responseTypes.ERROR,
                            message: 'BTCPay session not ready. Please try again.',
                        };
                    }

                    // For wallet/card methods, if no BTCPay session exists, create a fake one
                    if (!btcPaySession && (currentPaymentMethod === 'applepay' || currentPaymentMethod === 'googlepay' || currentPaymentMethod === 'card')) {
                        btcPaySession = 'fake-session-' + Date.now();
                    }

                    // Prepare payment method data based on payment type
                    // Ensure all values are strings or booleans to avoid REST API validation errors
                    const paymentMethodData = {
                        peachpay_transaction_id: String('convesio-tx-' + Date.now()),
                        payment_method_type: String(currentPaymentMethod || paymentConfirmedData?.paymentMethod || 'btcpay')
                    };

                    // Include payment data based on payment method
                    if (paymentConfirmedData) {
                        // Add common payment data that PHP expects (use lowercase for WooCommerce Blocks compatibility)
                        // Convert all values to strings to avoid REST API validation errors
                        paymentMethodData.paymentid = String(paymentConfirmedData.paymentId || '');
                        paymentMethodData.paymentmethod = String(paymentConfirmedData.paymentMethod || '');
                        paymentMethodData.status = String(paymentConfirmedData.status || '');
                        paymentMethodData.amount = String(paymentConfirmedData.amount || '0');
                        paymentMethodData.currency = String(paymentConfirmedData.currency || '');
                        paymentMethodData.ordernumber = String(paymentConfirmedData.orderNumber || '');

                        // Also add in camelCase format for PHP compatibility
                        paymentMethodData.paymentId = String(paymentConfirmedData.paymentId || '');
                        paymentMethodData.paymentMethod = String(paymentConfirmedData.paymentMethod || '');

                        if (paymentConfirmedData.paymentMethod === 'card') {
                            // Card payment data
                            paymentMethodData.convesiopay_payment_token = String(paymentConfirmedData.token || window.convesiopayPaymentToken || '');
                        } else if (paymentConfirmedData.paymentMethod === 'applepay') {
                            // Apple Pay payment data
                            // Use token from paymentConfirmedData, or fallback to window.convesiopayPaymentToken
                            const applePayToken = paymentConfirmedData.token || window.convesiopayPaymentToken || '';
                            paymentMethodData.convesiopay_payment_token = String(applePayToken);
                            paymentMethodData.payment_method_type = String('applepay');
                            paymentMethodData.convesiopay_payment_id = String(paymentConfirmedData.paymentId || '');
                            paymentMethodData.paymentId = String(paymentConfirmedData.paymentId || '');
                            paymentMethodData.applepay_payment_id = String(paymentConfirmedData.paymentId || '');
                            paymentMethodData.applepay_amount = String(paymentConfirmedData.amount || '0');
                            paymentMethodData.applepay_currency = String(paymentConfirmedData.currency || '');
                        } else if (paymentConfirmedData.paymentMethod === 'googlepay') {
                            const googlePayToken = paymentConfirmedData.token || window.convesiopayPaymentToken || '';
                            paymentMethodData.convesiopay_payment_token = String(googlePayToken);
                            paymentMethodData.payment_method_type = String('googlepay');
                            paymentMethodData.convesiopay_payment_id = String(paymentConfirmedData.paymentId || '');
                            paymentMethodData.paymentId = String(paymentConfirmedData.paymentId || '');
                            paymentMethodData.googlepay_payment_id = String(paymentConfirmedData.paymentId || '');
                            paymentMethodData.googlepay_amount = String(paymentConfirmedData.amount || '0');
                            paymentMethodData.googlepay_currency = String(paymentConfirmedData.currency || '');
                        } else if (paymentConfirmedData.paymentMethod === 'btcpay') {
                            // BTCPay payment data
                            paymentMethodData.convesiopay_payment_token = String('btc-session-' + btcPaySession);
                            paymentMethodData.btcpay_session_id = String(btcPaySession || '');
                            paymentMethodData.btcpay_payment_id = String(paymentConfirmedData.paymentId || '');
                            paymentMethodData.btcpay_invoice_id = String(paymentConfirmedData.invoiceId || '');
                            paymentMethodData.btcpay_status = String(paymentConfirmedData.status || '');
                        }
                    } else {
                        // Fallback: Check if we have ApplePay token in window
                        if (window.convesiopayApplePayPaymentData && window.convesiopayApplePayPaymentData.token) {
                            // ApplePay payment but paymentConfirmedData not set - use window data
                            paymentMethodData.convesiopay_payment_token = String(window.convesiopayApplePayPaymentData.token);
                            paymentMethodData.payment_method_type = String('applepay');
                            paymentMethodData.paymentmethod = String('applepay');
                            paymentMethodData.status = String('authorized');
                            paymentMethodData.applepay_amount = String(window.convesiopayApplePayPaymentData.amount || '0');
                            paymentMethodData.applepay_currency = String(window.convesiopayApplePayPaymentData.currency || '');
                        } else if (window.convesiopayPaymentToken && currentPaymentMethod === 'applepay') {
                            // ApplePay token in window but not in paymentConfirmedData
                            paymentMethodData.convesiopay_payment_token = String(window.convesiopayPaymentToken);
                            paymentMethodData.payment_method_type = String('applepay');
                            paymentMethodData.paymentmethod = String('applepay');
                            paymentMethodData.status = String('authorized');
                        } else if (window.convesiopayGooglePayPaymentData && window.convesiopayGooglePayPaymentData.token) {
                            paymentMethodData.convesiopay_payment_token = String(window.convesiopayGooglePayPaymentData.token);
                            paymentMethodData.payment_method_type = String('googlepay');
                            paymentMethodData.paymentmethod = String('googlepay');
                            paymentMethodData.status = String('authorized');
                            paymentMethodData.googlepay_amount = String(window.convesiopayGooglePayPaymentData.amount || '0');
                            paymentMethodData.googlepay_currency = String(window.convesiopayGooglePayPaymentData.currency || '');
                        } else if (window.convesiopayPaymentToken && currentPaymentMethod === 'googlepay') {
                            paymentMethodData.convesiopay_payment_token = String(window.convesiopayPaymentToken);
                            paymentMethodData.payment_method_type = String('googlepay');
                            paymentMethodData.paymentmethod = String('googlepay');
                            paymentMethodData.status = String('authorized');
                        } else {
                            // Fallback for BTCPay session
                            paymentMethodData.paymentid = String('btc-session-' + btcPaySession);
                            paymentMethodData.paymentmethod = String('btcpay');
                            paymentMethodData.status = String('pending');
                            paymentMethodData.convesiopay_payment_token = String('btc-session-' + btcPaySession);
                            paymentMethodData.btcpay_session_id = String(btcPaySession || '');
                        }
                    }

                    // Return success with payment data for WooCommerce to process
                    return {
                        type: emitResponse.responseTypes.SUCCESS,
                        meta: {
                            paymentMethodData: paymentMethodData,
                        },
                    };
                });
                return unsubscribe;
            }
        }, [eventRegistration, emitResponse]);

        return createElement(
            'div',
            {
                className: 'wc-convesiopay-unified-blocks-content',
                style: {
                    width: '100%',
                    padding: '0',
                    margin: '0'
                }
            },
            createElement(
                'div',
                {
                    id: 'convesiopay-unified-component-container',
                    className: 'convesiopay-component-container',
                    style: {
                        border: '1px solid #e0e0e0',
                        borderRadius: '5px',
                        background: '#f8f8f8',
                        margin: '0',
                        minHeight: '300px',
                        minWidth: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        width: '100%'
                    }
                }
            )
        );
    };

    /**
     * ConvesioPay Unified payment method configuration
     */
    const ConvesioPayUnifiedPaymentMethod = {
        name: 'peachpay_convesiopay_unified',
        label: createElement(ConvesioPayLabel),
        content: createElement(ConvesioPayUnifiedContent),
        edit: createElement(ConvesioPayUnifiedContent),
        canMakePayment: () => {
            // Hide if no active methods
            return activeMethods.length > 0;
        },
        ariaLabel: 'ConvesioPay',
        supports: {
            features: settings.supports || ['products']
        },
        placeOrderButtonLabel: __('Complete Order', 'peachpay-for-woocommerce'),
    };

    // Reset session state when the page loads
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(() => {
            resetSessionState();
            setupCartTotalMonitoring();

            // Initialize last known cart total
            lastKnownCartTotal = getCurrentCartTotal();
        }, 1000);
    });
    
    // Listen for payment method changes to update button state when switching between methods
    // This ensures button is enabled when switching to Cash on Delivery or other payment methods
    document.addEventListener('change', function(event) {
        if (event.target && event.target.name === 'payment_method') {
            // Small delay to ensure the payment method change is processed
            setTimeout(() => {
                updateSubmitButtonState();
            }, 100);
        }
    }, true); // Use capture phase to catch changes early

    // Register the payment method
    if (typeof registerPaymentMethod === 'function') {
        registerPaymentMethod(ConvesioPayUnifiedPaymentMethod);
    } else {
    }

})(); // End IIFE