/**
 * @file assets/js/adminjs/admin-publisher.js
 * jQuery UI Autocomplete on the Publisher field; suggests existing publisher names via mbs_publisher_suggest AJAX.
 * @package MyBookShowroom
 * @since   1.0.0
 */

( function ( $, undefined ) {
	'use strict';

	$( function () {
		var $field = $( '#mbs_publisher' );
		if ( ! $field.length ) {
			return;
		}

		var nonce = ( window.MBS_BookEditorAjax || {} ).nonce || '';

		$field.autocomplete( {
			minLength: 1,
			delay:     300,
			source: function ( req, respond ) {
				$.ajax( {
					url:      ajaxurl,
					method:   'GET',
					data:     {
						action: 'mbs_publisher_suggest',
						nonce:  nonce,
						q:      req.term
					},
					success: function ( res ) {
						if ( res.success && Array.isArray( res.data ) ) {
							respond( res.data );
						} else {
							respond( [] );
						}
					},
					error: function () {
						respond( [] );
					}
				} );
			}
		} );
	} );

} )( jQuery );

/**
 * Publisher & Imprint sidebar → Book Header live sync.
 *
 * When the taxonomy dropdowns in the sidebar Publisher & Imprint metabox
 * change, this updates the corresponding Book Header display fields so the
 * user sees the selection reflected immediately without saving.
 *
 * Publisher dropdown  (#mbs_publisher_term)  → #mbs_publisher text input
 * Imprint  dropdown  (#mbs_imprint_term)     → #mbs_imprint_display readonly
 *
 * @since 2.4.0
 */
( function ( $, undefined ) {
	'use strict';

	$( function () {

		/**
		 * Publisher dropdown change → update Book Header mbs_publisher text field.
		 * 'None' selection leaves the text field value unchanged so any manually
		 * entered name is not silently cleared.
		 *
		 * @param {Event} e jQuery change event.
		 * @returns {void}
		 * @since 2.4.0
		 */
		$( '#mbs_publisher_term' ).on( 'change', function () {
			var val  = $( this ).val();
			var name = $( this ).find( 'option:selected' ).text();
			if ( val && val !== '0' ) {
				$( '#mbs_publisher' ).val( name );
			}
		} );

		/**
		 * Imprint dropdown change → update Book Header mbs_imprint_display readonly field.
		 * Clears the display field when 'None' is selected.
		 *
		 * @param {Event} e jQuery change event.
		 * @returns {void}
		 * @since 2.4.0
		 */
		$( '#mbs_imprint_term' ).on( 'change', function () {
			var val  = $( this ).val();
			var name = $( this ).find( 'option:selected' ).text();
			$( '#mbs_imprint_display' ).val( ( val && val !== '0' ) ? name : '' );
		} );

	} );

} )( jQuery );
