(function($) {
    var autosaveDelay = 1000;
    var autosaveTimeout;
    // Static selectors for classic checkout
    var selectors = [
        '#billing_first_name', '#billing_address_1', '#billing_phone',
        '#billing_country', '#billing_state', '#billing_city', '#billing_email', '#billing_last_name'
    ];

    function autosave() {
        var formData = {
            action: 'autosave_order',
            _ajax_nonce: ads_ajax_data.nonce,
            billing_first_name: $(selectors[0]).val() || '',
            billing_address_1: $(selectors[1]).val() || '',
            billing_phone: $(selectors[2]).val() || '',
            billing_country: $(selectors[3]).val() || '',
            billing_state: $(selectors[4]).val() || '',
            billing_city: $(selectors[5]).val() || '',
            billing_email: $(selectors[6]).val() || '',
            billing_last_name: $(selectors[7]).val() || '',
        };
        console.log('Incomplete triggered', formData);
        // Validate phone
        if (!formData.billing_phone || formData.billing_phone.length < 11) {
            console.log('Phone invalid, autosave skipped');
            return;
        }
        $.post(ads_ajax_data.ajax_url, formData)
            .done(function(response) {
                if (response.success) {
                    console.log(response.data.message + '. Order ID:', response.data.order_id);
                } else {
                    console.warn('Incomplete failed:', response.data);
                }
            })
            .fail(function(jqXHR, textStatus, errorThrown) {
                console.error('Request failed:', textStatus, errorThrown);
            });
    }

    // Bind autosave to input/change events on all selectors
    var allSelectors = selectors.join(',');
    console.log(allSelectors);
    $(document).on('input change blur', allSelectors, function() {
        clearTimeout(autosaveTimeout);
        autosaveTimeout = setTimeout(autosave, autosaveDelay);
    });

    // WooCommerce events
    $(document.body).on(
        'added_to_cart removed_from_cart updated_cart_totals shipping_method_selected updated_shipping_method wc_fragments_refreshed',
        function() {
            setTimeout(autosave, autosaveDelay);
        }
    );

    // Run autosave on page load
    $(window).on('load', function() {
        setTimeout(autosave, autosaveDelay);
    });
})(jQuery);