/**
 * ConvesioPay WooCommerce Blocks Integration
 */

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


// Get ConvesioPay settings with safety check
const settings = (typeof getSetting === 'function') ? getSetting('peachpay_convesiopay_card_data', {}) : {};

/**
 * Label component for ConvesioPay
 */
const ConvesioPayLabel = () => {
    return createElement('span', { 
        className: 'wc-block-components-payment-method-label wc-block-components-payment-method-label--with-icon' 
    }, settings.title || __('ConvesioPay Card', 'peachpay-for-woocommerce'));
};

/**
 * Content component for ConvesioPay with proper payment setup integration
 */
const ConvesioPayContent = (props) => {
    const { eventRegistration, emitResponse } = props;

    useEffect(() => {
        // Initialize ConvesioPay component for blocks
        const initComponent = () => {
            if (typeof window.initConvesioPayComponent === 'function') {
                window.initConvesioPayComponent();
            } else {
                setTimeout(initComponent, 500);
            }
        };

        // Wait for DOM and scripts to be ready
        setTimeout(initComponent, 100);
    }, []);

    useEffect(() => {
        if (eventRegistration && eventRegistration.onPaymentSetup) {
            const unsubscribe = eventRegistration.onPaymentSetup(async () => {
                
                // Check for both payment token and transaction ID
                const token = window.convesiopayPaymentToken;
                let transactionId = window.peachpayTransactionId;
                
                
                // If no transaction ID, try to create one immediately
                if (!transactionId) {
                    try {
                        await createTransactionIfNeeded();
                        transactionId = window.peachpayTransactionId;
                    } catch (error) {
                        console.log('ConvesioPay Blocks: Transaction creation error:', {
                            message: error.message,
                            stack: error.stack
                        });
                    }
                }
                
                if (!token) {
                    return {
                        type: emitResponse.responseTypes.ERROR,
                        message: 'Payment token is required. Please wait for the payment form to load completely.',
                    };
                }

                if (!transactionId) {
                    return {
                        type: emitResponse.responseTypes.ERROR,
                        message: 'Transaction ID is required. Please refresh the page and try again.',
                    };
                }

                // Ensure both values are strings
                const tokenString = String(token);
                const transactionIdString = String(transactionId);
                
                
                const paymentData = {
                    type: emitResponse.responseTypes.SUCCESS,
                    meta: {
                        paymentMethodData: {
                            convesiopay_payment_token: tokenString,
                            peachpay_transaction_id: transactionIdString,
                        },
                    },
                };
                
                
                return paymentData;
            });
            return unsubscribe;
        }
    }, [eventRegistration, emitResponse]);
    
    /**
     * Create a transaction ID if needed
     */
    const createTransactionIfNeeded = async () => {
        
        return new Promise((resolve, reject) => {
            // Check if we have the AJAX configuration
            if (typeof window.peachpayConvesioPayAjax === 'undefined') {
                console.error('ConvesioPay Blocks: AJAX configuration not found');
                reject(new Error('AJAX configuration not found'));
                return;
            }
            
            // Prepare transaction data for centralized PeachPay endpoint
            const transactionData = {
                gateway_id: 'peachpay_convesiopay_card',
                checkout_location: 'checkout-blocks'
            };
            
            
            // 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);
            }
            
            const transactionUrl = window.peachpayConvesioPayAjax.create_transaction_url || window.peachpayConvesioPayAjax.ajax_url;
            
            fetch(transactionUrl, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(response => {
                
                if (response.success && response.data && response.data.transaction_id) {
                    // Store transaction ID globally
                    window.peachpayTransactionId = response.data.transaction_id;
                    resolve(response.data.transaction_id);
                } else {
                    reject(new Error(response.data ? response.data.message : 'Unknown error'));
                }
            })
            .catch(error => {
                reject(new Error(error.message || 'Network error'));
            });
            
        });
    };

    return createElement(
        'div',
        { className: 'wc-convesiopay-blocks-content' },
        createElement('p', {}, settings.description || __('Pay securely with your credit or debit card via ConvesioPay.', 'peachpay-for-woocommerce')),
        createElement(
            'div',
            { 
                id: 'convesiopay-component-container',
                style: { 
                    border: '1px solid #e0e0e0',
                    borderRadius: '5px',
                    background: '#ffffff',
                    padding: '20px',
                    margin: '10px 0',
                    minHeight: '200px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center'
                }
            },
            createElement(
                'div',
                {
                    id: 'convesiopay-loading',
                    style: { textAlign: 'center', color: '#666' }
                },
                createElement('div', { style: { marginBottom: '10px' } }, '🔄'),
                'Loading ConvesioPay payment form...'
            )
        ),
        createElement('div', {
            id: 'convesiopay-error-message',
            style: {
                display: 'none',
                color: '#e74c3c',
                background: '#fdf2f2',
                border: '1px solid #e74c3c',
                borderRadius: '5px',
                padding: '10px',
                margin: '10px 0'
            }
        }),
        createElement('input', {
            type: 'hidden',
            id: 'convesiopay-payment-token',
            name: 'convesiopay_payment_token',
            value: ''
        }),
        createElement('input', {
            type: 'hidden',
            id: 'peachpay-transaction-id',
            name: 'peachpay_transaction_id',
            value: ''
        })
    );
};

/**
 * ConvesioPay payment method configuration
 */
const ConvesioPayPaymentMethod = {
    name: 'peachpay_convesiopay_card',
    label: createElement(ConvesioPayLabel),
    content: createElement(ConvesioPayContent),
    edit: createElement(ConvesioPayContent),
    canMakePayment: () => true,
    ariaLabel: settings.title || __('ConvesioPay Card', 'peachpay-for-woocommerce'),
    supports: {
        features: settings.supports || ['products']
    },
    // Payment processing for WooCommerce Blocks
    placeOrderButtonLabel: __('Place order', 'peachpay-for-woocommerce'),
};

// Register the payment method with safety check
if (typeof registerPaymentMethod === 'function') {
    registerPaymentMethod(ConvesioPayPaymentMethod);
}

// Integration with ConvesioPay direct component for WooCommerce Blocks
document.addEventListener('DOMContentLoaded', function() {
    // Listen for WooCommerce Blocks checkout events
    const { select, subscribe } = wp.data;
    
    if (select && subscribe) {
        
        // Listen to checkout store changes for payment token validation
        subscribe(() => {
            const checkoutStore = select('wc/store/checkout');
            if (!checkoutStore) return;
            
            const checkoutStatus = {
                isProcessing: checkoutStore.isProcessing(),
                isBeforeProcessing: checkoutStore.isBeforeProcessing(),
                isComplete: checkoutStore.isComplete(),
                hasError: checkoutStore.hasError()
            };
            
            // Validate payment token and transaction ID before processing
            if (checkoutStatus.isBeforeProcessing) {
                const paymentStore = select('wc/store/payment');
                const activeMethod = paymentStore ? paymentStore.getActivePaymentMethod() : null;
                
                if (activeMethod === 'peachpay_convesiopay_card') {
                    const token = window.convesiopayPaymentToken;
                    const transactionId = window.peachpayTransactionId;
                }
            }
        });
    }
});