jQuery( function( $ ) {
    wcStartbuttonFormHandler();
    $('#startbutton-payment-button').on('click', function(event) {
        event.preventDefault();
        window.location.reload();
        // wcStartbuttonFormHandler();
    });

	function wcStartbuttonFormHandler() {
        let amount = Number( wc_startbutton_params.amount );
        let currency = wc_startbutton_params.currency;
        // Check if we're in development environment (localhost)
        // const isDevelopment = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
        console.log('url', location.origin + '/wc-api/WC_Startbutton_Webhook');
        console.log('wc_startbutton_params.env', wc_startbutton_params.env);
        // Configuration for development environment
        const config = {
            phone: wc_startbutton_params.telephone,
            key: wc_startbutton_params.key,
            amount,
            channels: [],
            webhookUrl: location.origin + '/wc-api/WC_Startbutton_Webhook',
            env: wc_startbutton_params.env,
            currency: currency,
            email: wc_startbutton_params.email,
            metadata: {
                ...wc_startbutton_params,
                source: 'wordpress',
            },
            ignoreRedirect: true,
            // reference: wc_startbutton_params.order_id + '_' + Date.now(),            
        };
        
        // Add development-specific configuration
        // if (isDevelopment) {
        //     console.log('Running in development mode - CORS proxy may be needed');
        //     // You can add development-specific overrides here if needed
        // }
        
        new Promise((resolve, reject) => {
            SBInit({
                ...config,
                success: (res) => {
                    console.log('success');
                    
                    // Store payment data for redirect in finally()
                    window.startbuttonPaymentData = {
                        order_id: wc_startbutton_params.order_id,
                        tx_ref: res.reference,
                        tx_id: res.transaction,
                        nonce: wc_startbutton_params.nonce
                    };
                    
                    console.log('res', res);
                    resolve(res);
                },
                close: (res) => {
                    console.log('closed');
                    console.log('close res', res);
                    resolve();
                },
                error: (res) => {
                    console.log('error res', res);
                    alert(res.error.message);
                    reject(res);
                }
            });
        })
        .finally(() => {
            $('#startbutton-payment-button').removeClass('disabled');
            $('#startbutton-cancel-payment-button').removeClass('disabled');
            
            // Handle redirect in finally() - this will execute regardless of success/error
            if (window.startbuttonPaymentData) {
                const { order_id, tx_ref, tx_id, nonce } = window.startbuttonPaymentData;
                console.log('resolved...', {order_id, tx_ref, tx_id, nonce});
                // Try form submission first
                // try {
                //     $form = $( '#order_review' );
                //     $form.append( '<input type="hidden" name="order_id" value="' + order_id + '"/>' );
                //     $form.append( '<input type="hidden" name="startbutton_tx_ref" value="' + tx_ref + '"/>' );
                //     $form.append( '<input type="hidden" name="startbutton_tx_id" value="' + tx_id + '"/>' );
                //     $form.append( '<input type="hidden" name="startbutton_nonce" value="' + nonce + '"/>' ); 
                    
                //     $form.submit();
                //     console.log('Form submitted successfully');
                // } catch (formError) {
                //     console.log('Form submission failed, attempting direct redirect:', formError);
                // Fallback to direct URL redirect
                const redirectUrl = wc_startbutton_params.api_url + '?' + new URLSearchParams({
                    order_id: order_id,
                    startbutton_tx_ref: tx_ref,
                    startbutton_tx_id: tx_id,
                    startbutton_nonce: nonce
                }).toString();
                
                console.log('Redirecting to:', redirectUrl);
                window.location.href = redirectUrl;
                // }
                
                // Clear the stored data
                delete window.startbuttonPaymentData;
            }
        });  
	}

});

