/* JS extracted from Amazon Authorization View */
(function ($) {
	// Ensure ajaxurl is defined via localization
	const ajaxUrl        = momcs_auth.ajax_url;
	const authorizeNonce = momcs_auth.nonce_authorize;
	const callbackNonce  = momcs_auth.nonce_callback;

	/**
	 * Open a centered popup window.
	 *
	 * @param {string} url   URL to open.
	 * @param {string} title Window title.
	 * @param {number} w     Width in pixels.
	 * @param {number} h     Height in pixels.
	 * @returns {Window|null}
	 */
	function openCenteredPopup(url, title, w, h) {
		// Handle multi-monitor setups; these values account for browser chrome / monitor offset.
		const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
		const dualScreenTop  = window.screenTop  !== undefined ? window.screenTop  : screen.top;

		const width  = window.innerWidth  ? window.innerWidth  : document.documentElement.clientWidth  ? document.documentElement.clientWidth  : screen.width;
		const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;

		const left = ( ( width  / 2 ) - ( w / 2 ) ) + dualScreenLeft;
		const top  = ( ( height / 2 ) - ( h / 2 ) ) + dualScreenTop;

		const features = `scrollbars=yes,width=${w},height=${h},top=${top},left=${left}`;
		const newWindow = window.open( url, title, features );
		if ( newWindow && newWindow.focus ) {
			newWindow.focus();
		}
		return newWindow;
	}

	/**
	 * Extract the ISO country code from a label like "Canada (CA)" and
	 * return the flag-icons CSS class HTML. UK is mapped to GB.
	 */
	function flagHtml( label ) {
		var match = label.match( /\(([A-Z]{2})\)\s*$/ );
		if ( ! match ) {
			return '';
		}
		var code = match[1].toLowerCase();
		if ( code === 'uk' ) {
			code = 'gb';
		}
		return '<span class="fi fi-' + code + '"></span>';
	}

	/**
	 * Custom searchable region dropdown (matches product search pattern).
	 */
	var RegionDropdown = {
		$select: null,
		$wrapper: null,
		$input: null,
		$dropdown: null,
		options: [],
		selectedIndex: -1,
		isOpen: false,

		init: function () {
			this.$select = $( '#region' );
			if ( ! this.$select.length ) {
				return;
			}

			// Collect options from the original <select>.
			var self = this;
			this.$select.find( 'option' ).each( function () {
				var val = $( this ).val();
				if ( val ) {
					self.options.push( { value: val, label: $( this ).text() } );
				}
			} );

			// Hide the original <select>.
			this.$select.hide();

			// Build the custom UI after the hidden select.
			this.$wrapper = $(
				'<div class="momcs-region-search-wrapper">' +
					'<svg class="momcs-region-search-icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
						'<circle cx="11" cy="11" r="8"></circle>' +
						'<path d="m21 21-4.35-4.35"></path>' +
					'</svg>' +
					'<input type="text" class="momcs-region-search-input" placeholder="-- Select Region --" autocomplete="off">' +
					'<svg class="momcs-region-chevron" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
						'<polyline points="6 9 12 15 18 9"></polyline>' +
					'</svg>' +
					'<div class="momcs-region-search-dropdown"></div>' +
				'</div>'
			);
			this.$select.after( this.$wrapper );
			this.$input    = this.$wrapper.find( '.momcs-region-search-input' );
			this.$dropdown = this.$wrapper.find( '.momcs-region-search-dropdown' );

			this.bindEvents();
		},

		bindEvents: function () {
			var self = this;

			// Filter on input.
			this.$input.on( 'input', function () {
				self.filter( $( this ).val() );
				self.showDropdown();
			} );

			// Show dropdown on focus.
			this.$input.on( 'focus', function () {
				self.filter( $( this ).val() );
				self.showDropdown();
			} );

			// Keyboard navigation.
			this.$input.on( 'keydown', function ( e ) {
				self.handleKeydown( e );
			} );

			// Click outside to close.
			$( document ).on( 'click', function ( e ) {
				if ( ! $( e.target ).closest( '.momcs-region-search-wrapper' ).length ) {
					self.hideDropdown();
				}
			} );

			// Item click.
			this.$dropdown.on( 'click', '.momcs-region-result-item', function () {
				self.selectItem( $( this ).data( 'value' ), $( this ).text() );
			} );
		},

		filter: function ( query ) {
			var q    = query.toLowerCase();
			var html = '';
			var count = 0;

			for ( var i = 0; i < this.options.length; i++ ) {
				var opt  = this.options[ i ];
				var flag = flagHtml( opt.label );
				if ( ! q || opt.label.toLowerCase().indexOf( q ) !== -1 ) {
					html += '<div class="momcs-region-result-item' + ( count === 0 ? ' is-focused' : '' ) + '" data-value="' + opt.value + '" data-index="' + count + '">' +
						flag + ' ' + opt.label +
						'</div>';
					count++;
				}
			}

			if ( ! count ) {
				html = '<div class="momcs-region-no-results">No matching regions</div>';
			}

			this.$dropdown.html( html );
			this.selectedIndex = count > 0 ? 0 : -1;
		},

		selectItem: function ( value, label ) {
			this.$select.val( value ).trigger( 'change' );
			this.$input.val( label );
			// Show flag icon next to the input text.
			this.$wrapper.find( '.momcs-region-selected-flag' ).remove();
			var flag = flagHtml( label );
			if ( flag ) {
				this.$input.before( '<span class="momcs-region-selected-flag">' + flag + '</span>' );
			}
			this.hideDropdown();
			this.clearError();
		},

		showDropdown: function () {
			this.$dropdown.addClass( 'is-open' );
			this.isOpen = true;
		},

		hideDropdown: function () {
			this.$dropdown.removeClass( 'is-open' );
			this.isOpen = false;
			this.selectedIndex = -1;
		},

		handleKeydown: function ( e ) {
			var $items = this.$dropdown.find( '.momcs-region-result-item' );
			if ( ! $items.length ) {
				return;
			}

			if ( e.key === 'ArrowDown' ) {
				e.preventDefault();
				this.selectedIndex = Math.min( this.selectedIndex + 1, $items.length - 1 );
				this.highlightItem( $items );
			} else if ( e.key === 'ArrowUp' ) {
				e.preventDefault();
				this.selectedIndex = Math.max( this.selectedIndex - 1, 0 );
				this.highlightItem( $items );
			} else if ( e.key === 'Enter' ) {
				e.preventDefault();
				if ( this.selectedIndex >= 0 && this.isOpen ) {
					var $item = $items.eq( this.selectedIndex );
					this.selectItem( $item.data( 'value' ), $item.text() );
				}
			} else if ( e.key === 'Escape' ) {
				this.hideDropdown();
			}
		},

		highlightItem: function ( $items ) {
			$items.removeClass( 'is-focused' );
			var $current = $items.eq( this.selectedIndex ).addClass( 'is-focused' );
			// Scroll into view.
			if ( $current.length ) {
				$current[0].scrollIntoView( { block: 'nearest' } );
			}
		},

		clearError: function () {
			this.$select.removeClass( 'momcs-mapping-field-error' );
			this.$wrapper.removeClass( 'momcs-region-error' );
			$( '#region_error' ).hide();
		},

		showError: function () {
			this.$select.addClass( 'momcs-mapping-field-error' );
			this.$wrapper.addClass( 'momcs-region-error' );
		}
	};

	$(
		function () {
			// Initialize custom searchable region dropdown.
			RegionDropdown.init();

			// Button click handler
			$( '#momcs-auth-button' ).on(
				'click',
				function () {
					// Validate
					const connectionName = $( '#connection_name' ).val();
					const region         = $( '#region' ).val();
					clearAuthValidationErrors();
					let errors = [];
					if ( ! connectionName) {
						$( '#connection_name' ).addClass( 'momcs-mapping-field-error' );
						$( '#connection_name_error' ).text( momcs_auth.strings.connection_required ).show();
						errors.push( momcs_auth.strings.connection_required );
					}
					if ( ! region) {
						RegionDropdown.showError();
						$( '#region_error' ).text( momcs_auth.strings.region_required ).show();
						errors.push( momcs_auth.strings.region_required );
					}
					if (errors.length) {
						displayAuthValidationErrors( errors );
						return;
					}
					// Loader
					$( '.momcs-auth-button-container' ).hide();
					$( '#momcs-auth-loader' ).show();
					// Ajax authorize
					$.post(
						ajaxUrl,
						{
							action: 'momcs_sync_authorize',
							security: authorizeNonce,
							connection_name: connectionName,
							region: region
						},
						function (response) {
							if (response.success && response.data && response.data.auth_url) {
								const authWindow = openCenteredPopup( response.data.auth_url, 'Amazon Authorization', 800, 700 );
								let authorized   = false;
								// Listen for completion message
								function onMsg(ev){
									if (ev && ev.data && ev.data.type === 'momcs_authorized') {
										authorized = true;
										window.removeEventListener( 'message', onMsg );
										$( '#momcs-auth-loader' ).hide();
										$( '#momcs-auth-success' ).show();
										// Fire a custom event so other scripts can react if needed.
										$( document ).trigger( 'momcs_auth_success' );
										// Redirect to Sync Settings tab after a brief delay so user sees success.
										var uuid = ev.data.uuid || '';
										if ( uuid ) {
											var url = new URL( window.location.href );
											url.searchParams.delete( 'step' );
											url.searchParams.set( 'config_tab', 'sync' );
											url.searchParams.set( 'uuid', uuid );
											url.searchParams.set( 'action', 'edit' );
											setTimeout( function() {
												window.location.href = url.toString();
											}, 1500 );
										}
									}
								}
								window.addEventListener( 'message', onMsg );
								// Poll for popup closed; if closed without message, treat as cancelled
								const poll = setInterval(
									function () {
										if ( ! authWindow || authWindow.closed) {
											clearInterval( poll );
											if ( ! authorized) {
												// User closed early; reset UI
												$( '#momcs-auth-loader' ).hide();
												$( '.momcs-auth-button-container' ).show();
												// Optional: show notice
												if (window.toastr) {
													toastr.warning( momcs_auth.strings.authorization_cancelled || 'Authorization cancelled.' ); }
											}
										}
									},
									500
								);
							} else {
								alert( 'Error: ' + (response.data && response.data.message ? response.data.message : 'Unknown') );
								$( '#momcs-auth-loader' ).hide();
								$( '.momcs-auth-button-container' ).show();
							}
						}
					).fail(
						function (xhr,status,error) {
							console.error( 'AJAX error:', status, error );
							alert( 'Error: ' + error );
							$( '#momcs-auth-loader' ).hide();
							$( '.momcs-auth-button-container' ).show();
						}
					);
				}
			);

			// Remove error class on change.
			$( '#connection_name' ).on(
				'input',
				function () {
					$( this ).removeClass( 'momcs-mapping-field-error' );
					$( '#connection_name_error' ).hide();
				}
			);
			$( '#region' ).on(
				'change',
				function () {
					RegionDropdown.clearError();
				}
			);
		}
	);

	function displayAuthValidationErrors(errorsArray){
		let html = '<div class="momcs-mapping-validation-summary">';
		html    += '<span class="dashicons dashicons-warning"></span>';
		html    += momcs_auth.strings.fix_errors;
		html    += '<ul>';
		errorsArray.forEach(
			function (e) {
				html += '<li>' + e + '</li>'; }
		);
		html += '</ul></div>';
		$( '#momcs-auth-validation-container' ).html( html ).show()[0].scrollIntoView( {behavior:'smooth',block:'center'} );
	}
	function clearAuthValidationErrors(){
		$( '#connection_name_error, #region_error' ).hide();
		$( '#connection_name, #region' ).removeClass( 'momcs-mapping-field-error' );
		RegionDropdown.clearError();
		$( '#momcs-auth-validation-container' ).hide().empty();
	}

	// Removed simulated callback flow in favor of real broker popup
})( jQuery );
