/**
 * @file assets/js/adminjs/admin-authors.js
 * Author(s) input with WP suggest autocomplete, Add button, and removable tag list in the Book Editor.
 * @package MyBookShowroom
 * @since   1.0.0
 */

(function( MBS, $, undefined ) {
	'use strict';
	var __ = wp.i18n.__;

	MBS.Authors = {
		init: function() {
			if ( ! $( '#mbs_authors_input' ).length ) {
				return;
			}

			const input  = $( '#mbs_authors_input' );
			const hidden = $( '#mbs_authors' );
			const list   = $( '#mbs-author-list' );

			// Core WP suggest for mbs_author taxonomy.
			// minchars: 2 — type at least two characters to see suggestions.
			input.suggest( ajaxurl + '?action=ajax-tag-search&tax=mbs_author', {
				multiple: true,
				minchars: 1,
				delay:    300,
				onSelect: function() {
					// WP suggest with multiple:true appends ", " to the input after selection
					// so the user can type another name. Strip any trailing comma/whitespace
					// before treating the value as a finished author name.
					const term = this.value.replace( /,\s*$/, '' ).trim();
					if ( ! term ) { return; }
					MBS.Authors.addAuthorTag( term );
					input.val( '' );
				}
			} );

			// Manual "Add Author" button — adds whatever is typed without
			// requiring the user to select from the autocomplete dropdown.
			$( '#mbs-add-author-btn' ).on( 'click', function() {
				const term = input.val().trim();
				if ( term ) {
					MBS.Authors.addAuthorTag( term );
					input.val( '' );
				}
				input.focus();
			} );

			// Remove handler (delegated on the tag list container).
			// BUG-07C: Was using tag.data('term-name') but PHP-rendered tags used
			// data-term-id — mismatch. PHP now outputs data-term-name; both paths
			// consistently use data-term-name here.
			list.on( 'click', '.mbs-remove-author', function( e ) {
				e.preventDefault();
				const $tag = $( this ).closest( '.mbs-author-tag' );
				const name = $tag.data( 'term-name' );
				let current = hidden.val() ? hidden.val().split( ',' ) : [];
				current = current.filter( function( n ) { return n.trim() !== name; } );
				hidden.val( current.join( ',' ) );
				$tag.remove();
			} );

		},

		/**
		 * Add a new author tag to the list and update the hidden field.
		 *
		 * BUG-07B: Was generating malformed HTML — missing '>' after opening span,
		 * and using string concatenation that exposed XSS surface.
		 * Now uses jQuery DOM construction: safe against injection, always valid HTML.
		 *
		 * @param {string} term Author name to add.
		 */
		addAuthorTag: function( term ) {
			const hidden = $( '#mbs_authors' );
			const list   = $( '#mbs-author-list' );
			let current  = hidden.val() ? hidden.val().split( ',' ) : [];

			// Duplicate check: iterate rather than use attribute selector to avoid
			// escaping issues with special characters in author names.
			let isDuplicate = false;
			list.find( '.mbs-author-tag' ).each( function() {
				if ( $( this ).data( 'term-name' ) === term ) {
					isDuplicate = true;
					return false; // break .each()
				}
			} );
			if ( isDuplicate ) { return; }

			// Build tag via jQuery DOM construction — no HTML string injection.
			const $tag = $( '<span>', { 'class': 'mbs-author-tag', 'data-term-name': term } )
				.text( term )
				.append( '\u00a0' )
				.append(
					$( '<a>', { href: '#', 'class': 'mbs-remove-author', title: __( 'Remove author', 'my-book-showroom' ) } )
						.html( '&times;' )
				);

			list.append( $tag ).append( ' ' );
			current.push( term );
			hidden.val( current.join( ',' ) );
		}
	};

	// BUG-07A: Auto-init was missing — the entire module never activated.
	// Pattern matches admin-validation.js.
	$( function() {
		if ( typeof MBS !== 'undefined' && MBS.Authors ) {
			MBS.Authors.init();
		}
	} );

} )( window.MBS = window.MBS || {}, jQuery );
