jQuery( document.body ).on( 'checkout_error', () => {
	requestAnimationFrame( () => {
		jQuery(
			'.woocommerce-error li[data-id], ' +
			'.wc-block-components-notice-banner[data-id], ' +
			'.wc-block-components-notice-banner li[data-id]'
		).each( function () {
			const $error = jQuery( this );
			const fieldId = $error.data( 'id' );

			if ( fieldId ) {
				const $field = jQuery( '#' + fieldId );
				const $row = jQuery( '#' + fieldId + '_field' );
				const descriptionId = fieldId + '_description';
				const message = $error.is( '.wc-block-components-notice-banner' )
					? $error.find( '.wc-block-components-notice-banner__content' ).text().trim()
					: $error.text().trim();

				$row
					.removeClass( 'woocommerce-validated' )
					.addClass( 'woocommerce-invalid' )
					.find( '.checkout-inline-error-message' )
					.remove();

				$field.attr( 'aria-invalid', 'true' )

				if ( message ) {
					$field.attr( 'aria-describedby', descriptionId );

					$row.append(
						jQuery( '<p>', {
							id: descriptionId,
							class: 'checkout-inline-error-message',
							text: message,
						} )
					);
				}
			}
		} );
	} );
} );
