/**
 * ConvesioPay BTCPay WooCommerce Blocks Integration
 * Following the same component creation pattern as card payments
 */

(function() {
    'use strict';

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

    // Get ConvesioPay BTCPay settings
    const settings = getSetting('peachpay_convesiopay_btcpay_data', {});

    /**
     * Check whether BTCPay is enabled before creating sessions or mounting UI.
     *
     * The PHP Blocks integration only localizes `enabled` when the gateway is
     * active. If the script is present with empty/default settings, treat that
     * as disabled and skip all session work.
     */
    const isBtcpayEnabled = () => {
        return settings.enabled === true || settings.enabled === 'yes';
    };

    // Global state management
    let btcPaySession = null;
    let isSessionCreated = false;
    let convesioPayComponent = null;
    let isComponentMounted = false;
    
    // Payment status tracking
    let paymentConfirmedData = null;
    
    /**
     * Reset BTCPay session state for new checkout
     */
    /**
     * Reset BTCPay session state when starting a completely new checkout
     * This should only be called when we detect a new checkout session
     */
    const resetBTCPaySessionState = () => {
        btcPaySession = null;
        isSessionCreated = false;
        paymentConfirmedData = null;
    };
    

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

    /**
     * Listen for postMessage events from BTCPay iframe
     */
    const setupBTCPayMessageListener = () => {
        
        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, // Use as payment ID
                        status: 'Processing',
                        paymentId: messageData.invoiceId // invoiceId becomes our payment ID
                    };
                    
                    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 (captured via postMessage from BTCPay iframe)
        if (!paymentConfirmedData) {
            console.warn('ConvesioPay BTCPay: Payment not confirmed during modal session - disabling place order button click');
            
            // 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 to ensure fresh session for next checkout
        setTimeout(() => {
            resetBTCPaySessionState();
        }, 5000); // Reset after 5 seconds to allow order processing to complete
        
        // Find the place order button with the specific classes
        const placeOrderButton = document.querySelector('.components-button.wc-block-components-button.wp-element-button.wc-block-components-checkout-place-order-button.contained');
        
        if (placeOrderButton) {
            placeOrderButton.click();
        } else { 
            // Try alternative selectors
            const altButton1 = document.querySelector('.wc-block-components-checkout-place-order-button');
            const altButton2 = document.querySelector('[data-block-name="woocommerce/checkout-order-summary-block"] button');
            const altButton3 = document.querySelector('button[type="submit"]');
            
            if (altButton1) {
                altButton1.click();
            } else if (altButton2) {
                altButton2.click();
            } else if (altButton3) {
                altButton3.click();
            } else {
                console.error('ConvesioPay BTCPay: Could not find place order button with any selector');
            }
        }
    };

    /**
     * Get real WooCommerce order number from blocks checkout
     */
    const getRealOrderNumber = () => {
        // 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) {
                    // Try to get order ID from checkout store
                    const orderId = checkoutStore.getOrderId();
                    if (orderId) {
                        return orderId.toString();
                    }
                }
            } catch (e) {
            }
        }

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

        // For blocks checkout, use cart hash + timestamp as order identifier (before order creation)
        // This ensures uniqueness even if cart contents are the same
        if (window.wp && window.wp.data && window.wp.data.select) {
            try {
                const cartStore = window.wp.data.select('wc/store/cart');
                if (cartStore) {
                    const cartHash = cartStore.getCartHash();
                    if (cartHash) {
                        const timestamp = Date.now();
                        const cartOrderNumber = `CART-${cartHash}-${timestamp}`;
                        return cartOrderNumber;
                    }
                }
            } catch (e) {
            }
        }

        // Last resort: generate session-based identifier with higher precision
        const timestamp = Date.now();
        const random = Math.floor(Math.random() * 10000);
        const sessionOrderNumber = `SESSION-BTCPAY-${timestamp}-${random}`;
        return sessionOrderNumber;
    };

    /**
     * Get order data for BTCPay session from WooCommerce Blocks
     */
    const getBlocksOrderData = () => {
        
        const orderData = {
            isValid: false,
            orderNumber: getRealOrderNumber(),
            amount: 0,
            currency: 'USD',
            email: '',
            name: 'Customer'
        };
        
        // 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); // Already in minor units
                }
                
                if (cartTotals && cartTotals.currency_code) {
                    orderData.currency = cartTotals.currency_code;
                }
            } catch (e) {
            }
        }
        
        // Fallback: Try to get from DOM
        if (!orderData.amount) {
            const totalElement = document.querySelector('.wp-block-woocommerce-checkout-order-summary-totals-block .wc-block-formatted-money-amount, .wc-block-components-totals-footer-item .wc-block-formatted-money-amount');
            if (totalElement) {
                const totalText = totalElement.textContent.replace(/[^0-9.]/g, '');
                const total = parseFloat(totalText) || 0;
                orderData.amount = Math.round(total * 100); // Convert to cents
            }
        }
        
        // Get customer info - placeholder for now
        orderData.email = 'customer@example.com';
        orderData.name = 'Customer';
        
        orderData.isValid = orderData.amount > 0;
        
        return orderData;
    };

    /**
     * Create BTCPay session via AJAX call (Backend - Required Step 1)
     */
    const createBTCPaySessionAjax = async (orderData) => {
        if (!isBtcpayEnabled()) {
            return {
                success: false,
                data: { message: 'BTCPay payment method is disabled' },
                disabled: true
            };
        }

        
        const requestData = {
            action: 'peachpay_convesiopay_create_btcpay_session',
            nonce: settings.nonce || '',
            integration: 'PeachPay',
            returnUrl: window.location.href,
            orderNumber: orderData.orderNumber,
            amount: orderData.amount,
            currency: orderData.currency,
            email: orderData.email,
            name: orderData.name
        };
        
        
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            const ajaxUrl = settings.ajax_url || '/wp-admin/admin-ajax.php';
            
            xhr.open('POST', ajaxUrl, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            
            xhr.onload = function() {
                if (xhr.status === 200) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        resolve(response);
                    } catch (e) {
                        console.error('ConvesioPay BTCPay Blocks: Failed to parse JSON:', xhr.responseText);
                        reject(new Error('Invalid server response'));
                    }
                } else {
                    console.error('ConvesioPay BTCPay Blocks: AJAX Error:', xhr.status, xhr.statusText);
                    reject(new Error('Server request failed: ' + xhr.status));
                }
            };
            
            xhr.onerror = function() {
                console.error('ConvesioPay BTCPay Blocks: Network error');
                reject(new Error('Network error'));
            };
            
            const params = new URLSearchParams(requestData).toString();
            xhr.send(params);
        });
    };

    /**
     * Create BTCPay session when radio button is selected
     */
    const createBTCPaySession = async () => {
        if (!isBtcpayEnabled()) {
            return { success: false, message: 'BTCPay payment method is disabled', disabled: true };
        }

        
        // Check if we already have a valid session for this checkout
        if (isSessionCreated && btcPaySession) {
            return { success: true, session: btcPaySession };
        }
        
        
        try {
            const orderData = getBlocksOrderData();
            if (!orderData.isValid) {
                throw new Error('Unable to get order details');
            }
            
            const sessionResponse = await createBTCPaySessionAjax(orderData);
            
            
            if (!sessionResponse.success || !sessionResponse.data?.session) {
                throw new Error(sessionResponse.message || 'Failed to create BTCPay session');
            }
            
            // Store session for current checkout
            btcPaySession = sessionResponse.data.session;
            isSessionCreated = true;
            
            return { success: true, session: btcPaySession };
            
        } catch (error) {
            console.error('ConvesioPay BTCPay Blocks: Session creation failed:', error);
            return { success: false, message: error.message };
        }
    };



    /**
     * Create and mount ConvesioPay component (SAME PATTERN AS CARD PAYMENTS)
     */
    const createAndMountConvesioPayComponent = async () => {
        if (!isBtcpayEnabled()) {
            return { success: false, message: 'BTCPay payment method is disabled', disabled: true };
        }

        
        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');
            }
            // Debug logging for settings and config

            // 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 (SAME PATTERN AS CARD PAYMENTS)
            const cpay = window.ConvesioPay(apiKey);
            
            // Get order data for customer email
            const orderData = getBlocksOrderData();
            
            
            // Initialize component (EXACTLY SAME PATTERN AS CARD PAYMENTS)
            const component = cpay.component({
                environment: config.api_url?.includes('qa') ? 'test' : 'live',
                clientKey: clientKey,
                customerEmail: orderData.email || 'customer@example.com',
                integration: 'PeachPay',
                theme: 'light'
            });
            
            
            // Store globally (SAME AS CARD PAYMENTS)
            convesioPayComponent = component;
            isComponentMounted = true;
            
            component.on('change', () => {
                // Payment status changes are now handled by postMessage events
                // from BTCPay iframe when status becomes 'Processing'
            });
            
            return { success: true, component: component };
            
        } catch (error) {
            console.error('ConvesioPay BTCPay Blocks: Component creation/mounting failed:', error);
            return { success: false, message: error.message };
        }
    };

    /**
     * Mount ConvesioPay component directly in the content div
     */
    const mountConvesioPayComponent = async () => {
        
        if (!btcPaySession) {
            console.error('ConvesioPay BTCPay Blocks: No session available for component mounting');
            return;
        }
        
        // Check if component is already mounted in the content
        const existingComponent = document.querySelector('#convesiopay-btcpay-component-container .convesiopay-component');
        if (existingComponent) {
            return;
        }
        
        try {
            // Create and mount the component
            const componentResult = await createAndMountConvesioPayComponent();
            
            if (componentResult.success) {
                
                // Find the content container
                const contentContainer = document.querySelector('.wc-convesiopay-btcpay-blocks-content');
                if (!contentContainer) {
                    throw new Error('Content container not found');
                }
                
                // The component container already exists in the content div
                const componentContainer = contentContainer.querySelector('#convesiopay-btcpay-component-container');
                if (!componentContainer) {
                    throw new Error('Component container not found in content');
                }
                
                // Clear the loading content
                componentContainer.innerHTML = '';
                
                // Mount the component in the container
                await convesioPayComponent.mount('#convesiopay-btcpay-component-container');
                
                const orderData = getBlocksOrderData();
                // Create BTCPay intent using the mounted component
                await convesioPayComponent.createBTCPayIntent({
                    session: btcPaySession,
                    integration: 'PeachPay',
                    returnUrl: window.location.href,
                    orderNumber: orderData.orderNumber,
                    amount: orderData.amount,
                    currency: orderData.currency,
                    email: orderData.email,
                    name: orderData.name
                });
                
                // Set up postMessage listener for iframe communication
                setupBTCPayMessageListener();
                
                
            } else {
                throw new Error(componentResult.message || 'Failed to create component');
            }
            
        } catch (error) {
            console.error('ConvesioPay BTCPay Blocks: Component mounting or intent creation failed:', error);
            
            // Show error in the content area
            const contentContainer = document.querySelector('.wc-convesiopay-btcpay-blocks-content');
            if (contentContainer) {
                const errorDiv = document.createElement('div');
                errorDiv.style.cssText = `
                    color: red;
                    font-size: 14px;
                    text-align: center;
                    padding: 20px;
                    border: 1px solid #ff0000;
                    border-radius: 5px;
                    background: #fff5f5;
                    margin: 10px 0;
                `;
                errorDiv.innerHTML = `
                    <div>❌ Error</div>
                    <small>Failed to create BTCPay payment: ${error.message}</small>
                `;
                
                // Insert error message
                const descriptionP = contentContainer.querySelector('p');
                if (descriptionP) {
                    descriptionP.parentNode.insertBefore(errorDiv, descriptionP.nextSibling);
                } else {
                    contentContainer.appendChild(errorDiv);
                }
            }
        }
    };

    /**
     * Content component for ConvesioPay BTCPay
     */
    const ConvesioPayBTCPayContent = (props) => {
        const { eventRegistration, emitResponse } = props;

        // Create BTCPay session and mount component when radio button is selected
        useEffect(() => {
            if (!isBtcpayEnabled()) {
                return;
            }

            
            // Create BTCPay session immediately when radio button is selected
            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 {
                    console.error('ConvesioPay BTCPay Blocks: Failed to create BTCPay session on radio selection:', sessionResult.message);
                }
            }).catch(error => {
                console.error('ConvesioPay BTCPay Blocks: BTCPay session creation failed:', error);
            });
        }, []);

        // Handle payment setup (when Place Order is clicked) - USE EXISTING SESSION
        useEffect(() => {
            if (eventRegistration && eventRegistration.onPaymentSetup) {
                const unsubscribe = eventRegistration.onPaymentSetup(async () => {
                    
                    // Check if we have a session (created when radio button was selected)
                    if (!btcPaySession) {
                        console.error('ConvesioPay BTCPay Blocks: No BTCPay session available');
                        return {
                            type: emitResponse.responseTypes.ERROR,
                            message: 'BTCPay session not ready. Please try again.',
                        };
                    }
                    
                    
                    // Prepare payment method data
                    const paymentMethodData = {
                        convesiopay_payment_token: 'btc-session-' + btcPaySession,
                        peachpay_transaction_id: 'btc-tx-' + Date.now(),
                        payment_method_type: 'btcpay',
                        btcpay_session_id: btcPaySession
                    };
                    
                    // Include payment ID if we have payment confirmation
                    if (paymentConfirmedData && paymentConfirmedData.paymentId) {
                        paymentMethodData.btcpay_payment_id = paymentConfirmedData.paymentId;
                        paymentMethodData.btcpay_invoice_id = paymentConfirmedData.invoiceId;
                        paymentMethodData.btcpay_status = paymentConfirmedData.status;
                    }
                    
                    // 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-btcpay-blocks-content' },
            createElement('p', {}, settings.description || __('Pay with cryptocurrency via ConvesioPay BTCPay.', 'peachpay-for-woocommerce')),
            createElement(
                'div',
                { 
                    id: 'convesiopay-btcpay-component-container',
                    className: 'btcpay-component-container',
                    style: { 
                        padding: '20px',
                        border: '1px solid #e0e0e0',
                        borderRadius: '5px',
                        background: '#f8f8f8',
                        margin: '10px 0',
                        minHeight: '200px',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                    }
                },
                createElement('div', { 
                    style: { textAlign: 'center', color: '#666' }
                }, 
                    createElement('div', { style: { fontSize: '16px', marginBottom: '8px' } }, '⏳'),
                    createElement('div', {}, 'Loading BTCPay payment component...'),
                    createElement('small', { style: { fontSize: '12px' } }, 'Please wait while we prepare your crypto payment')
                )
            )
        );
    };

    /**
     * ConvesioPay BTCPay payment method configuration
     */
    const ConvesioPayBTCPayPaymentMethod = {
        name: 'peachpay_convesiopay_btcpay',
        label: createElement(ConvesioPayBTCPayLabel),
        content: createElement(ConvesioPayBTCPayContent),
        edit: createElement(ConvesioPayBTCPayContent),
        canMakePayment: () => {
            return isBtcpayEnabled();
        },
        ariaLabel: settings.title || __('Crypto', 'peachpay-for-woocommerce'),
        supports: {
            features: settings.supports || ['products']
        },
        placeOrderButtonLabel: __('Complete Order', 'peachpay-for-woocommerce'),
    };


    
    // Reset session state when the page loads to ensure fresh sessions
    document.addEventListener('DOMContentLoaded', function() {
        // Small delay to let other scripts initialize first
        setTimeout(() => {
            resetBTCPaySessionState();
        }, 1000);
    });

    // Register the payment method
    if (typeof registerPaymentMethod === 'function') {
        registerPaymentMethod(ConvesioPayBTCPayPaymentMethod);
    } else {
        console.error('ConvesioPay BTCPay Blocks: registerPaymentMethod is not available');
    }

})(); // End IIFE
