/* global wpaymePayAdminTour, wpaymeAdminTourSettings */
jQuery( document ).ready( function( $ ) {
	// Initialize pointers with delay to ensure all elements are loaded
	setTimeout(function() {
		// Check if pointers are defined
		if (typeof wpaymePayAdminTour !== 'undefined' && wpaymePayAdminTour.pointers && wpaymePayAdminTour.pointers.length) {
			console.log('Wpayme Tour: Found ' + wpaymePayAdminTour.pointers.length + ' pointers to initialize');
			
			// Close any existing pointers first
			$('.wp-pointer').pointer('close');
			
			// Find each pointer element and open it
			$.each(wpaymePayAdminTour.pointers, function(index, pointer) {
				console.log('Wpayme Tour: Processing pointer ' + index + ' for selector: ' + pointer.selector);
				
				// Make sure the selector exists on the page
				var $target = $(pointer.selector);
				if ($target.length === 0) {
					console.log('Wpayme Tour: Pointer selector not found: ' + pointer.selector + ' - trying additional selectors');
					
					// Try some fallback selectors in this order
					var fallbackSelectors = [
						'#wpbody-content .wrap h1', 
						'#wpbody-content .wrap',
						'#wpbody-content',
						'#wpcontent',
						'body'
					];
					
					// Try each fallback selector
					for (var i = 0; i < fallbackSelectors.length; i++) {
						$target = $(fallbackSelectors[i]);
						if ($target.length > 0) {
							console.log('Wpayme Tour: Found fallback target using ' + fallbackSelectors[i]);
							break;
						}
					}
				} else {
					console.log('Wpayme Tour: Found target element for pointer');
				}
				
				// Define pointer options
				var options = $.extend(true, {}, pointer.options, {
					pointerClass: 'wp-pointer wp-wpayme-pointer',
					buttons: function() {
						return false;
					},
					close: function() {
						// Do nothing special on close
					}
				});
				
				// Initialize and open the pointer
				try {
					var $pointer = $target.first().pointer(options);
					$pointer.pointer('open');
					console.log('Wpayme Tour: Pointer opened successfully');
					
					// Position check - make sure it's visible in the viewport
					var $pointerElement = $('.wp-wpayme-pointer:visible');
					if ($pointerElement.length) {
						var pointerTop = $pointerElement.offset().top;
						var windowTop = $(window).scrollTop();
						var windowHeight = $(window).height();
						
						// If pointer is outside viewport, scroll to it
						if (pointerTop < windowTop || pointerTop > windowTop + windowHeight - 200) {
							$('html, body').animate({
								scrollTop: Math.max(0, pointerTop - 100)
							}, 300);
							console.log('Wpayme Tour: Scrolled to make pointer visible');
						}
					}
				} catch (e) {
					console.error('Wpayme Tour: Error opening pointer:', e);
				}
			});
		} else {
			console.log('Wpayme Tour: No pointers found or wpaymePayAdminTour is not defined');
		}
	}, 500); // Shorter delay for initial display

	// Add click handler for the Start Tour button
	$( document ).on( 'click', '.start-tour', function( e ) {
		e.preventDefault();
		
		// Get the full URL with nonce from the href attribute
		var startUrl = $(this).attr('href');
		
		// Ensure URL has the latest timestamp
		if (startUrl.indexOf('_ts=') !== -1) {
			startUrl = startUrl.replace(/(_ts=\d+)/, '_ts=' + new Date().getTime());
		} else {
			startUrl += (startUrl.indexOf('?') !== -1 ? '&' : '?') + '_ts=' + new Date().getTime();
		}
		
		// Log the action
		console.log('Wpayme Tour: Starting tour: ' + startUrl);
		
		// Navigate to the start URL
		window.location.href = startUrl;
		
		return false;
	} );

	// Navigation button handlers (Next, Previous, Close, Finish)
	$( document ).on( 'click', '.pp-pointer-button-next, .pp-pointer-button-prev, .pp-pointer-button-close, .pp-pointer-button-finish', function( e ) {
		e.preventDefault();
		
		// Get the URL from the button
		var url = $(this).attr('href');
		var buttonClass = $(this).attr('class');
		
		// Ensure URL has the latest timestamp
		if (url.indexOf('_ts=') !== -1) {
			url = url.replace(/(_ts=\d+)/, '_ts=' + new Date().getTime());
		} else {
			url += (url.indexOf('?') !== -1 ? '&' : '?') + '_ts=' + new Date().getTime();
		}
		
		// Log which button was clicked
		console.log('Wpayme Tour: Button clicked: ' + buttonClass);
		console.log('Wpayme Tour: Navigating to: ' + url);
		
		// Close any open pointers before navigation
		$('.wp-pointer').pointer('close');
		
		// Navigate to the URL
		window.location.href = url;
		
		return false;
	});
} );
