/* Auto Publication Updater — settings page: author lookup + manual-entry repeater. */
( function () {
	'use strict';

	function $( sel, ctx ) {
		return ( ctx || document ).querySelector( sel );
	}

	/* ---------- Author lookup ---------- */

	var queryInput = $( '#publiton-lookup-query' );
	var lookupBtn = $( '#publiton-lookup-btn' );
	var spinner = $( '#publiton-lookup-spinner' );
	var resultsBox = $( '#publiton-lookup-results' );
	var currentBox = $( '#publiton-current-author' );
	var idField = $( '#publiton-author-id' );
	var nameField = $( '#publiton-author-name' );
	var inputField = $( '#publiton-author-input' );

	function showMessage( text ) {
		resultsBox.textContent = '';
		var p = document.createElement( 'p' );
		p.className = 'publiton-lookup-message';
		p.textContent = text;
		resultsBox.appendChild( p );
	}

	function selectCandidate( candidate ) {
		idField.value = candidate.id;
		nameField.value = candidate.name;
		inputField.value = queryInput.value;
		currentBox.textContent = '';
		var strong = document.createElement( 'strong' );
		strong.textContent = candidate.name;
		var code = document.createElement( 'code' );
		code.textContent = candidate.id;
		currentBox.appendChild( strong );
		currentBox.appendChild( document.createTextNode( ' ' ) );
		currentBox.appendChild( code );
		currentBox.appendChild( document.createTextNode( ' ✓' ) );
		resultsBox.textContent = '';
	}

	function renderCandidates( candidates ) {
		resultsBox.textContent = '';
		if ( ! candidates.length ) {
			showMessage( PUBLITON.i18n.noMatches );
			return;
		}
		var list = document.createElement( 'ul' );
		list.className = 'publiton-candidates';
		candidates.forEach( function ( candidate ) {
			var li = document.createElement( 'li' );
			var btn = document.createElement( 'button' );
			btn.type = 'button';
			btn.className = 'button button-small';
			btn.textContent = PUBLITON.i18n.select;
			btn.addEventListener( 'click', function () {
				selectCandidate( candidate );
			} );
			var label = document.createElement( 'span' );
			var hint = candidate.hint ? ' — ' + candidate.hint : '';
			label.textContent = candidate.name + hint + ' (' + candidate.works + ' ' + PUBLITON.i18n.works + ') ';
			li.appendChild( label );
			li.appendChild( btn );
			list.appendChild( li );
		} );
		resultsBox.appendChild( list );
	}

	function lookup() {
		var query = queryInput.value.trim();
		if ( ! query ) {
			return;
		}
		spinner.classList.add( 'is-active' );
		lookupBtn.disabled = true;
		var body = new URLSearchParams();
		body.set( 'action', 'publiton_lookup_author' );
		body.set( '_ajax_nonce', PUBLITON.nonce );
		body.set( 'q', query );
		fetch( PUBLITON.ajaxUrl, { method: 'POST', body: body } )
			.then( function ( response ) {
				return response.json();
			} )
			.then( function ( json ) {
				if ( json.success ) {
					renderCandidates( json.data.candidates );
				} else {
					showMessage( ( json.data && json.data.message ) || PUBLITON.i18n.lookupError );
				}
			} )
			.catch( function () {
				showMessage( PUBLITON.i18n.lookupError );
			} )
			.finally( function () {
				spinner.classList.remove( 'is-active' );
				lookupBtn.disabled = false;
			} );
	}

	if ( lookupBtn ) {
		lookupBtn.addEventListener( 'click', lookup );
		queryInput.addEventListener( 'keydown', function ( event ) {
			if ( 'Enter' === event.key ) {
				event.preventDefault();
				lookup();
			}
		} );
	}

	/* ---------- Manual entries repeater ---------- */

	var entriesBox = $( '#publiton-manual-entries' );
	var addBtn = $( '#publiton-add-entry' );
	var template = $( '#publiton-entry-template' );
	var nextIndex = entriesBox ? entriesBox.children.length : 0;

	if ( addBtn && template ) {
		addBtn.addEventListener( 'click', function () {
			var html = template.innerHTML.replace( /__i__/g, String( nextIndex++ ) );
			var holder = document.createElement( 'div' );
			holder.innerHTML = html;
			entriesBox.appendChild( holder.firstElementChild );
		} );
	}

	if ( entriesBox ) {
		entriesBox.addEventListener( 'click', function ( event ) {
			if ( event.target.classList.contains( 'publiton-remove-entry' ) ) {
				event.target.closest( '.publiton-entry' ).remove();
			}
		} );
	}
} )();
