/**
 * This file is responsible for the waiting room screen.
 */

/* global northmill_bnpl_waiting_screen */
jQuery( document ).ready(
	function ($) {
		const order_key           = new URLSearchParams( window.location.search ).get( 'order_key' );
		const ajax_url            = northmill_bnpl_waiting_screen.ajax_url;
		const cancel_url          = northmill_bnpl_waiting_screen.cancel_url;
		const order_received_url  = northmill_bnpl_waiting_screen.order_received_url;
		const nonce               = northmill_bnpl_waiting_screen.nonce;
		let failed_attempts_count = 0;
		const max_attempts        = 20; // Maximum number of attempts.
		const retry_delay         = 2000; // Delay in milliseconds between each attempt. TODO: Maybe increase?
		let transaction_check     = null;

		const $cancel_buttons = $( '.cancel-transaction-button' );

		let not_started_triggered = false;
		let started_triggered     = false;

		function checkTransactionStatus( reset_failed_attempts_count ) {
			if ( reset_failed_attempts_count === true ) {
				failed_attempts_count = 0;
			}

			if ( failed_attempts_count >= max_attempts ) {
				console.error( "Maximum attempts reached. Stopping status checks." );
				return;
			}

			$.ajax(
				{
					url: ajax_url,
					type: 'POST',
					dataType: 'json',
					data: {
						action: 'northmill_bnpl_transaction_check',
						order_key: order_key,
						_ajax_nonce: nonce
					},
					success: function (response) {
						let status   = 'unknown';
						let bnpl_url = '';
						if ( response.success === true ) {
							status = response.data.status;
						}

						switch (status) {
							case 'not_started':
								if ( ! not_started_triggered ) {
									not_started_triggered = true;
								}
								transaction_check = setTimeout( checkTransactionStatus, retry_delay, true );
								break;
							case 'started':
								if ( ! started_triggered ) {
									started_triggered = true;
									// Desktop.
									$( '#desktop-qr-code-section' ).hide();
									$( '#desktop-waiting-section' ).show();

									// Mobile.
									$( '#bnpl-link' ).hide();
									$( '#mobile-spinner' ).show();
								}
								transaction_check = setTimeout( checkTransactionStatus, retry_delay, true );
								break;
							case 'completed':
								$cancel_buttons.remove();
								window.location.href = order_received_url;
								break;
							case 'cancelled':
								$cancel_buttons.remove();
								window.location.href = cancel_url;
								break;
							case 'unknown':
							default:
								// Retry after a delay.
								transaction_check = setTimeout( checkTransactionStatus, retry_delay, false );
								failed_attempts_count++;
								break;
						}
					},
					error: function () {
						// Retry after a delay on error.
						transaction_check = setTimeout( checkTransactionStatus, retry_delay, false );
						failed_attempts_count++;
					}
				}
			);
		}

		// Initial call to start the loop.
		checkTransactionStatus( true );

		$cancel_buttons.on(
			'click',
			function ( event ) {
				event.preventDefault();

				// Desktop.
				$( '#desktop-qr-code-section' ).hide();
				$( '#desktop-waiting-section' ).hide();
				$( '#desktop-cancelling-section' ).show();

				// Mobile.
				$( '#mobile-link-section' ).hide();
				$( '#mobile-cancelling-section' ).show();

				// Clear the transaction check loop.
				clearTimeout( transaction_check );

				$.ajax(
					{
						url: ajax_url,
						type: 'POST',
						data: {
							action: 'northmill_bnpl_transaction_cancel',
							order_key: order_key,
							_ajax_nonce: nonce
						},
						complete: function () {
							window.location.href = cancel_url;
						}
					}
				);
			}
		);
	}
);
