(function ( $ ) {
	let swish_timout;
	function swish_payment_trigger() {
		$.ajax(
			{
				type : 'post',
				url : swishAjax.ajaxurl,
				dataType : 'json',
				data : {
					url: window.location.href,
					valid : swishAjax.nonce,
					action : 'swish_pay_status',
				},
				success : function ( response ) {
					if ( true === response.error ) {
						swish_timout = setTimeout( swish_payment_trigger, 700 );
					} else {
						if ('processing' === response.status || 'completed' === response.status) {
							window.location.replace( swishAjax.redirect_success );
						} else if ('cancelled' === response.status) {
							console.log( 'cancelled' );
							window.location.replace( swishAjax.redirect_cancelled );
						} else {
							console.log( 'unknown' );
							window.location.replace( swishAjax.redirect_cancel );
						}
					}
				}
			}
		);
	}

	function cancel_swish_payment() {
		$( '.mf-swish-pay__cancel' ).hide();
		$( '.mf-swish-pay__open-app' ).hide();

		$.ajax(
			{
				type: 'post',
				url: swishAjax.ajaxurl,
				dataType: 'json',
				data: {
					url: window.location.href,
					valid: swishAjax.nonce,
					action: 'swish_pay_cancel',
				},
				success: function (response) {
					if (true !== response.success) {
						$( '.moreflo-swish-error' ).show();
						console.log( response );
					} else {
						window.location.replace( swishAjax.redirect_cancelled );
					}

				}
			}
		);
	}

	$( document ).ready(
		function () {
			swish_payment_trigger();

			$( document ).on(
				'click',
				'.mf-swish-pay__cancel',
				function (e) {
					e.preventDefault();
					clearTimeout( swish_timout );
					cancel_swish_payment();
				}
			);
		}
	);
})( jQuery );
