/**
 * @file assets/js/adminjs/admin-share-text.js
 * Per-book social share text pill insertion, live token preview, and Oxford-comma author formatting in the Book Editor.
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

	var MBS_ShareText = {

		serverData: window.MBS_ShareTextData || {},

		init: function () {
			this.bindPills();
			this.bindPreview();
			this.bindLiveFields(); // watch title + author fields for real-time updates
			this.updatePreview();  // render initial state on page load
		},

		/**
		 * Insert text at the cursor position of an <input> or <textarea>.
		 * Replaces any active selection. Repositions cursor after the insert.
		 */
		insertAtCursor: function ( el, text ) {
			var start = el.selectionStart;
			var end   = el.selectionEnd;
			var val   = el.value;

			el.value = val.slice( 0, start ) + text + val.slice( end );
			el.selectionStart = el.selectionEnd = start + text.length;

			// Trigger input so the preview updates immediately after insert.
			$( el ).trigger( 'input' );
		},

		/**
		 * Read the current book title from the DOM editor field.
		 * Falls back to the server-localised value for saved posts where the
		 * field may not be present.
		 */
		getLiveTitle: function () {
			var $field = $( '#mbs_book_title' );
			if ( $field.length ) {
				var val = $field.val().trim();
				if ( val ) { return val; }
			}
			return this.serverData.title || '';
		},

		/**
		 * Read the current author list from #mbs_authors (comma-separated names),
		 * format it the same way PHP does, and return the result.
		 * Falls back to the server-localised author string.
		 */
		getLiveAuthor: function () {
			var $hidden = $( '#mbs_authors' );
			if ( $hidden.length ) {
				var raw   = $hidden.val().trim();
				var names = raw
					? raw.split( ',' ).map( function ( n ) { return n.trim(); } ).filter( Boolean )
					: [];

				if ( names.length === 1 ) { return names[ 0 ]; }
				if ( names.length === 2 ) { return sprintf( __( '%1$s and %2$s', 'my-book-showroom' ), names[ 0 ], names[ 1 ] ); }
				if ( names.length > 2 ) {
					return sprintf( __( '%1$s, and %2$s', 'my-book-showroom' ), names.slice( 0, -1 ).join( ', ' ), names[ names.length - 1 ] );
				}
			}
			return this.serverData.author || '';
		},

		/**
		 * Resolve {title}, {author}, {url} tokens against live DOM data.
		 * When the share text field is empty, the global default template is used.
		 */
		resolveTokens: function ( template ) {
			if ( ! template || ! template.trim() ) {
				template = this.serverData.globalDefault || '';
			}

			return template
				.replace( /\{title\}/g,  this.getLiveTitle()  )
				.replace( /\{author\}/g, this.getLiveAuthor() )
				.replace( /\{url\}/g,    this.serverData.url || '' );
		},

		updatePreview: function () {
			var val      = $( '#mbs_share_text' ).val();
			var resolved = MBS_ShareText.resolveTokens( val );
			$( '#mbs_share_text_preview' ).text( resolved );
		},

		bindPills: function () {
			$( document ).on( 'click', '.mbs-share-text-pill', function ( e ) {
				e.preventDefault();

				var tag    = $( this ).data( 'tag' );
				var $input = $( '#mbs_share_text' );

				if ( ! $input.length || ! tag ) {
					return;
				}

				MBS_ShareText.insertAtCursor( $input[ 0 ], String( tag ) );
				$input.trigger( 'focus' );
			} );
		},

		bindPreview: function () {
			$( '#mbs_share_text' ).on( 'input', function () {
				MBS_ShareText.updatePreview();
			} );
		},

		/**
		 * Watch the book title input and the hidden authors field so the preview
		 * updates whenever those values change — no save required.
		 * The authors hidden input is updated by admin-authors.js whenever
		 * a tag is added or removed, so we use MutationObserver on the author
		 * tag list as a proxy (the hidden input change event isn't reliable for
		 * programmatic updates).
		 */
		bindLiveFields: function () {
			// Title field — standard input event.
			$( '#mbs_book_title' ).on( 'input', function () {
				MBS_ShareText.updatePreview();
			} );

			// Author list — observe #mbs-author-list DOM changes (tags added/removed).
			// admin-authors.js appends/removes .mbs-author-tag elements here.
			var authorList = document.getElementById( 'mbs-author-list' );
			if ( authorList && window.MutationObserver ) {
				var observer = new MutationObserver( function () {
					MBS_ShareText.updatePreview();
				} );
				observer.observe( authorList, { childList: true, subtree: true } );
			}
		}
	};

	$( document ).ready( function () {
		MBS_ShareText.init();
	} );

} )( jQuery );
