( function ( $ ) {
	'use strict';

	var polling = null;

	function ajax( action, extra ) {
		return $.post( arcaiAdmin.ajaxUrl, $.extend( { action: action, nonce: arcaiAdmin.nonce }, extra || {} ) );
	}

	function fmt( template, values ) {
		return template.replace( /%(\d)\$s/g, function ( match, index ) {
			return values[ index - 1 ];
		} );
	}

	function setProgress( state ) {
		var pct = state.total ? Math.round( ( 100 * state.done ) / state.total ) : 0;
		$( '#arcai-progress .arcai-progress-bar span' ).css( 'width', pct + '%' );
		$( '#arcai-progress' ).attr( 'data-status', state.status );
		$( '#arcai-indexed-count' ).text( state.indexed_posts );

		var text = '';
		if ( state.status === 'running' ) {
			text = state.done + ' / ' + state.total;
		} else if ( state.status === 'done' ) {
			text = '✓ ' + state.done + ' / ' + state.total;
		} else if ( state.status === 'error' ) {
			text = '⚠ ' + state.message;
		} else if ( state.status === 'cancelled' ) {
			text = '✕';
		}
		if ( state.errors > 0 && state.status !== 'error' ) {
			text += ' (' + state.errors + ' errors)';
		}
		$( '#arcai-progress .arcai-progress-text' ).text( text );

		$( '#arcai-index-btn' ).prop( 'disabled', state.status === 'running' );
		$( '#arcai-cancel-btn' ).prop( 'disabled', state.status !== 'running' );

		if ( state.status === 'running' && ! polling ) {
			polling = setInterval( poll, 2000 );
		}
		if ( state.status !== 'running' && polling ) {
			clearInterval( polling );
			polling = null;
		}
	}

	function poll() {
		ajax( 'arcai_index_status' ).done( function ( res ) {
			if ( res.success ) {
				setProgress( res.data );
			}
		} );
	}

	$( '#arcai-index-btn' ).on( 'click', function () {
		var $btn = $( this ).prop( 'disabled', true );

		ajax( 'arcai_estimate_index' )
			.done( function ( res ) {
				if ( ! res.success ) {
					alert( arcaiAdmin.i18n.error );
					$btn.prop( 'disabled', false );
					return;
				}
				var est = res.data;
				var message = fmt( arcaiAdmin.i18n.confirmIndex, [
					est.posts.toLocaleString(),
					est.tokens.toLocaleString(),
					'$' + est.cost.toFixed( 4 )
				] );
				if ( ! window.confirm( message ) ) {
					$btn.prop( 'disabled', false );
					return;
				}
				ajax( 'arcai_start_index' ).done( function ( startRes ) {
					if ( startRes.success ) {
						setProgress( startRes.data );
					} else {
						alert( ( startRes.data && startRes.data.message ) || arcaiAdmin.i18n.error );
						$btn.prop( 'disabled', false );
					}
				} );
			} )
			.fail( function () {
				alert( arcaiAdmin.i18n.error );
				$btn.prop( 'disabled', false );
			} );
	} );

	$( '#arcai-cancel-btn' ).on( 'click', function () {
		ajax( 'arcai_cancel_index' ).done( function ( res ) {
			if ( res.success ) {
				setProgress( res.data );
			}
		} );
	} );

	if ( $( '#arcai-progress' ).attr( 'data-status' ) === 'running' ) {
		polling = setInterval( poll, 2000 );
	}
} )( jQuery );
