(
	function ( $ ) {
		$( document ).ready(
			function () {
				$( '.algolia_post_index' ).on(
					'click',
					function () {
						let post_ID         = $( '.algolia-post-index' ).val();
						let algolia_message = $( '.algolia-message' );
						$.ajax(
							{
								type: 'POST',
								url: wlc_algolia.ajax_url,
								data: {
									action: 'wlc_algolia_handle_post_index',
									post_id: post_ID,
									algolia_nonce: wlc_algolia.nonce,
								},
								beforeSend: function () {
									algolia_message.text( '' );
								},
								success: function ( response ) {
									if ( '' !== response.data.message ) {
										algolia_message.text( response.data.message );
									}
								},
								error: function ( xhr, status, error ) {
									console.error( 'AJAX request failed with status: ' + status + ', error: ' + error );
								}
							}
						);
					}
				);

				$( '.index-post-type' ).on(
					'click',
					function ( e ) {
						e.preventDefault();
						let post_type                 = $( this ).attr( 'data-post-type' );
						let index_name                = $( this ).attr( 'data-index-name' );
						let selected_post_type        = $( '.' + post_type );
						let error_message_container   = $( '.index-error-message' );
						let success_message_container = $( '.index-success-message' );
						let error_message             = $( '.post-type-index-error-message' );
						let success_message           = $( '.post-type-index-success-message' );
						let button                    = $( this );

						startProgressUpdates( post_type );

						if ( selected_post_type.is( ':checked' ) ) {
							$.ajax(
								{
									type: 'POST',
									url: wlc_algolia.ajax_url,
									data: {
										action: 'wlc_algolia_handle_post_type_index',
										post_type: post_type,
										index_name: index_name,
										algolia_cpt_nonce: wlc_algolia.cpt_nonce,
									},
									beforeSend: function () {
										error_message_container.css(
											'display',
											'none'
										);
										success_message_container.css(
											'display',
											'none'
										);
										update_progress_bar( 0, post_type );
										button.prop( 'disabled', true );
									},
									success: function ( response ) {
										if ( response.data && response.data.message && true !== response.success ) {
											error_message_container.css(
												'display',
												'block'
											);
											error_message.html( response.data.message );
											button.prop( 'disabled', false );
										} else {
											success_message_container.css(
												'display',
												'block'
											);
											success_message.html( response.data && response.data.message ? response.data.message : '' );

											// Process batches in the background (non-blocking UI).
											process_next_batch( post_type, button );
										}
									}
								}
							);
						}
					}
				);

				/**
				 * Wizard UX enhancements (no reload):
				 * - Test connection via AJAX
				 * - Quick-select post types
				 * - "Index all" in wizard step 5
				 */
				$( '#wlc-wizard-test-connection' ).on(
					'click',
					function () {
						let nonce = $( '#wlc-wizard-ajax-nonce-test' ).val();
						let appId = $( '[data-wlc-field="app_id"]' ).val();
						let writeKey = $( '[data-wlc-field="write_key"]' ).val();
						let statusEl = $( '#wlc-wizard-conn-status' );

						statusEl.removeClass( 'is-success is-error' ).addClass( 'is-loading' );
						statusEl.text( 'Testing connection…' );

						$.ajax(
							{
								type: 'POST',
								url: wlc_algolia.ajax_url,
								data: {
									action: 'wlc_algolia_wizard_test_connection',
									nonce: nonce,
									application_id: appId,
									write_api_key: writeKey,
								},
								success: function ( response ) {
									statusEl.removeClass( 'is-loading' );
									if ( response && response.success ) {
										statusEl.addClass( 'is-success' );
										let msg = ( response.data && response.data.message ) ? response.data.message : 'OK';
										if ( response.data && null !== response.data.indicesCount ) {
											msg += ' (indices: ' + response.data.indicesCount + ')';
										}
										statusEl.text( msg );
									} else {
										statusEl.addClass( 'is-error' );
										let msg = ( response && response.data && response.data.message ) ? response.data.message : 'Connection failed.';
										statusEl.text( msg );
									}
								},
								error: function () {
									statusEl.removeClass( 'is-loading' ).addClass( 'is-error' );
									statusEl.text( 'Connection failed.' );
								},
							}
						);
					}
				);

				$( '.wlc-wizard-select' ).on(
					'click',
					function () {
						let mode = $( this ).attr( 'data-wlc-select' );
						let boxes = $( '.wlc-wizard-rows--pt input[type="checkbox"]' );
						if ( ! boxes.length ) return;

						if ( 'all' === mode ) {
							boxes.prop( 'checked', true );
							return;
						}
						if ( 'none' === mode ) {
							boxes.prop( 'checked', false );
							return;
						}
						if ( 'recommended' === mode ) {
							boxes.each( function () {
								let isRec = $( this ).attr( 'data-recommended' ) === '1';
								$( this ).prop( 'checked', isRec );
							} );
						}
					}
				);

				// Step 3: reload step with different post type to show different field list.
				$( '#wlc-wizard-primary-post-type' ).on(
					'change',
					function () {
						let val = $( this ).val();
						if ( ! val ) return;
						let url = new URL( window.location.href );
						url.searchParams.set( 'primary_post_type', val );
						window.location.href = url.toString();
					}
				);

				// Step 3: filter fields list.
				$( '#wlc-wizard-field-filter' ).on(
					'input',
					function () {
						let q = ( $( this ).val() || '' ).toString().trim().toLowerCase();
						let rows = $( '.wlc-wizard-fieldrow' );
						if ( ! rows.length ) return;
						if ( '' === q ) {
							rows.show();
							return;
						}
						rows.each( function () {
							let hay = ( $( this ).attr( 'data-field' ) || '' ).toString();
							$( this ).toggle( hay.indexOf( q ) !== -1 );
						} );
					}
				);

				// Step 3: keep facet/index consistent.
				$( '.wlc-wizard-fieldlist' ).on(
					'change',
					'input[type="checkbox"][data-wlc-role]',
					function () {
						let role = $( this ).attr( 'data-wlc-role' );
						let field = $( this ).attr( 'data-wlc-field' );
						if ( ! field ) return;

						let indexBox = $( 'input[data-wlc-role="index"][data-wlc-field="' + field + '"]' );
						let facetBox = $( 'input[data-wlc-role="facet"][data-wlc-field="' + field + '"]' );

						if ( 'facet' === role && $( this ).is( ':checked' ) ) {
							// Faceting requires indexing the field.
							indexBox.prop( 'checked', true );
						}
						if ( 'index' === role && ! $( this ).is( ':checked' ) ) {
							// Turning off indexing turns off facet.
							facetBox.prop( 'checked', false );
						}
					}
				);

				$( '#wlc-wizard-index-all' ).on(
					'click',
					function () {
						let buttons = $( '.wlc-wizard-index-row .index-post-type' );
						if ( ! buttons.length ) return;
						let i = 0;
						function next() {
							if ( i >= buttons.length ) return;
							let btn = $( buttons[i] );
							i++;
							// Trigger existing handler
							btn.trigger( 'click' );
							setTimeout( next, 250 );
						}
						next();
					}
				);
			}
		);

		function update_progress_bar( percentage, post_type ) {
			let progress_text = $( '.progress-text-' + post_type );
			let progress_bar  = $( '.progress-bar-' + post_type );
			progress_bar.css( 'width', percentage + '%' );
			progress_text.text( Math.round( percentage ) + '%' );
		}

		function checkProgressAndUpdateProgressBar(post_type) {
			let progressAjaxUrl = ( window.wlc_algolia && wlc_algolia.ajax_url ) ? wlc_algolia.ajax_url : ajaxurl;
			$.ajax({
				type: 'POST',
				url: progressAjaxUrl,
				data: {
					action: 'wlc_algolia_get_index_progress',
					post_type: post_type,
					algolia_progress_nonce: ( window.wlc_algolia && wlc_algolia.progress_nonce ) ? wlc_algolia.progress_nonce : '',
				},
				success: function(response) {
					if(response.success) {
						const percentage = parseFloat(response.data.progress);
						update_progress_bar(percentage, post_type);
						if (percentage >= 100) {
							clearInterval(intervalId[post_type]);
						}
					}
				}
			});
		}
		
		let intervalId = {}; 
		
		function startProgressUpdates(post_type) {
			intervalId[post_type] = setInterval(function() {
				checkProgressAndUpdateProgressBar(post_type);
			}, 1000); 
		}

		function stopProgressUpdates( post_type ) {
			if ( intervalId[post_type] ) {
				clearInterval( intervalId[post_type] );
				delete intervalId[post_type];
			}
		}

		function process_next_batch( post_type, button ) {
			$.ajax(
				{
					type: 'POST',
					url: wlc_algolia.ajax_url,
					data: {
						action: 'wlc_algolia_process_post_type_index_batch',
						post_type: post_type,
						algolia_cpt_nonce: wlc_algolia.cpt_nonce,
					},
					success: function ( response ) {
						if ( response && response.success && response.data ) {
							const pct = parseFloat( response.data.progress || 0 );
							update_progress_bar( pct, post_type );

							if ( response.data.done ) {
								stopProgressUpdates( post_type );
								update_progress_bar( 100, post_type );
								button.prop( 'disabled', false );
								return;
							}

							// schedule next batch
							setTimeout( function () {
								process_next_batch( post_type, button );
							}, 50 );
						} else {
							button.prop( 'disabled', false );
						}
					},
					error: function () {
						button.prop( 'disabled', false );
					},
				}
			);
		}

		let enable_autocomplete     = $( 'input.autocomplete-enable' );
		let autocomplete_checkboxes = $( 'input.autocomplete-input' );
		let autocomplete_ui_switch  = $( 'span.autocomplete-switch' );

		function update_autocomplete_changes() {
			if ( ! enable_autocomplete.prop( 'checked' ) ) {
				autocomplete_checkboxes.prop( 'disabled', true );
				autocomplete_checkboxes.css( 'opacity', '0' );
				autocomplete_ui_switch.css( 'opacity', '0.2' );
			} else {
				autocomplete_checkboxes.prop( 'disabled', false );
				autocomplete_ui_switch.css( 'opacity', '1' );
			}
		}

		update_autocomplete_changes();

		$( enable_autocomplete ).change(
			function () {
				update_autocomplete_changes();
			}
		);

	}
)( jQuery );
