/**
 * ConvesioPay Checkout Integration - Direct Component Approach
 * Following CONVESIOPAY_COMPLETE_FLOW_GUIDE.md
 */
jQuery(document).ready(function($) {
    'use strict';


    // Global variables
    let convesiopayComponent = null;
    let isComponentReady = false;
    
    // Check if WooCommerce Blocks checkout
    const isWooCommerceBlocks = typeof wp !== 'undefined' && wp.data && wp.data.select && wp.data.select('wc/store/payment');

    /**
     * Initialize ConvesioPay component
     * Following flow guide Section 3.2
     */
    function initConvesioPayComponent() {
        
        // Check if container exists
        const container = document.getElementById('convesiopay-component-container');
        if (!container) {
            return;
        }

        // Check if already initialized
        if (convesiopayComponent) {
            return;
        }

        if (typeof ConvesioPay === 'undefined') {
            setTimeout(initConvesioPayComponent, 500);
            return;
        }

        // Get configuration
        const config = window.peachpayConvesioPayConfig;
        if (!config) {
            showError('ConvesioPay configuration not found');
            return;
        }


        try {
            
            // Create ConvesioPay instance with API key
            const cpay = ConvesioPay(config.apiKey);
            
            // Create component using the instance
            convesiopayComponent = cpay.component({
                environment: config.api_url?.includes('qa') ? 'test' : 'live',
                clientKey: config.clientKey,
                customerEmail: config.customerEmail || '',
                integration: 'PeachPay',
                theme: config.theme || 'light'
            });

            if (convesiopayComponent && typeof convesiopayComponent.mount === 'function') {
                // Mount the component to container
                convesiopayComponent.mount('#convesiopay-component-container');

                // Set up event listeners - ConvesioPay only supports 'change' event
                convesiopayComponent.on('change', handleComponentChange);
                
                // Component is ready after mounting (no 'ready' event available)
                isComponentReady = true;
                
                // Hide loading message
                const loading = document.getElementById('convesiopay-loading');
                if (loading) {
                    loading.style.display = 'none';
                }
                
                hideError();
                
                // Create PeachPay transaction when component is ready
                createPeachPayTransaction();

                // Make component globally available for other payment methods (Apple Pay, BTCPay)
                window.convesioPayComponent = convesiopayComponent;

            } else {
                showError('Failed to create payment component');
            }
        } catch (error) {
            showError('Error loading payment form: ' + error.message);
        }
    }

    /**
     * Handle component ready event
     */
    function handleComponentReady() {
        isComponentReady = true;
        
        // Hide loading message
        const loading = document.getElementById('convesiopay-loading');
        if (loading) {
            loading.style.display = 'none';
        }
        
        hideError();
        
        // Create PeachPay transaction when component is ready
        createPeachPayTransaction();
    }
    
    /**
     * Create PeachPay transaction for ConvesioPay
     */
    function createPeachPayTransaction() {
        
        // Check if we have the AJAX configuration
        if (typeof window.peachpayConvesioPayAjax === 'undefined') {
            showError('Payment system configuration error. Please refresh and try again.');
            return;
        }
        
        
        // Prepare transaction data for centralized PeachPay endpoint
        const transactionData = {
            gateway_id: 'peachpay_convesiopay_card',
            checkout_location: isWooCommerceBlocks ? 'checkout-blocks' : 'checkout-page'
        };
        
        // 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);
        }
        
        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;
                
                // Add transaction ID to payment data
                addTransactionIdToPaymentData(response.data.transaction_id);
                
                // Update hidden fields
                updateHiddenFields(response.data.transaction_id);
                
            } else {
                showError('Failed to initialize payment system. Please try again.');
            }
        })
        .catch(error => {
            
            showError('Payment system initialization failed. Please refresh and try again.');
        });
        
        // Keep the original jQuery.ajax as backup (commented out)
        /*
        jQuery.ajax({
            url: transactionUrl,
            type: 'POST',
            data: transactionData,
            success: function(response) {
                
                if (response.success && response.data && response.data.transaction_id) {
                    // Store transaction ID globally
                    window.peachpayTransactionId = response.data.transaction_id;
                    
                    // Add transaction ID to payment data
                    addTransactionIdToPaymentData(response.data.transaction_id);
                    
                    // Update hidden fields
                    updateHiddenFields(response.data.transaction_id);
                    
                } else {
                    showError('Failed to initialize payment system. Please try again.');
                }
            },
            error: function(xhr, status, error) {
                console.log('ConvesioPay: XHR responseText:', xhr.responseText);
                console.log('ConvesioPay: Error:', error);
                
                
                try {
                    const errorResponse = JSON.parse(xhr.responseText);
                    console.log('ConvesioPay: Parsed error response:', errorResponse);
                } catch (e) {
                    console.log('ConvesioPay: Could not parse error response as JSON');
                }
                
                showError('Payment system initialization failed. Please refresh and try again.');
            }
        });
        */
        
    }
    
    /**
     * Add transaction ID to payment forms
     */
    function addTransactionIdToPaymentData(transactionId) {
        // For traditional checkout forms
        let transactionField = document.getElementById('peachpay-transaction-id-field');
        if (!transactionField) {
            transactionField = document.createElement('input');
            transactionField.type = 'hidden';
            transactionField.id = 'peachpay-transaction-id-field';
            transactionField.name = 'peachpay_transaction_id';
            
            // Find the payment form and add the field
            const paymentForm = document.querySelector('#convesiopay-payment-form, form.checkout');
            if (paymentForm) {
                paymentForm.appendChild(transactionField);
            }
        }
        
        if (transactionField) {
            transactionField.value = transactionId;
        }
        
        // Also update the hidden field in the blocks component
        const blocksTransactionField = document.getElementById('peachpay-transaction-id');
        if (blocksTransactionField) {
            blocksTransactionField.value = transactionId;
        }
        
    }

    /**
     * Handle component change event
     * Following ConvesioPay documentation pattern
     */
    async function handleComponentChange(event) {
        
        if (event.isValid) {
            // All component fields are valid and we can get the token
            try {
                const tokenResult = convesiopayComponent.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) {
                    storePaymentToken(token);
                }
                
                // Component is valid, enable checkout
                enableSubmitButton();
                hideError();
            } catch (error) {
                showError('Failed to create payment token');
                disableSubmitButton();
            }
        } else {
            // Handle errors, one or more component fields are not valid
            showError('Please complete all required payment fields');
            disableSubmitButton();
        }
    }

    /**
     * Handle component error event
     */
    function handleComponentError(error) {
        showError('Payment form error: ' + (error.message || 'Unknown error'));
        disableSubmitButton();
    }

    /**
     * Create payment token
     * Following ConvesioPay documentation
     */
    async function createPaymentToken() {
        if (!convesiopayComponent || !isComponentReady) {
            throw new Error('ConvesioPay component not ready');
        }

        try {
            // Use the correct ConvesioPay SDK method
            const token = await convesiopayComponent.createToken();

            if (!token) {
                throw new Error('Token creation returned empty result');
            }

            return token;
        } catch (error) {
            throw error;
        }
    }

    /**
     * Store payment token in form
     */
    function storePaymentToken(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
        if (isWooCommerceBlocks) {
            window.convesiopayPaymentToken = token;
        }
        
    }

    /**
     * Update hidden fields with transaction ID
     */
    function updateHiddenFields(transactionId) {
        // Update all hidden fields
        const fields = [
            'peachpay-transaction-id-field',
            'peachpay-transaction-id',
            'convesiopay-payment-token'
        ];
        
        fields.forEach(fieldId => {
            const field = document.getElementById(fieldId);
            if (field) {
                if (fieldId.includes('transaction')) {
                    field.value = transactionId;
                }
            }
        });
    }

    /**
     * Utility functions
     */
    function showError(message) {
        const errorDiv = document.getElementById('convesiopay-error-message');
        if (errorDiv) {
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
        }
    }

    function hideError() {
        const errorDiv = document.getElementById('convesiopay-error-message');
        if (errorDiv) {
            errorDiv.style.display = 'none';
        }
    }

    function enableSubmitButton() {
        $('button[type="submit"], input[type="submit"]', '.woocommerce-checkout').prop('disabled', false);
    }

    function disableSubmitButton() {
        $('button[type="submit"], input[type="submit"]', '.woocommerce-checkout').prop('disabled', true);
    }

    /**
     * WooCommerce Blocks integration
     */
    if (isWooCommerceBlocks) {
        
        // Hook into Blocks checkout to inject payment token
        if (typeof wp !== 'undefined' && wp.hooks) {
            wp.hooks.addFilter(
                'woocommerce_blocks_checkout_payment_method_data',
                'convesiopay/add-payment-token',
                function(paymentMethodData, paymentMethodName) {
                    if (paymentMethodName === 'peachpay_convesiopay_card') {
                        // Add ConvesioPay payment token
                        if (window.convesiopayPaymentToken) {
                            paymentMethodData.convesiopay_payment_token = window.convesiopayPaymentToken;
                        }
                        
                        // Add PeachPay transaction ID
                        if (window.peachpayTransactionId) {
                            paymentMethodData.peachpay_transaction_id = window.peachpayTransactionId;
                        }
                        
                    }
                    return paymentMethodData;
                }
            );
        }
    }

    /**
     * Traditional checkout form submission handler
     */
    $('form.checkout').on('checkout_place_order_peachpay_convesiopay_card', async function() {
        
        // Check if we already have a token
        const existingToken = document.getElementById('convesiopay-payment-token');
        if (existingToken && existingToken.value) {
            return true; // Allow form submission
        }
        
        // Try to create token if component is ready
        if (convesiopayComponent && isComponentReady) {
            try {
                const token = await createPaymentToken();
                storePaymentToken(token);
                return true; // Allow form submission
            } catch (error) {
                showError('Payment processing failed. Please try again.');
                return false; // Prevent form submission
            }
        } else {
            showError('Payment form not ready. Please wait and try again.');
            return false; // Prevent form submission
        }
    });

    /**
     * Initialize component when payment method is selected
     */
    
    // For traditional checkout
    $(document).on('change', 'input[name="payment_method"]', function() {
        if ($(this).val() === 'peachpay_convesiopay_card') {
            // Create transaction immediately when payment method is selected
            createPeachPayTransaction();
            setTimeout(initConvesioPayComponent, 300);
        }
    });

    // Initialize if ConvesioPay is already selected
    if ($('input[name="payment_method"][value="peachpay_convesiopay_card"]').is(':checked')) {
        createPeachPayTransaction();
        setTimeout(initConvesioPayComponent, 1000);
    }

    // For WooCommerce Blocks - use MutationObserver to detect when container appears
    if (isWooCommerceBlocks) {
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1 && node.id === 'convesiopay-component-container') {
                        // Create transaction immediately for WooCommerce Blocks
                        createPeachPayTransaction();
                        setTimeout(initConvesioPayComponent, 300);
                    }
                });
            });
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
        
        // Also create transaction immediately when page loads for WooCommerce Blocks
        $(document).ready(function() {
            createPeachPayTransaction();
        });
    }

    // Make initConvesioPayComponent available globally for debugging
    window.initConvesioPayComponent = initConvesioPayComponent;
    
});