/**
 * @file assets/js/adminjs/repeater/mbs-buy-links.js
 * MBS.BuyLinks -- book-level buy link repeater
 * Component of admin-repeater.js -- extracted Session 94.
 * Dependency: mbs-admin-repeater (namespace initializer), mbs-link-icon-helper.
 * @package MyBookShowroom
 */

// =============================================================================
// Buy Links Repeater
// =============================================================================

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

	MBS.BuyLinks = {

		/** @type {Object|null} MBS.SortableList instance for the buy links container. */
		_sortable: null,

		init: function() {
			this.bindSortable();
			this.bindAddRow();
			this.bindRemoveRow();
			this.bindLabelAutoFill();
		},

		/**
		 * Initialize sortable via MBS.SortableList factory.
		 * controlsSelector targets .mbs-buy-link-fallback span rendered by render_row().
		 * @returns {void}
		 */
		bindSortable: function() {
			var $rows = $( '#mbs-buy-links-rows' );
			if ( ! $rows.length ) { return; }

			if ( typeof MBS.SortableList !== 'undefined' ) {
				MBS.BuyLinks._sortable = MBS.SortableList.create( {
					container:        '#mbs-buy-links-rows',
					itemSelector:     '.mbs-buy-link-row',
					handleSelector:   '.mbs-drag-handle',
					controlsSelector: '.mbs-buy-link-fallback',
					upSelector:       '.mbs-reorder-move-up',
					downSelector:     '.mbs-reorder-move-down'
				} );
			} else {
				// MBS.SortableList unavailable -- show fallback arrows on all existing rows.
				$rows.find( '.mbs-drag-handle' ).hide();
				$rows.find( '.mbs-buy-link-fallback' ).show();
			}
		},

		/**
		 * Bind the Add Buy Link button.
		 * Clones the hidden template row, re-enables disabled inputs (A2-012),
		 * resets field values, toggles sort controls, and appends to container.
		 * @returns {void}
		 */
		bindAddRow: function() {
			$( document ).on( 'click', '.mbs-add-buy-link-row', function( e ) {
				e.preventDefault();
				var $container = $( '#mbs-buy-links-rows' );
				$container.find( '.mbs-no-rows-message' ).remove();

				// Clone .mbs-buy-link-row from within the hidden template div (Sprint 182).
				var $clone = $( '#buy-link-row-template .mbs-buy-link-row' ).clone().show();

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

				$clone.find( 'input[type="url"]' ).val( '' );
				$clone.find( 'input[type="hidden"]' ).val( '' );
				$clone.find( 'select' ).val( '' );

				if ( MBS.BuyLinks._sortable ) {
					var hasDrag = MBS.BuyLinks._sortable.usingDrag();
					$clone.find( '.mbs-buy-link-fallback' ).toggle( ! hasDrag );
					$clone.find( '.mbs-drag-handle' ).toggle( hasDrag );
				} else {
					var hasSortable = typeof $.fn.sortable !== 'undefined';
					$clone.find( '.mbs-buy-link-fallback' ).toggle( ! hasSortable );
					$clone.find( '.mbs-drag-handle' ).toggle( hasSortable );
				}

				$container.append( $clone );

				if ( MBS.BuyLinks._sortable ) { MBS.BuyLinks._sortable.refresh(); } // (A2-009)
			} );
		},

		/**
		 * Bind the Remove button on each buy link row.
		 * @returns {void}
		 */
		bindRemoveRow: function() {
			$( document ).on( 'click', '.mbs-remove-buy-link-row', function( e ) {
				e.preventDefault();
				if ( window.confirm( __( 'Remove this buy link?', 'my-book-showroom' ) ) ) {
					$( this ).closest( '.mbs-buy-link-row' ).remove();
				}
			} );
		},

		/**
		 * Auto-detect retailer key from URL and update label + icon on blur.
		 * Delegates to MBS.LinkIconHelper.applyDetection().
		 * defaultLabel is 'Buy Now' for buy link rows.
		 * @returns {void}
		 */
		bindLabelAutoFill: function() {
			$( document ).on( 'blur', '#mbs-buy-links-rows .mbs-buy-link-url', function() {
				var $row = $( this ).closest( '.mbs-buy-link-row' );
				var url  = $( this ).val();
				MBS.LinkIconHelper.applyDetection(
					$row, url,
					( window.MBS_ADMIN && window.MBS_ADMIN.retailersUrl ) ? window.MBS_ADMIN.retailersUrl : '',
					( window.MBS_ADMIN && window.MBS_ADMIN.siteIconUrl )  ? window.MBS_ADMIN.siteIconUrl  : '',
					'Buy Now'
				);
			} );
		}

	};

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

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