/**
 * @file assets/js/adminjs/repeater/mbs-awards.js
 * MBS.Awards — awards & accolades repeater (Sprint CE-1)
 * Component of admin-repeater.js — extracted Session 94.
 * Dependency: mbs-admin-repeater (namespace initializer).
 * @package MyBookShowroom
 */

// =============================================================================
// Awards & Accolades Repeater (Sprint CE-1)
// =============================================================================

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

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

		bindAddRow: function() {
			$( document ).on( 'click', '.mbs-add-award-row', function( e ) {
				e.preventDefault();

				const $container = $( '#mbs-awards-rows' );
				const $template  = $( '#awards-row-template' ).clone()
					.removeAttr( 'id' )
					.removeClass( 'mbs-award-row-template' )
					.show();

				const rowCount = $container.find( '.mbs-award-row' ).length;

				// Re-index all name attributes from [0] to [rowCount].
				$template.find( 'input, select' ).each( function() {
					const name = $( this ).attr( 'name' );
					if ( name ) {
						$( this ).attr( 'name', name.replace( /\[0\]/, '[' + rowCount + ']' ) );
					}
					$( this ).val( '' );
				} );
				// Re-enable template inputs disabled to prevent phantom form submission (PLG-006).
				$template.find( '[disabled]' ).prop( 'disabled', false );

				$container.append( $template );
			} );
		},

		bindRemoveRow: function() {
			$( document ).on( 'click', '.mbs-remove-award-row', function( e ) {
				e.preventDefault();
				// eslint-disable-next-line no-alert
				if ( window.confirm( __( 'Remove this award?', 'my-book-showroom' ) ) ) {
					$( this ).closest( '.mbs-award-row' ).remove();
				}
			} );
		}
	};

	$( function() {
		MBS.Awards.init();
	} );

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