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

	var cfg = window.tsffeAdmin || {};
	var form = document.getElementById( 'tsffe-form' );
	if ( ! form ) {
		return;
	}

	var steps = Array.prototype.slice.call( form.querySelectorAll( '.tsffe-step' ) );
	var current = 0;

	var prevBtn = document.getElementById( 'tsffe-prev' );
	var nextBtn = document.getElementById( 'tsffe-next' );
	var publishBtn = document.getElementById( 'tsffe-publish' );
	var refreshBtn = document.getElementById( 'tsffe-refresh-preview' );
	var result = document.getElementById( 'tsffe-publish-result' );

	function showStep( i ) {
		current = Math.max( 0, Math.min( steps.length - 1, i ) );
		steps.forEach( function ( s, idx ) {
			s.hidden = idx !== current;
		} );
		prevBtn.disabled = current === 0;
		var last = current === steps.length - 1;
		// Inline display as well as `hidden`: WP admin's `.button { display:
		// inline-block }` overrides the browser's [hidden]{display:none}.
		nextBtn.hidden = last;
		nextBtn.style.display = last ? 'none' : '';
		publishBtn.hidden = ! last;
		publishBtn.style.display = last ? '' : 'none';
	}

	// Collect the form into a nested object suitable for $_POST['statement'].
	function collect() {
		var data = {
			answers: {},
			non_compliance: [],
			disproportionate_burden: [],
			out_of_scope: []
		};

		function lines( name ) {
			var el = form.querySelector( '[name="' + name + '"]' );
			if ( ! el ) {
				return [];
			}
			return el.value.split( '\n' ).map( function ( s ) {
				return s.trim();
			} ).filter( function ( s ) {
				return s.length > 0;
			} );
		}

		[ 'org_name', 'site_name', 'site_url', 'scope', 'contact_email', 'feedback_method',
		  'enforcement_country', 'wcag_version', 'prepared_date', 'last_reviewed_date',
		  'assessment_method', 'technologies' ].forEach( function ( name ) {
			var el = form.querySelector( '[name="' + name + '"]' );
			data[ name ] = el ? el.value : '';
		} );

		data.non_compliance = lines( 'non_compliance' );
		data.disproportionate_burden = lines( 'disproportionate_burden' );
		data.out_of_scope = lines( 'out_of_scope' );

		form.querySelectorAll( 'input[type="radio"]:checked' ).forEach( function ( r ) {
			var m = r.name.match( /^answers\[(.+)\]$/ );
			if ( m ) {
				data.answers[ m[ 1 ] ] = r.value;
			}
		} );

		var cf = document.getElementById( 'tsffe-confirm_full' );
		data.confirm_full = cf && cf.checked ? '1' : '';

		return data;
	}

	function footerLink() {
		var el = document.getElementById( 'tsffe-footer_link' );
		return el && el.checked ? '1' : '0';
	}

	// Build a urlencoded body that preserves the nested statement[...] structure.
	function encodeStatement( body, obj, prefix ) {
		Object.keys( obj ).forEach( function ( key ) {
			var val = obj[ key ];
			var name = prefix + '[' + key + ']';
			if ( Array.isArray( val ) ) {
				val.forEach( function ( v, i ) {
					body.set( name + '[' + i + ']', v );
				} );
			} else if ( val && typeof val === 'object' ) {
				encodeStatement( body, val, name );
			} else {
				body.set( name, val == null ? '' : val );
			}
		} );
	}

	function ajax( action ) {
		var body = new URLSearchParams();
		body.set( 'action', action );
		body.set( '_ajax_nonce', cfg.nonce );
		body.set( 'footer_link', footerLink() );
		encodeStatement( body, collect(), 'statement' );

		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();
		} );
	}

	function clearErrors() {
		form.querySelectorAll( '.tsffe-error' ).forEach( function ( e ) {
			e.textContent = '';
		} );
	}

	function showErrors( errors ) {
		clearErrors();
		Object.keys( errors || {} ).forEach( function ( field ) {
			var el = form.querySelector( '.tsffe-error[data-error-for="' + field + '"]' );
			if ( el ) {
				el.textContent = errors[ field ];
			}
		} );
	}

	function refreshPreview() {
		ajax( 'tsffe_preview' ).then( function ( json ) {
			if ( json && json.success ) {
				document.getElementById( 'tsffe-preview' ).innerHTML = json.data.html;
			}
		} ).catch( function () {} );
	}

	function save() {
		return ajax( 'tsffe_save' ).then( function ( json ) {
			if ( json && json.success ) {
				showErrors( json.data.errors );
			}
			refreshPreview();
			return json;
		} );
	}

	nextBtn.addEventListener( 'click', function () {
		save();
		showStep( current + 1 );
	} );
	prevBtn.addEventListener( 'click', function () {
		save();
		showStep( current - 1 );
	} );
	refreshBtn.addEventListener( 'click', refreshPreview );

	publishBtn.addEventListener( 'click', function () {
		publishBtn.disabled = true;
		result.textContent = cfg.i18n.publishing;
		ajax( 'tsffe_publish' ).then( function ( json ) {
			publishBtn.disabled = false;
			if ( json && json.success ) {
				clearErrors();
				result.innerHTML = cfg.i18n.published + ' ';
				if ( json.data.page_url ) {
					var a = document.createElement( 'a' );
					a.href = json.data.page_url;
					a.textContent = json.data.page_url;
					result.appendChild( a );
				}
			} else {
				result.textContent = cfg.i18n.fixErrors;
				showErrors( json && json.data ? json.data.errors : {} );
			}
		} ).catch( function () {
			publishBtn.disabled = false;
			result.textContent = cfg.i18n.saveError;
		} );
	} );

	showStep( 0 );
	refreshPreview();
}() );
