; ( function ( document, $ ) {
	'use strict';

	const euCountries = edd_global_vars.edd_eu_countries;

	$( document.body ).on( 'edd_gateway_loaded', function ( e, gateway ) {
		toggleVatWrap();
	} );

	function toggleVatWrap () {
		const VATContainer = $( '#edd-card-vat-wrap' );
		if ( !VATContainer.length ) {
			return;
		}

		$( '#billing_country' ).on( 'change', toggleVatWrap );

		const isInArray = euCountries.includes( $( '#billing_country' ).val() );
		if ( isInArray ) {
			VATContainer.show();
		} else {
			VATContainer.hide();
			hideResult();
		}
	}

	// Get the checkout form element.
	const checkoutUpdatedCartElement = edd_global_vars.checkout_updated_cart_selector;
	const checkoutFormElement = edd_global_vars.checkout_form_selector;

	function hideResult () {
		$( '#edd-vat-check-result' ).remove();
	}

	function showError ( $el, message ) {
		$el.append( '<div id="edd-vat-check-result" class="edd_errors edd-alert edd-alert-error"><p class="edd_error">' + message + '</p></div>' );
	}

	const eddVatCheck = function ( event ) {
		const $vatField = $( '#edd-card-vat-wrap' ),
			billingCountry = $( '#billing_country' ).val(),
			vatInput = $( '#edd-vat-number' ),
			vatNumber = vatInput.val(),
			button = $( '#edd-vat-check-button' );

		if ( ! $vatField.length ) {
			return false;
		}

		if ( $vatField.data( 'check' ) ) {
			return false;
		}

		hideResult();

		if ( ! vatNumber ) {
			showError( $vatField, edd_global_vars.messages.vat_number_missing );
			return false;
		}

		if ( ! billingCountry ) {
			showError( $vatField, edd_global_vars.messages.country_missing );
			return false;
		}

		vatInput.prop( 'disabled', true );
		button.prop( 'disabled', true );

		// create a span with classes edd-loading and edd-loading-ajax and insert it before the button
		const loadingSpan = document.createElement( 'span' );
		loadingSpan.classList.add( 'edd-loading', 'edd-loading-ajax' );
		button.before( loadingSpan );

		const postData = {
			action: 'edd_vat_check',
			billing_country: billingCountry,
			vat_number: vatNumber,
			nonce: $( '#edd-checkout-address-fields-nonce' ).val(),
			current_page: edd_global_vars.current_page,
		};

		$vatField.data( 'check', true );

		$( document.body ).trigger( 'edd_eu_vat:before_vat_check', postData );

		$.ajax( {
			type: 'POST',
			data: postData,
			dataType: 'json',
			url: edd_global_vars.ajaxurl,
			xhrFields: {
				withCredentials: true
			}
		} )
			.done( function ( response, textStatus, jqXHR ) {
				if ( jqXHR.status == 200 && typeof response.html !== 'undefined' ) {
					let $updatedCart = $( $.parseHTML( response.html.trim() ) ).filter( checkoutUpdatedCartElement );

					// Update cart.
					if ( $updatedCart.length ) {
						$( checkoutFormElement ).replaceWith( $updatedCart );
					}

					// Update totals.
					$( '.edd_cart_amount' ).html( response.total );

					// Add VAT result message.
					$vatField.append( response.vat_check_result );

					// Create tax data (in same format as EDD) and trigger edd_taxes_recalulcated to ensure everything is up to date.
					const taxData = {
						postdata: postData,
						response: response
					};

					$( document.body )
						.trigger( 'edd_taxes_recalculated', taxData )
						.trigger( 'edd_eu_vat:vat_check', response );
				} else {
					showError( $vatField, edd_global_vars.messages.ajax_error );
				}
			} )
			.fail( function ( jqXHR, textStatus, errorThrown ) {
				showError( $vatField, edd_global_vars.messages.ajax_error );
			} )
			.always( function () {
				button.prop( 'disabled', false );
				vatInput.prop( 'disabled', false );
				$vatField.data( 'check', false );
				loadingSpan.remove();

				$( document.body ).trigger( 'edd_eu_vat:vat_check_complete' );
			} );

		return false;
	};

	$( function () {
		// Bind events for purchase form.
		$( '#edd_purchase_form' )
			.on( 'click', '#edd-vat-check-button', eddVatCheck )
			.on( 'change', '#billing_country', function ( event ) {
				const vatData = $( '#edd-vat-check-result' ).data();

				// Clear previous VAT number and result if country is changed.
				if ( vatData?.valid && vatData?.country !== $( this ).val() ) {
					$( '#edd-vat-number' ).val( '' );
					hideResult();
				}

				toggleVatWrap();
			} )
			.on( 'change', '#edd-stripe-update-billing-address', function ( event ) {
				// Prevent EDD Stripe hiding the VAT field when toggling the billing fields for saved addresses.
				toggleVatWrap();
			} )
			.on( 'change', '#edd-vat-show-fields', function ( event ) {
				// Toggle VAT fields visibility based on checkbox state.
				const isChecked = $( this ).is( ':checked' );
				const $fieldsWrap = $( '#edd-vat-fields-wrap' );
				const $vatInput = $( '#edd-vat-number' );

				if ( isChecked ) {
					$fieldsWrap.slideDown( 200 );
				} else {
					$fieldsWrap.slideUp( 200 );
					// Clear VAT number and result when unchecking.
					$vatInput.val( '' );
					hideResult();
				}

				// Update button state based on input value.
				updateVatButtonState();
			} )
			.on( 'input', '#edd-vat-number', function ( event ) {
				// Enable/disable button based on input value.
				updateVatButtonState();
			} );

		// Initialize button state on page load.
		updateVatButtonState();
	} );

	/**
	 * Update the VAT validation button state based on input value.
	 */
	function updateVatButtonState() {
		const $button = $( '#edd-vat-check-button' );
		const $input = $( '#edd-vat-number' );
		const hasValue = $input.val().trim().length > 0;

		$button.prop( 'disabled', ! hasValue );
	}

	/**
	 * Remove the Recurring notices when taxes are recalculated.
	 * At this time, they do not respond to tax recalculation.
	 */
	function removeRecurringNotices ( data ) {
		if ( data.postdata.current_tax_amount !== data.response.tax_raw ) {
			$( '#edd-recurring-sl-auto-renew' ).each( function () {
				$( this ).remove();
			} );

			$( '#edd-recurring-sl-cancel-replace' ).each( function () {
				$( this ).remove();
			} );
		}
	}

	// $( document.body )
	// 	.on( 'edd_gateway_loaded', function ( e, gateway ) {
	// 		// Trigger EU country check when payment gateway loaded.
	// 		toggleVatWrap();

	// 		// Also check EU country when 'Add new' card option selected in EDD Stripe.
	// 		$( '#edd-stripe-add-new' ).on( 'change', function ( e ) {
	// 			toggleVatWrap();
	// 		} );
	// 	} );

	// Disable the purchase button while we wait for tax recalculation.
	$( function () {
		// Bind events for purchase form.
		$( '#edd_purchase_form' )
			.on( 'change', '#billing_country', function ( event ) {
				$( '#edd-purchase-button, #billing_country' ).prop( 'disabled', true )
			} )
	} );

	// Update the data-total attribute.
	$( document.body ).on( "edd_taxes_recalculated", function ( event, data ) {
		const cartAmount = $( '.edd_cart_amount' );
		const rawTax = data?.response?.total_raw

		if ( rawTax !== undefined ) {
			cartAmount.attr( 'data-total', rawTax )
		}

		$( '#edd-purchase-button, #billing_country' ).prop( 'disabled', false );
		removeRecurringNotices( data);
	} );

	return {
		checkVatNumber: eddVatCheck,
		checkCountry: toggleVatWrap
	};
} )( document, jQuery );
