/**
 * ConvesioPay ApplePay WooCommerce Blocks Integration
 * Following the same component creation pattern as BTCPay 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 ApplePay settings
    const settings = getSetting('peachpay_convesiopay_applepay_data', {});

    // Global state management
    let applePaySession = null;
    let isSessionCreated = false;
    let convesioPayComponent = null;
    let isComponentMounted = false;

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

    /**
     * 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 orderKey = urlParams.get('key');
        const orderId = urlParams.get('order');
        
        if (orderId) {
            return orderId;
        }

        // For blocks checkout, use cart hash as order identifier (before order creation)
        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 cartOrderNumber = `CART-${cartHash}`;
                        return cartOrderNumber;
                    }
                }
            } catch (e) {
            }
        }

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

    /**
     * Get order data for ApplePay 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 ApplePay session using ConvesioPay component
     */
    const createApplePaySession = async () => {
        
        if (isSessionCreated) {
            return { success: true, session: applePaySession };
        }
        
        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 (SAME PATTERN AS BTCPay)
            const cpay = window.ConvesioPay(apiKey);
            
            // Get order data for customer email
            const orderData = getBlocksOrderData();
            
            if (!orderData.isValid) {
                throw new Error('Unable to get order details');
            }
            
            
            // Initialize component (EXACTLY SAME PATTERN AS BTCPay)
            const component = cpay.component({
                environment: config.api_url?.includes('qa') ? 'test' : 'live',
                clientKey: clientKey,
                customerEmail: orderData.email || 'customer@example.com',
                integration: 'PeachPay',
                theme: 'light'
            });
            
            
            // Mount the component (SAME AS BTCPay)
            await component.mount('#convesiopay-applepay-component-container');
            
            // Store globally (SAME AS BTCPay)  
            convesioPayComponent = component;
            isComponentMounted = true;
            
            
            component.on('change', (event) => {
                
                if (event.type === 'applepay') {
                    
                    if (event.isSuccessful) {
                        // NEW FLOW: On successful device confirmation, extract token from event.token
                        // Payment will NOT be automatically created - backend will create it with secret key
                        const paymentToken = event.token
                            ?? event.paymentData?.token
                            ?? event.data?.token
                            ?? null;
                        
                        if (paymentToken) {
                            // Store token globally for backend to use when creating payment
                            window.convesiopayPaymentToken = paymentToken;
                            window.convesiopayApplePayPaymentData = {
                                paymentMethod: 'applepay',
                                token: paymentToken,
                                amount: event.paymentData?.amount || orderData.amount,
                                currency: event.paymentData?.currency || orderData.currency,
                                status: 'authorized' // Device authorized, payment will be created by backend
                            };
                        }
                    }
                }
            });
            
            
            // Create ApplePay session using the component method (NEW FLOW - no orderNumber)
            // orderNumber is removed to use the new token-based flow where payment is created after order exists
            const sessionResult = await component.createApplePaySession({
                integration: '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
            });
            
            
            // Store session globally
            applePaySession = sessionResult;
            isSessionCreated = true;
            
            return { success: true, session: sessionResult, component: convesioPayComponent };
            
        } catch (error) {
            return { success: false, message: error.message };
        }
    };

    /**
     * Mount ConvesioPay component and create ApplePay session (SAME PATTERN AS BTCPay)
     */
    const mountComponentAndCreateSession = async () => {
        
        try {
            // Create ApplePay session
            const sessionResult = await createApplePaySession();
            
            if (sessionResult.success) {
                return sessionResult;
            } else {
                throw new Error(sessionResult.message || 'Failed to create component');
            }
            
        } catch (error) {
            // Show error in the content area
            const contentContainer = document.querySelector('.wc-convesiopay-applepay-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 ApplePay 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 ApplePay
     */
    const ConvesioPayApplePayContent = (props) => {
        const { eventRegistration, emitResponse } = props;

        // Create ApplePay session and mount component when radio button is selected
        useEffect(() => {
            
            // Check if Apple Pay is available on this device/browser
            if (!window.ApplePaySession || !ApplePaySession.canMakePayments()) {
                return;
            }
            
            // Create ApplePay session and mount component immediately when radio button is selected
            mountComponentAndCreateSession().then(sessionResult => {
                // Session created successfully
            }).catch(() => {
                // ApplePay session creation failed
            });
        }, []);

        // 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 (!applePaySession) {
                        return {
                            type: emitResponse.responseTypes.ERROR,
                            message: 'ApplePay session not ready. Please try again.',
                        };
                    }
                    
                    
                    // Return success with existing session data for WooCommerce to process
                    return {
                        type: emitResponse.responseTypes.SUCCESS,
                        meta: {
                            paymentMethodData: {
                                convesiopay_payment_token: 'applepay-session-' + JSON.stringify(applePaySession),
                                peachpay_transaction_id: 'applepay-tx-' + Date.now(),
                                payment_method_type: 'applepay',
                                applepay_session_data: applePaySession
                            },
                        },
                    };
                });
                return unsubscribe;
            }
        }, [eventRegistration, emitResponse]);

        return createElement(
            'div',
            { className: 'wc-convesiopay-applepay-blocks-content' },
            createElement('p', {}, settings.description || __('Pay with Apple Pay via ConvesioPay.', 'peachpay-for-woocommerce')),
            createElement(
                'div',
                { 
                    id: 'convesiopay-applepay-component-container',
                    className: 'applepay-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 ApplePay payment component...'),
                    createElement('small', { style: { fontSize: '12px' } }, 'Please wait while we prepare your Apple Pay payment')
                )
            )
        );
    };

    /**
     * ConvesioPay ApplePay payment method configuration
     */
    const ConvesioPayApplePayPaymentMethod = {
        name: 'peachpay_convesiopay_applepay',
        label: createElement(ConvesioPayApplePayLabel),
        content: createElement(ConvesioPayApplePayContent),
        edit: createElement(ConvesioPayApplePayContent),
        canMakePayment: () => {
            // Check if Apple Pay is available
            try {
                const hasApplePaySession = typeof window.ApplePaySession !== 'undefined';
                const canMakePayments = hasApplePaySession ? ApplePaySession.canMakePayments() : false;
                const available = hasApplePaySession && canMakePayments;
                
                
                return available;
            } catch (error) {
                return false;
            }
        },
        ariaLabel: settings.title || __('Apple Pay', 'peachpay-for-woocommerce'),
        supports: {
            features: settings.supports || ['products']
        },
        placeOrderButtonLabel: __('Complete Order', 'peachpay-for-woocommerce'),
    };

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

})(); // End IIFE