/**
 * Stablezact Payment Modal JavaScript - Refactored to use CoinleyVanilla SDK
 *
 * Handles the payment modal functionality using the loaded CoinleyVanilla script.
 */
(function($) {
    'use strict';

    // Warn early if the CoinleyVanilla SDK failed to load. (Moved here from an inline
    // inline script in the payment-modal template to comply with the wp_enqueue policy.)
    $(function() {
        if (typeof CoinleyVanilla === 'undefined') {
            console.warn('CoinleyVanilla SDK not loaded. Payment functionality may not work.');
        }
    });

    let orderData = {};
    let stablezactPayment = null;

    // Merchant wallet configuration - dynamically loaded from backend
    // This will be populated from stablezactParams.merchantWallets after script loads
    let merchantWallets = {};

    // Main StablezactPaymentModal Class - Refactored for CoinleyVanilla SDK
    class StablezactPaymentModal {
        constructor() {
            this.modal = $('#stablezact-payment-modal');
            this.modalOverlay = $('.stablezact-modal-overlay');
            this.closeBtn = $('.stablezact-modal-close');
            this.cancelBtns = $('.stablezact-btn-cancel');
            this.loadingOverlay = $('.stablezact-loading-overlay');
            
            this.init();
        }

        init() {
            // Load merchant wallets from PHP-localized data
            this.loadMerchantWallets();
            this.bindEvents();
            this.initStablezactPaymentGateway();
        }

        // Load merchant wallet addresses from backend configuration
        loadMerchantWallets() {
            if (typeof stablezactParams !== 'undefined' && stablezactParams.merchantWallets) {
                merchantWallets = stablezactParams.merchantWallets;

                // Log which networks are configured
                const networks = Object.keys(merchantWallets);
                if (networks.length > 0) {
                } else {
                }
            } else {
                merchantWallets = {};
            }
        }

        // Initialize Stablezact Payment Gateway using CoinleyVanilla SDK
        initStablezactPaymentGateway() {
            // Wait for CoinleyVanilla SDK to load if not immediately available
            const initWithRetry = (attempts = 0, maxAttempts = 10) => {
                if (typeof CoinleyVanilla !== "undefined") {
                    try {
                        const sdkConfig = {
                            publicKey: stablezactParams.publicKey,
                            apiUrl: stablezactParams.apiUrl,
                            theme: "light",
                            debug: stablezactParams.debug || false,
                        };

                        stablezactPayment = new CoinleyVanilla(sdkConfig);

                        // Make stablezactPayment globally accessible for Blocks integration
                        window.stablezactPayment = stablezactPayment;

                        return true;
                    } catch (error) {
                        this.showNotice('Payment system initialization failed.', 'error');
                        return false;
                    }
                } else if (attempts < maxAttempts) {
                    setTimeout(() => initWithRetry(attempts + 1, maxAttempts), 500);
                    return false;
                } else {
                    this.showNotice('Payment system not available. Please refresh the page.', 'error');
                    return false;
                }
            };

            initWithRetry();
        }

        bindEvents() {
            const self = this;

            // Close modal events
            this.closeBtn.on('click', function() {
                if (!$(this).prop('disabled')) {
                    self.closeModal();
                }
            });

            this.modalOverlay.on('click', function() {
                self.closeModal();
            });

            this.cancelBtns.on('click', function() {
                if (!$(this).prop('disabled')) {
                    self.closeModal();
                }
            });

            // Listen for form submission on checkout - with higher priority
            $(document.body).on('click', '#place_order', function(e) {
                const paymentMethod = $('input[name="payment_method"]:checked').val();
                
                if (paymentMethod === 'stablezact') {
                    e.preventDefault();
                    e.stopImmediatePropagation(); // Prevent other handlers from running
                    
                    
                    // Close any existing old modals
                    $('.coinley-modal').hide();
                    
                    self.populateOrderData();
                    self.processCheckout();
                    return false;
                }
            });
        }

        // Open the payment modal
        openModal() {
            this.modal.show();
            $('body').addClass('stablezact-modal-open');
        }

        // Close the payment modal
        closeModal() {
            this.modal.hide();
            $('body').removeClass('stablezact-modal-open');
        }

        // Show loading overlay
        showLoading() {
            this.loadingOverlay.show();
        }

        // Hide loading overlay
        hideLoading() {
            this.loadingOverlay.hide();
        }

        // Populate order data from the form
        populateOrderData() {
            const billingFirstName = $('#billing_first_name').val();
            const billingLastName = $('#billing_last_name').val();
            const billingEmail = $('#billing_email').val();
            
            // Use converted USD amount if available, otherwise use original
            const amount = stablezactParams.total ? parseFloat(stablezactParams.total) : 100.00;
            const currency = stablezactParams.currency || 'USD';
            
            orderData = {
                customerName: billingFirstName + ' ' + billingLastName,
                customerEmail: billingEmail,
                amount: amount,
                currency: currency,
                orderId: stablezactParams.orderId || 'temp-' + Date.now()
            };

        }

        // STABLEZACT VANILLA SDK PAYMENT PROCESSING
        async processCheckout() {
            try {
                if (!stablezactPayment) {
                    throw new Error(
                        "CoinleyVanilla payment gateway not initialized. Please refresh the page and try again."
                    );
                }

                // Show processing state
                this.showLoading();


                // Prepare payment configuration
                const paymentConfig = {
                    amount: orderData.amount,
                    customerEmail: orderData.customerEmail,
                    merchantName: stablezactParams.merchantName || "WooCommerce Store",
                    callbackUrl: stablezactParams.callbackUrl || `${window.location.origin}/wp-json/stablezact/v1/webhook`,
                    merchantWalletAddresses: merchantWallets,
                    preferredNetwork: 'ethereum', // Set default network to Ethereum
                    preferredCurrency: 'USDT', // Set default currency to USDT
                    metadata: {
                        orderId: orderData.orderId,
                        customerName: orderData.customerName,
                        customerEmail: orderData.customerEmail,
                        source: "woocommerce-plugin",
                    },
                };

                const callbacks = {
                    onSuccess: (paymentId, transactionHash, paymentDetails) => {
                        // SDK returns nested structure - extract actual values
                        let actualPaymentId = paymentId;
                        let actualTransactionHash = transactionHash;
                        let actualPaymentDetails = paymentDetails;

                        // Handle nested structure: SDK returns { paymentId, transactionHash, paymentDetails }
                        if (paymentId && typeof paymentId === 'object') {
                            // The entire response is in the first parameter
                            actualPaymentId = paymentId.paymentId || paymentId.id;
                            actualTransactionHash = paymentId.transactionHash; // ← FIX: Get from top level!
                            actualPaymentDetails = paymentId.paymentDetails || paymentId;
                        }

                        this.handlePaymentSuccess(
                            orderData.orderId,
                            actualPaymentId,
                            actualTransactionHash,
                            actualPaymentDetails
                        );
                    },
                    onError: (error) => {
                        this.handlePaymentError(error);
                    },
                    onClose: () => {
                        this.hideLoading();
                        this.closeModal();
                    },
                };

                // Open the CoinleyVanilla payment modal
                stablezactPayment.open(paymentConfig, callbacks);

            } catch (error) {
                this.hideLoading();
                this.showNotice(
                    error.message ||
                    "There was a problem processing your order. Please try again.",
                    'error'
                );
            }
        }

        // Handle successful payment
        async handlePaymentSuccess(orderId, paymentId, transactionHash, paymentDetails) {
            try {

                // Update WooCommerce order with payment details
                this.updateWooCommerceOrder(orderId, paymentId, transactionHash, paymentDetails);

                // Show success message
                this.showNotice('Payment completed successfully! Redirecting...', 'success');

                // Close the modal first
                this.closeModal();

                // For regular checkout, redirect to thank you page
                // For blocks checkout, trigger form submission
                if (window.location.pathname.includes('/checkout/')) {
                    // Regular checkout - redirect to order received page
                    setTimeout(() => {
                        this.returnToStore();
                    }, 1000);
                } else {
                    // This is handled by the Blocks callback system
                }

            } catch (error) {
                this.showNotice(
                    "Payment was received, but we had trouble updating your order. Please contact support with your transaction ID: " +
                    transactionHash,
                    'warning'
                );
                
                // Still try to redirect even if there was an error
                setTimeout(() => {
                    this.returnToStore();
                }, 2000);
            }
        }

        // Handle payment error
        handlePaymentError(error) {
            this.hideLoading();
            this.showNotice(`Payment failed: ${error}`, 'error');
        }

        // Update WooCommerce order with payment information
        updateWooCommerceOrder(orderId, paymentId, transactionHash, paymentDetails) {
            const data = {
                action: 'stablezact_update_order',
                order_id: orderId || orderData.orderId,
                payment_id: paymentId,
                transaction_hash: transactionHash,
                currency: paymentDetails?.currency || 'Unknown',
                network: paymentDetails?.network,
                amount: paymentDetails?.amount || orderData.amount,
                nonce: stablezactParams.nonce
            };
            
            
            $.post(stablezactParams.ajaxUrl, data)
                .done((response) => {
                })
                .fail((error) => {
                });
        }

        // Return to the order details page
        returnToStore() {
            const returnUrl = (stablezactParams && stablezactParams.orderReceivedUrl) 
                ? stablezactParams.orderReceivedUrl 
                : window.location.origin + '/checkout/order-received/';
            window.location.href = returnUrl;
        }


        // Show notice - simplified for CoinleyVanilla integration
        showNotice(message, type = 'info') {
            
            // Try WooCommerce notices first
            if (typeof wc_add_to_cart_params !== 'undefined' && $('.woocommerce-notices-wrapper').length) {
                $(document.body).trigger('wc_fragment_refresh');
                
                const noticeClass = type === 'error' ? 'woocommerce-error' : 
                                   type === 'warning' ? 'woocommerce-info' : 
                                   type === 'success' ? 'woocommerce-message' : 'woocommerce-info';
                
                $(`.${noticeClass}`).remove();
                $('.woocommerce-notices-wrapper').append(`<div class="${noticeClass}">${message}</div>`);
            } else {
                // Fallback to simple alert for critical messages
                if (type === 'error') {
                    alert(`Error: ${message}`);
                } else {
                }
            }
        }
    }

    // Set global flag immediately to prevent wallet connect initialization
    window.coinleyVanillaActive = true;

    // Global helper function for WooCommerce Blocks integration
    window.processStablezactCheckout = function(amount, customerEmail, resolve, emitResponse) {
        
        const stablezactPaymentInstance = window.stablezactPayment || stablezactPayment;
        
        if (!stablezactPaymentInstance) {
            resolve({
                type: emitResponse.responseTypes.ERROR,
                message: 'Payment system not ready. Please try again.'
            });
            return;
        }

        const paymentConfig = {
            amount: amount,
            customerEmail: customerEmail,
            merchantName: stablezactParams.merchantName || "WooCommerce Store",
            callbackUrl: stablezactParams.callbackUrl || `${window.location.origin}/wp-json/stablezact/v1/webhook`,
            merchantWalletAddresses: merchantWallets,
            preferredNetwork: 'ethereum', // Set default network to Ethereum
            preferredCurrency: 'USDT', // Set default currency to USDT
            metadata: {
                orderId: 'blocks_' + Date.now(),
                customerEmail: customerEmail,
                source: "woocommerce-blocks",
            },
        };

        const callbacks = {
            onSuccess: (paymentId, transactionHash, paymentDetails) => {

                // SDK returns nested structure - extract actual values
                let actualPaymentId = paymentId;
                let actualTransactionHash = transactionHash;
                let actualPaymentDetails = paymentDetails;

                // Handle nested structure: SDK returns { paymentId, transactionHash, paymentDetails }
                if (paymentId && typeof paymentId === 'object') {
                    // The entire response is in the first parameter
                    actualPaymentId = paymentId.paymentId || paymentId.id;
                    actualTransactionHash = paymentId.transactionHash; // ← FIX: Get from top level!
                    actualPaymentDetails = paymentId.paymentDetails || paymentId;
                }

                // Store payment data for order creation
                window.stablezactPaymentData = {
                    paymentId: actualPaymentId,
                    transactionHash: actualTransactionHash,
                    paymentDetails: actualPaymentDetails
                };

                const paymentMethodData = {
                    stablezact_transaction_hash: String(actualTransactionHash || ''),
                    stablezact_payment_id: String(actualPaymentId || ''),
                    stablezact_completed: 'true'
                };


                resolve({
                    type: emitResponse.responseTypes.SUCCESS,
                    meta: {
                        paymentMethodData: paymentMethodData
                    }
                });
            },
            onError: (error) => {
                resolve({
                    type: emitResponse.responseTypes.ERROR,
                    message: `Payment failed: ${error}`
                });
            },
            onClose: () => {
                resolve({
                    type: emitResponse.responseTypes.ERROR,
                    message: 'Payment cancelled'
                });
            },
        };

        // Open the CoinleyVanilla payment modal
        stablezactPaymentInstance.open(paymentConfig, callbacks);
    };

    // Initialize the payment modal on document ready
    $(document).ready(function() {
        new StablezactPaymentModal();
    });

})(jQuery); 