var wpwlOptions = {
    paymentTarget: 'tpApplePayifrm',
    shopperResultTarget: 'tpApplePayifrm',
    onError: function(error){
        console.log('error::' + error);
    }
};

(function(tpap, $){
    var termsChecked = false;
    var isFastCheckout = true;
    var isToCCheckboxActive = false;
    var termCheckboxValidationText = 'Please tick and conditions checkbox to proceed';
    var isProcessing = false;
    var requestQueue = [];
    var formData = {};
    var processingRequests = new Map();
    
    // FIXED: Reduced debounce time and improved logic
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
    
    // FIXED: Less aggressive throttling
    function throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            } else {
                // FIXED: Don't completely block, just log
                console.log('Apple Pay: Request throttled, will retry shortly');
            }
        }
    }
    
    // FIXED: Enhanced request ID with better uniqueness
    function generateRequestId() {
        return 'applepay_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9) + '_' + performance.now();
    }
    
    function communicateWithParentWindow( e ){
        if( e.detail.hasOwnProperty( 'funcs' ) ){
            for ( var i = 0, len = e.detail.funcs.length; i < len; i++ ) {
                try{
                    let tempfunc = eval( e.detail.funcs[ i ].name );
                    tempfunc(e.detail.funcs[i].args);
                }catch( err ){
                    console.log( err );
                }
            }
        }
    }

    function postMessageToParent(obj){
        if(typeof window.CustomEvent === "function") {
            var event = new CustomEvent('parentApplePayLogV52', {detail:obj});
        } else {
            var event = document.createEvent('Event');
            event.initEvent('parentApplePayLogV52', true, true);
            event.detail = obj;
        }
        window.parent.document.dispatchEvent(event);
    }

    function setScreenSizeClass( args ){
        let topScreenWidth = args[0];
        if( topScreenWidth >= 768 ){
            $('body').addClass('tpapplepay-bigscreen');
        }else{
            $('body').removeClass('tpapplepay-bigscreen');
        }
    }

    function validateTermsCheckbox( args ){
        termsChecked = args[0];
    }

    function getFormData( args ){
        formData = args[0];
    }
    
    function drawFormElementToPage(brands){
        console.log('drawing form.paymentWidgets applepay element! =>' + brands);
        jQuery('#cnpf').html(`
            <div class="tp-applepay-init-loader">
                <form action="${tpconf.formpayurl}" class="paymentWidgets" data-brands="${brands}"></form>
            </div>
        `);
    }
    
    // FIXED: Enhanced checkout response with better error handling and cache management
    var getCheckoutResponse = function() {
        return new Promise(function(resolve, reject) {
            var retryCount = 0;
            var maxRetries = 2; // Reduced retries to avoid delays
            
            function makeRequest() {
                var requestId = generateRequestId();
                
                // FIXED: Less aggressive duplicate checking
                if (processingRequests.has('checkout')) {
                    var existingRequestTime = processingRequests.get('checkout_time') || 0;
                    if (Date.now() - existingRequestTime < 2000) { // Only wait 2 seconds
                        console.log('Recent checkout request in progress, waiting...');
                        setTimeout(() => makeRequest(), 500);
                        return;
                    } else {
                        // Clear stale request
                        processingRequests.delete('checkout');
                        processingRequests.delete('checkout_time');
                    }
                }
                
                processingRequests.set('checkout', requestId);
                processingRequests.set('checkout_time', Date.now());
                
                // FIXED: Add cache busting parameter
                var cacheParam = '&_cb=' + Date.now() + Math.random();
                
                fetch(tpconf.ajaxurl + '?action=tp_applepay_checkout_response&order_id=' + tpAppOrderID + cacheParam, {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json',
                        'X-Request-ID': requestId,
                        'Cache-Control': 'no-cache, no-store, must-revalidate',
                        'Pragma': 'no-cache'
                    },
                    body: JSON.stringify({
                        timestamp: Date.now(),
                        force_refresh: retryCount > 0
                    })
                })
                .then(function(response){
                    if (!response.ok) {
                        throw new Error('Network response was not ok: ' + response.status);
                    }
                    return response.json();
                })
                .then(function(json){
                    console.log('applepay init success');
                    console.log(json.data);
                    isToCCheckboxActive = json.data.termAndConditionCheckbox;
                    termCheckboxValidationText = json.data.termAndConditionValidationText;
                    processingRequests.delete('checkout');
                    processingRequests.delete('checkout_time');
                    resolve(json.data);
                })
                .catch(function(error) {
                    processingRequests.delete('checkout');
                    processingRequests.delete('checkout_time');
                    retryCount++;
                    
                    if (retryCount < maxRetries) {
                        console.log('Retrying checkout request... Attempt ' + retryCount);
                        setTimeout(() => makeRequest(), 500 * retryCount); // Shorter retry delay
                    } else {
                        console.error('Max retries reached for checkout request:', error);
                        reject(error);
                    }
                });
            }
            
            makeRequest();
        });
    };
    
    // FIXED: Enhanced payment processing with better duplicate prevention
    var processResponseToCreateOrder = async function(payment) {
        var requestId = generateRequestId();
        postMessageToParent({funcs:[{"name":"sendFormData","args":['getFormData']}]});
        // FIXED: More granular processing check
        var processingKey = 'payment_' + tpAppOrderID + '_' + tpAppOPPWCheckoutID;
        if (processingRequests.has(processingKey)) {
            var processingTime = processingRequests.get(processingKey + '_time') || 0;
            if (Date.now() - processingTime < 5000) { // Only block for 5 seconds
                console.log('Payment already being processed for this order/checkout');
                return {
                    status: 'FAILURE', 
                    errors: [{
                        code: 'processing', 
                        message: 'Payment is already being processed. Please wait.'
                    }]
                };
            } else {
                // Clear stale processing state
                processingRequests.delete(processingKey);
                processingRequests.delete(processingKey + '_time');
            }
        }
        
        processingRequests.set(processingKey, true);
        processingRequests.set(processingKey + '_time', Date.now());
        
        // Add visual feedback
        postMessageToParent({
            funcs: [{
                name: "showProcessingIndicator",
                args: [true]
            }]
        });
        
        try {
            var response = await fetch('/?wc-ajax=onPaymentAuthorized&order_id=' + tpAppOrderID, {
                method: 'POST',
                credentials: 'include',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                    'X-Request-ID': requestId,
                    'X-Payment-Session': tpap_session_id,
                    'Cache-Control': 'no-cache'
                },
                body: JSON.stringify({
                    'payment': payment, 
                    'checkout_id': tpAppOPPWCheckoutID, 
                    'session_id': tpap_session_id,
                    'timestamp': Date.now(),
                    'request_id': requestId,
                    'form_data': formData
                })
            });
            
            if (!response.ok) {
                throw new Error('Network response was not ok: ' + response.status);
            }
            
            var data = await response.json();
            console.log('Payment response:', data);
            
            return data;
            
        } catch (error) {
            console.error('Payment processing error:', error);
            return {
                status: 'FAILURE',
                errors: [{
                    code: 'network_error',
                    message: 'Network error occurred. Please check your connection and try again.'
                }]
            };
        } finally {
            // Clean up processing state
            processingRequests.delete(processingKey);
            processingRequests.delete(processingKey + '_time');
            
            // Remove visual feedback
            postMessageToParent({
                funcs: [{
                    name: "showProcessingIndicator",
                    args: [false]
                }]
            });
        }
    }
    
    // FIXED: Reduced debounce time and better error handling
    var drawOppwaScriptToPage = debounce(function() {
        console.log('Starting Apple Pay widget initialization...');
        
        var promise = getCheckoutResponse();
        promise.then(function (response){
            if (response && response.checkout_id) {
                renderTpGatewayWidget(response);
            } else {
                throw new Error('Invalid checkout response received');
            }
        }).catch((error) => {
            console.error('Failed to get checkout response:', error);
            postMessageToParent({
                funcs: [{
                    name: "showError",
                    args: ['Failed to initialize payment. Please refresh and try again.']
                }]
            });
        });
    }, 150); // FIXED: Reduced from 300ms to 150ms
    
    function renderTpGatewayWidget(result){
        var responseResult = result;
        
        // FIXED: Enhanced validation
        if (!result || !result.checkout_id || !result.platformBase) {
            console.error('Invalid checkout response:', result);
            postMessageToParent({
                funcs: [{
                    name: "showError",
                    args: ['Invalid payment configuration. Please refresh and try again.']
                }]
            });
            return;
        }
        tpAppOrderID = result.order_id;
        let applePay = {
            displayName: result.displayName,
            style: "black",
            currencyCode: result.currencyCode,
            submitOnPaymentAuthorized: [ "customer" ],
            checkAvailability: "canMakePayments",
            merchantCapabilities: result.merchantCapabilities,
            total: result.total,
            onCancel: function () {
                console.log('Payment cancelled by user');
                // FIXED: Clear processing state on cancel
                processingRequests.clear();
                isProcessing = false;
            },
            requiredShippingContactFields: result.requiredShippingContactFields,
            requiredBillingContactFields: result.requiredBillingContactFields,
            onPaymentAuthorized: async function(payment){
                console.log('Apple Pay payment authorized, processing...');
                
                // FIXED: Add timestamp to payment data
                payment.timestamp = Date.now();
                payment.checkout_id = tpAppOPPWCheckoutID;
                
                var response = await processResponseToCreateOrder(payment);
                
                if( response.hasOwnProperty('result') && response.result == 'success' ){
                    return {
                        status: 'SUCCESS'
                    };
                }

                if( response.hasOwnProperty('result') && response.result == 'failure' ){
                    let messages = response.messages || "Unknown Error";
                    postMessageToParent({
                        funcs:[
                            {
                                "name": "showSwalMessages",
                                "args": [
                                    messages
                                ]
                            }
                        ]
                    });
                }

                return {
                    status: 'FAILURE',
                    errors: response.data.errors || [{
                        code: 'unknown_error',
                        message: 'Payment failed. Please try again.'
                    }]
                };
            }
        };
    
        wpwlOptions.applePay = applePay;
        
        wpwlOptions.createCheckout = function() {
            console.log('Creating Apple Pay checkout...');
            if( termsChecked == false && isToCCheckboxActive == true ){
                alert(termCheckboxValidationText);
                return null;
            }
            return responseResult.checkout_id;
        };
    
        let platform_base = result.platformBase;
        let checkout_id = result.checkout_id;
        tpAppOPPWCheckoutID = checkout_id;
        
        let scriptURL = "https://" + platform_base + "/v1/paymentWidgets.js?checkoutId=" + checkout_id;
        if( isFastCheckout ){
            scriptURL = "https://" + platform_base + "/v1/paymentWidgets.js";
        }
        console.log('Loading payment widget: ' + scriptURL);
        
        // FIXED: Better script cleanup and loading
        var existingScript = document.querySelector('script[src*="paymentWidgets.js"]');
        if (existingScript) {
            existingScript.remove();
            console.log('Removed existing payment widget script');
        }
        
        let scriptElement = document.createElement( "script" );
        scriptElement.onload = function() {
            $('#mcif').hide();
            console.log('Payment widget loaded successfully');
        };
        scriptElement.onerror = function() {
            console.error('Failed to load payment widget from:', scriptURL);
            postMessageToParent({
                funcs: [{
                    name: "showError",
                    args: ['Failed to load payment system. Please refresh and try again.']
                }]
            });
        };
        scriptElement.src = scriptURL;
        document.body.appendChild( scriptElement );
    }
    
    // FIXED: Enhanced initialization with better error handling
    tpap.initialiseCnp = function(){
        try {
            console.log('Initializing Apple Pay CNP...');
            
            window.document.addEventListener('appleFrameLogV52', communicateWithParentWindow, false);
            postMessageToParent({funcs:[{"name":"tpApplepayInitWindowReady","args":['ready']}]});
           
            postMessageToParent({funcs:[{"name":"sendFormData","args":['getFormData']}]});

            // FIXED: Clean up any previous state more thoroughly
            isProcessing = false;
            processingRequests.clear();
            
            drawFormElementToPage('APPLEPAY');
            drawOppwaScriptToPage();
            
        } catch (error) {
            console.error('Failed to initialize Apple Pay:', error);
            postMessageToParent({
                funcs: [{
                    name: "showError",
                    args: ['Failed to initialize Apple Pay. Please refresh and try again.']
                }]
            });
        }
    }

})(window.tpap = window.tpap || {}, jQuery);

// FIXED: Enhanced document ready with retry mechanism
jQuery(function($) {
    console.log('Document ready, initializing Apple Pay...');
    
    // FIXED: Add a small delay to ensure everything is properly loaded
    setTimeout(function() {
        window.tpap.initialiseCnp();
    }, 100);
});

// FIXED: Enhanced visibility change handling
document.addEventListener('visibilitychange', function() {
    if (!document.hidden) {
        console.log('Page became visible, checking Apple Pay state...');
        // Clear any stale processing states when page becomes visible again
        if (window.tpap && window.tpap.processingRequests) {
            window.tpap.processingRequests.clear();
        }
    }
});
