/**
 * @file assets/js/adminjs/repeater/mbs-format-buy-links.js
 * MBS.FormatBuyLinks -- per-format buy link rows
 * Component of admin-repeater.js -- extracted Session 94.
 * Sprint 182: drag-sort via MBS.SortableList, one instance per format row container.
 * Dependencies: mbs-admin-repeater (namespace initializer), mbs-sortable-list.
 * @package MyBookShowroom
 */

// =============================================================================
// Format Buy Links -- add buy links within each format row
// =============================================================================

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

	MBS.FormatBuyLinks = {

		/**
		 * MBS.SortableList instances, keyed by data-row-index value.
		 * @type {Object}
		 */
		_sortables: {},

		/**
		 * Initialize the Format Buy Links repeater.
		 * @returns {void}
		 */
		init: function() {
			this.initSortables();
			this.bindAddBuyLink();
			// Remove handler: global listener in mbs-buy-links.js covers .mbs-remove-buy-link-row (A4-008).
		},

		/**
		 * Initialize one MBS.SortableList per .mbs-format-buy-links-rows container.
		 * Runs once at DOMReady for containers present in the initial page render.
		 * The factory handles both PRO drag mode and FREE arrow-button fallback.
		 * @returns {void}
		 */
		initSortables: function() {
			var self = this;
			if ( typeof MBS.SortableList === 'undefined' ) {
				return;
			}
			$( '.mbs-format-buy-links-rows' ).each( function() {
				var rowIdx = $( this ).data( 'row-index' );
				self._sortables[ rowIdx ] = MBS.SortableList.create( {
					container:        this,
					itemSelector:     '.mbs-buy-link-row',
					handleSelector:   '.mbs-drag-handle',
					controlsSelector: '.mbs-buy-link-fallback',
					upSelector:       '.mbs-reorder-move-up',
					downSelector:     '.mbs-reorder-move-down'
				} );
			} );
		},

		/**
		 * Bind the Add Buy Link button for each format row.
		 * Clones .mbs-buy-link-row from the hidden PHP template div, replaces
		 * __ROW_IDX__ name-attribute placeholders, re-enables disabled inputs
		 * (A2-012), clears field values, and appends to the container.
		 * Toggles sort-control visibility to match the active sort mode for
		 * this container, then calls sortable.refresh().
		 * @returns {void}
		 */
		bindAddBuyLink: function() {
			var self = this;
			$( document ).on( 'click', '.mbs-add-format-buy-link', function( e ) {
				e.preventDefault();
				var $btn       = $( this );
				var $container = $btn.prev( '.mbs-format-buy-links-rows' );
				var rowIdx     = $container.data( 'row-index' );
				var $template  = $( '#fmt-buy-link-row-template-' + rowIdx );
				if ( ! $template.length ) { return; }

				// Clone the .mbs-buy-link-row wrapper from within the hidden template div.
				var $clone = $template.find( '.mbs-buy-link-row' ).clone( true ).show();

				// Replace __ROW_IDX__ in all [name] attributes.
				$clone.find( '[name]' ).each( function() {
					$( this ).attr( 'name', $( this ).attr( 'name' ).replace( /__ROW_IDX__/g, rowIdx ) );
				} );

				// Re-enable inputs/buttons disabled on the template row (A2-012, E-0 spec).
				$clone.find( '[disabled]' ).prop( 'disabled', false );

				// Clear all field values.
				$clone.find( 'input[type="hidden"], input[type="url"], input[type="text"], textarea' )
				      .val( '' );

				// Toggle sort controls to match the active sort mode for this container.
				var sortable = self._sortables[ rowIdx ];
				if ( sortable ) {
					var hasDrag = sortable.usingDrag();
					$clone.find( '.mbs-buy-link-fallback' ).toggle( ! hasDrag );
					$clone.find( '.mbs-drag-handle' ).toggle( hasDrag );
				}

				$container.append( $clone );

				if ( sortable ) { sortable.refresh(); }
			} );
		}
	};

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

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