jQuery(function($){
    $(document).on('click', '.show-instruction', function(){
        $('.global-paypal-instruction').slideToggle();
        $(this).text(function(i, text){
            return text === 'Show Instruction' ? 'Hide Instruction' : 'Show Instruction';
        });
    });

    $(document).on('click', '.formipay-connect-paypal', function(e) {
        e.preventDefault();
        
        $.ajax({
            url: formipay_admin_setting.ajax_url,
            type: 'POST',
            data: {
                action: 'formipay_oneclick_connect',
                nonce: formipay_admin_setting.nonce
            },
            beforeSend: function() {
                $('#connect-status').html('<div class="notice notice-info"><p>Initiating PayPal connection...</p></div>');
            },
            success: function(response) {
                if (response.success) {
                    // Open PayPal auth in popup
                    const popup = window.open(
                        response.data.auth_url, 
                        'paypal_oauth',
                        'width=600,height=700,scrollbars=yes'
                    );
                    
                    // Listen for message from popup
                    window.addEventListener('message', function(event) {
                        if (event.data.type === 'formipay-paypal-connect') {
                            if (event.data.success) {
                                $('#connect-status').html(`
                                    <div class="notice notice-success">
                                        <p>${event.data.message}</p>
                                        <p>Webhook ID: ${event.data.webhook_id}</p>
                                    </div>
                                `);
                            } else {
                                $('#connect-status').html(`
                                    <div class="notice notice-error">
                                        <p>${event.data.message}</p>
                                    </div>
                                `);
                            }
                        }
                    });
                } else {
                    $('#connect-status').html(`
                        <div class="notice notice-error">
                            <p>Connection failed: ${response.data}</p>
                        </div>
                    `);
                }
            },
            error: function() {
                $('#connect-status').html(`
                    <div class="notice notice-error">
                        <p>Connection failed: Server error</p>
                    </div>
                `);
            }
        });
    });    
    
});