/**
 * @file assets/js/adminjs/admin-endorsements.js
 * Endorsements repeater (quote, attribution, title, visibility) in the Book Editor.
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

	MBS.Endorsements = {
		init: function() {
			this.bindAddRow();
			this.bindRemoveRow();
		},

		bindAddRow: function() {
			$( '.mbs-add-endorsement-row' ).on( 'click', function() {
				const row = `<div class="mbs-repeater-row">
					<textarea name="mbs_endorsement_quote[]" class="large-text" rows="3" placeholder="${escAttr(__( 'Quote text...', 'my-book-showroom' ))}"></textarea>
					<input type="text" name="mbs_endorsement_attributed_to[]" class="widefat" placeholder="${escAttr(__( 'Attributed to (name)', 'my-book-showroom' ))}">
					<input type="text" name="mbs_endorsement_attribution_title[]" class="widefat" placeholder="${escAttr(__( 'Title or publication', 'my-book-showroom' ))}">
					<label><input type="checkbox" name="mbs_endorsement_visible[]" value="1" checked> ${escHtml(__( 'Visible on front-end', 'my-book-showroom' ))}</label>
					<button type="button" class="button button-link-delete mbs-remove-row">${escHtml(__( 'Remove', 'my-book-showroom' ))}</button>
				</div>`;
				$( '.mbs-endorsements-repeater .mbs-repeater-rows' ).append( row );
			});
		},

		bindRemoveRow: function() {
			$( document ).on( 'click', '.mbs-remove-row', function() {
				if ( window.confirm( __( 'Remove this endorsement?', 'my-book-showroom' ) ) ) {
					$( this ).closest( '.mbs-repeater-row' ).remove();
				}
			});
		}
	};

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

// BUG-E1: Auto-init was missing — MBS.Endorsements.init() was never called so the
// Add / Remove click handlers were never bound. Pattern matches BUG-07A (admin-authors.js).
jQuery( function() {
	if ( typeof MBS !== 'undefined' && MBS.Endorsements ) {
		MBS.Endorsements.init();
	}
} );
