/**
 * @file assets/js/adminjs/repeater/mbs-reader-platforms.js
 * MBS.ReaderPlatforms -- Reader Platforms sortable repeater.
 * Manages add/remove rows, URL-based auto-detection of platform label and icon,
 * and drag-sort via MBS.SortableList.
 *
 * Depends on: mbs-sortable-list.js (MBS.SortableList).
 * @package MyBookShowroom
 */

// =============================================================================
// Reader Platforms Repeater
// =============================================================================

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

	MBS.ReaderPlatforms = {

		_sortable: null,

		/**
		 * Initialize the Reader Platforms repeater.
		 * @returns {void}
		 */
		init: function() {
			this.bindSortable();
			this.bindAddRow();
			this.bindRemoveRow();
			this.bindUrlAutoDetect();
			this.scanExistingRows();
		},

		/**
		 * Initialize sortable via MBS.SortableList factory.
		 * @returns {void}
		 */
		bindSortable: function() {
			var $rows = $( '#mbs-reader-platforms-rows' );
			if ( ! $rows.length ) {
				return;
			}

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

		/**
		 * Bind the Add Platform button.
		 * Clones the hidden template row, resets its fields, and appends it.
		 * @returns {void}
		 */
		bindAddRow: function() {
			$( document ).on( 'click', '.mbs-add-platform-row', function( e ) {
				e.preventDefault();

				var $container = $( '#mbs-reader-platforms-rows' );
				// Clone .mbs-platform-row from within the template div (Sprint 182).
				var $template  = $( '#reader-platform-row-template .mbs-platform-row' ).clone().show();

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

				// New rows have no DB record yet -- hide ALL sort controls until after save.
				$template.find( '.mbs-platform-fallback' ).hide();
				$template.find( '.mbs-drag-handle' ).hide();

				$container.append( $template );

				// Re-initialize sortable so the new row gets the drag binding.
				if ( MBS.ReaderPlatforms._sortable ) {
					MBS.ReaderPlatforms._sortable.refresh();
				}
			} );
		},

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

		/**
		 * Auto-detect platform key and label from URL on blur.
		 * Only fills label when the label field is currently empty.
		 * Updates icon preview to branded SVG when key is recognized.
		 * @returns {void}
		 */
		bindUrlAutoDetect: function() {
			$( document ).on( 'blur', '#mbs-reader-platforms-rows .mbs-platform-url', function() {
				var $row = $( this ).closest( '.mbs-platform-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  : '',
					''
				);
			} );
		},

		/**
		 * Scan rows already rendered on page load (DB-populated values).
		 * Fills label if empty and updates icon preview for any row that
		 * already has a URL. Runs once during init().
		 * @returns {void}
		 */
		scanExistingRows: function() {
			$( '#mbs-reader-platforms-rows .mbs-platform-row' ).each( function() {
				var $row = $( this );
				var url  = $row.find( '.mbs-platform-url' ).val();
				if ( ! url ) {
					return; // skip empty-URL rows
				}
				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  : '',
					''
				);
			} );
		},



	};

	$( function() {
		if ( $( '#mbs-reader-platforms-repeater' ).length ) {
			MBS.ReaderPlatforms.init();
		}
	} );

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