jQuery(document).ready(function($) {
    const formSelector = '.' + Checkout.checkoutFormSelector,
        nonceSelector = '#' + Checkout.nonceSelector;

    const inputSelectors = {
        'first_name' : '.' + Checkout.firstNameSelector + ' input',
        'last_name'  : '.' + Checkout.lastNameSelector + ' input',
        'email'     : '.' + Checkout.emailSelector + ' input',
        // Billing address fields
        'billing_street' : '.' + Checkout.billingStreetSelector + ' input',
        'billing_city'   : '.' + Checkout.billingCitySelector + ' input',
        'billing_state'  : '.' + Checkout.billingStateSelector + ' input',
        'billing_postcode': '.' + Checkout.billingPostcodeSelector + ' input',
        'billing_country': '.' + Checkout.billingCountrySelector + ' select',
        // Shipping address fields
        'shipping_street' : '.' + Checkout.shippingStreetSelector + ' input',
        'shipping_city'   : '.' + Checkout.shippingCitySelector + ' input',
        'shipping_state'  : '.' + Checkout.shippingStateSelector + ' input',
        'shipping_postcode': '.' + Checkout.shippingPostcodeSelector + ' input',
        'shipping_country': '.' + Checkout.shippingCountrySelector + ' select'
    };

    let $form = $(formSelector),
        $nonce = $(nonceSelector),
        fieldSelectors = Object.values(inputSelectors).join(', '),
        $fields = $(fieldSelectors, $form);

    $fields.on('change', saveOrUpdateCartMeta);

    /**
     * Get the checkout form information and send it to our Ajax function
     *
     * @param {object} e
     */
    function saveOrUpdateCartMeta(e) {
        let formData = {
            action: Checkout.save_update_action,
            _ajax_nonce: $nonce.val()
        };

        // Loop through inputSelectors to dynamically add data to formData
        $.each(inputSelectors, function(key, selector) {
            formData[key] = $(selector, $form).val();
        });

        $.ajax({
            url: Checkout.ajaxurl,
            data: formData,
            type: 'POST',
            dataType: 'json',
        }).done(function(response) {
            console.log('Data saved/updated', response);
        }).fail(function(jqXHR, textStatus) {
            console.error('Failed to save/update data: ' + textStatus);
        });
    }
});

