jQuery(function($) {
    // Handle refresh exchange rates button
    $('#woocommerce_startbutton_refresh_exchange_rates').on('click', function(e) {
        e.preventDefault();
        
        var button = $(this);
        var originalText = button.text();
        
        // Disable button and show loading state
        button.prop('disabled', true).text('Refreshing...');
        // console.log(startbutton_admin);
        $.ajax({
            url: startbutton_admin.ajax_url,
            type: 'POST',
            data: {
                action: 'startbutton_refresh_exchange_rates',
                nonce: startbutton_admin.nonce
            },
            success: function(response) {
                if (response.success) {
                    // Reload the page to show updated rates
                    location.reload();
                } else {
                    console.log('response', response);
                    alert('Failed to update exchange rates: ' + response.data);
                    button.prop('disabled', false).text(originalText);
                }
            },
            error: function(error) {
                console.log('error.responseText', error.responseText);
                alert('Failed to update exchange rates. Please try again.');
                button.prop('disabled', false).text(originalText);
            }
        });
    });
    
    // Handle currency switcher enable/disable
    $('#woocommerce_startbutton_enable_currency_switcher').on('change', function() {
        var isEnabled = $(this).is(':checked');
        var currencyFields = $('.currency-switcher-field');
        if (isEnabled) {
            currencyFields.show();
        } else {
            currencyFields.hide();
        }
    });
    
    // Initialize visibility on page load
    $(document).ready(function() {
        var isEnabled = $('#woocommerce_startbutton_enable_currency_switcher').is(':checked');
        var currencyFields = $('.currency-switcher-field');
        
        if (!isEnabled) {
            currencyFields.hide();
        }
    });
}); 