jQuery(
	function ($) {
		var debounceTimer;
		var lastSentData = {};

		function sendBillingData() {
			var data = {
				action: 'wac_capture_billing_fields'
			};
			var hasChanged = false;

			// Iterate over all input and select elements whose name starts with "billing_"
			$( 'input[name^="billing_"], select[name^="billing_"]' ).each(
				function () {
					var field = $( this ).attr( 'name' );
					var val   = $( this ).val();
					data[field] = val;

					if ( lastSentData[field] !== val ) {
						hasChanged = true;
					}
				}
			);

			// Only send request if at least one field's value has changed
			if ( hasChanged ) {
				// Cache current values
				lastSentData = Object.assign( {}, data );

				// Use $.post for REST API request
				$.post( wac_params.rest_url + '/capture-fields', data );
			}
		}

		// Attach blur and change event listeners to billing fields
		// Using 'blur' for immediate capture when a field loses focus
		// Using 'change' for select elements or when input values change
		$( 'body' ).on(
			'blur change',
			'input[name^="billing_"], select[name^="billing_"]',
			function () {
				clearTimeout( debounceTimer );
				debounceTimer = setTimeout( sendBillingData, 500 ); // Debounce to prevent excessive AJAX calls
			}
		);
	}
);
