/* global tfwaAdmin */
( function () {
	'use strict';

	var cfg = window.tfwaAdmin || {};

	function ajax( action, data ) {
		var body = new URLSearchParams();
		body.set( 'action', action );
		body.set( '_ajax_nonce', cfg.nonce );
		Object.keys( data || {} ).forEach( function ( k ) {
			body.set( k, data[ k ] );
		} );

		return fetch( cfg.ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			body: body.toString()
		} ).then( function ( res ) {
			return res.json();
		} ).then( function ( json ) {
			if ( ! json || ! json.success ) {
				throw new Error( 'request_failed' );
			}
			return json.data;
		} );
	}

	document.addEventListener( 'DOMContentLoaded', function () {
		var btn = document.getElementById( 'tfwa-scan-start' );
		if ( ! btn ) {
			return;
		}

		btn.addEventListener( 'click', function () {
			btn.disabled = true;

			var progress = document.getElementById( 'tfwa-scan-progress' );
			var bar = progress.querySelector( '.tfwa-progress-bar' );
			var status = document.getElementById( 'tfwa-scan-status' );

			progress.hidden = false;
			bar.style.width = '0%';
			status.textContent = cfg.i18n.scanning;

			ajax( 'tfwa_scan_start', {} ).then( function ( data ) {
				var total = data.total || 0;
				var token = data.token || '';
				var scanned = 0;

				function step() {
					return ajax( 'tfwa_scan_step', { token: token } ).then( function ( res ) {
						scanned = res.posts_scanned;

						var pct = total > 0 ? Math.min( 100, Math.round( scanned / total * 100 ) ) : 100;
						bar.style.width = pct + '%';
						status.textContent = cfg.i18n.scanning + ' ' + scanned + ' / ' + total;

						if ( ! res.done ) {
							return step();
						}

						bar.style.width = '100%';
						window.location.reload();
					} );
				}

				return step();
			} ).catch( function () {
				status.textContent = cfg.i18n.scanError;
				btn.disabled = false;
			} );
		} );
	} );
}() );
