/**
 * @file assets/js/adminjs/repeater/mbs-contributors.js
 * MBS.Contributors — contributor repeater, sort, public toggle
 * Component of admin-repeater.js — extracted Session 94.
 * Dependency: mbs-admin-repeater (namespace initializer).
 * @package MyBookShowroom
 */

// =============================================================================
// Contributors Repeater
// =============================================================================

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

	MBS.Contributors = {
		init: function() {
			this.bindAddRow();
			this.bindRemoveRow();
			this.bindRoleChange();
			this.bindSortable();
			this.bindSortButtons();
			this.bindPublicToggle();
		},

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

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

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

				// Update sort order on the hidden input.
				$template.find('.mbs-contributor-sort-input').val(rowCount);

				// Reset all form fields.
				$template.find('input[type="text"], input[type="hidden"]').each(function() {
					if ( ! $(this).hasClass('mbs-contributor-sort-input') ) {
						$(this).val('');
					}
				});
				$template.find('select').val('');
				$template.find('input[type="checkbox"]').prop('checked', true);
				$template.find('.mbs-contributor-custom-label').hide();

				// Show drag handle or arrows to match current sortable state.
				var hasSortable = typeof $.fn.sortable !== 'undefined';
				$template.find( '.mbs-drag-handle' ).toggle( hasSortable );
				$template.find( '.mbs-contributor-sort-controls' ).toggle( ! hasSortable );
				$container.append($template);
				// Refresh sortable so new row is draggable.
				if ( hasSortable && $container.data( 'ui-sortable' ) ) {
					$container.sortable( 'refresh' );
				}
			});
		},

		bindRemoveRow: function() {
			$(document).on('click', '.mbs-remove-contributor-row', function(e) {
				e.preventDefault();
				if (window.confirm(__('Remove this contributor?', 'my-book-showroom'))) {
					$(this).closest('.mbs-contributor-row').remove();
					MBS.Contributors.reindex();
				}
			});
		},

		bindRoleChange: function() {
			$(document).on('change', '.mbs-contributor-role-select', function() {
				const isOther = $(this).val() === 'Z01';
				$(this).closest('.mbs-contributor-row')
					.find('.mbs-contributor-custom-label')
					.toggle(isOther);
			});
		},

		/**
		 * Initialize jQuery UI Sortable on contributor rows.
		 * Hides drag handles and reveals arrow buttons when sortable is unavailable.
		 */
		bindSortable: function() {
			var $rows = $( '#mbs-contributors-rows' );
			if ( ! $rows.length ) { return; }

			if ( typeof $.fn.sortable !== 'undefined' ) {
				// Drag available — hide fallback arrows (already display:none in PHP).
				$rows.find( '.mbs-contributor-sort-controls' ).hide();
				$rows.find( '.mbs-drag-handle' ).show();
				$rows.sortable( {
					handle:      '.mbs-drag-handle',
					axis:        'y',
					cursor:      'move',
					tolerance:   'pointer',
					placeholder: 'mbs-sortable-placeholder',
					start: function( e, ui ) {
						ui.placeholder.height( ui.item.outerHeight() );
					},
					update: function() {
						MBS.Contributors.reindex();
					}
				} );
			} else {
				// No sortable — hide drag handles, reveal arrow buttons.
				$rows.find( '.mbs-drag-handle' ).hide();
				$rows.find( '.mbs-contributor-sort-controls' ).show();
			}
		},

		bindSortButtons: function() {
			$(document).on('click', '.mbs-contributor-move-up', function(e) {
				e.preventDefault();
				const $row = $(this).closest('.mbs-contributor-row');
				const $prev = $row.prev('.mbs-contributor-row');
				if ($prev.length) {
					$row.insertBefore($prev);
					MBS.Contributors.reindex();
				}
			});

			$(document).on('click', '.mbs-contributor-move-down', function(e) {
				e.preventDefault();
				const $row = $(this).closest('.mbs-contributor-row');
				const $next = $row.next('.mbs-contributor-row');
				if ($next.length) {
					$row.insertAfter($next);
					MBS.Contributors.reindex();
				}
			});
		},

		// C2-001: Sync the public checkbox state to the hidden field so save()
		// reads the correct value from mbs_contributor_public[]. Without this,
		// the hidden field always submits the PHP-rendered (DB) value regardless
		// of whether the admin changed the checkbox.
		bindPublicToggle: function() {
			$(document).on('change', '.mbs-contributor-public-cb', function() {
				$(this).closest('.mbs-contributor-row')
				       .find('.mbs-contributor-public-hidden')
				       .val( $(this).is(':checked') ? 1 : 0 );
			});
		},

		reindex: function() {
			$('#mbs-contributors-rows .mbs-contributor-row').each(function(i) {
				$(this).find('.mbs-contributor-sort-input').val(i);
			});
		}
	};

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

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