/**
 * @file assets/js/adminjs/admin-section-order.js
 * Section display-order drag-and-drop with jQuery UI Sortable and ↑/↓ arrow fallback for the Formatting tab.
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

	var __ = wp.i18n.__;

	MBS.SectionOrder = {

		init: function () {
			this.bindSortable();
			this.bindArrows();
			this.bindReset();
		},

		// ── Drag-and-drop (primary) ─────────────────────────────────────────

		bindSortable: function () {
			var $list    = $( '#mbs-section-sortable' );
			var $details = $( '.mbs-section-order-fallback' );

			if ( typeof $.fn.sortable !== 'undefined' && $list.length &&
			     $list.find( '.mbs-drag-handle' ).length ) {

				// PRO: DnD active -- hide and disable the details/arrow fallback.
				$details.hide();
				// FE-007: prevent hidden details checkboxes from submitting with form.
				$details.find( 'input[type="checkbox"]' ).prop( 'disabled', true );

				$list.sortable( {
					handle:    '.mbs-drag-handle',
					items:     'li',
					axis:      'y',
					tolerance: 'pointer',
					update: function () {
						MBS.SectionOrder.syncTableFromList();
						MBS.SectionOrder.updateHidden();
					}
				} );

			} else {

				// FREE / no-JS: show only the arrow table; hide the sortable list.
				$list.hide();
				// FE-007: prevent hidden list checkboxes from submitting with form.
				$list.find( 'input[type="checkbox"]' ).prop( 'disabled', true );

				// Show the arrow table directly (same approach as mbs-book-editor.js).
				// Setting <details>.open alone is not reliable in WP admin — direct
				// .show() on the table overrides any browser <details> hidden state.
				$( '#mbs-section-order-table' ).show();
				if ( $details.length ) {
					$details.attr( 'open', '' );
				}
			}
		},

		// ── Up/Down arrow fallback (inside <details>) ───────────────────────

		bindArrows: function () {
			// Guard: only bind on the Formatting tab. On the Book Editor,
			// mbs-book-editor.js already handles .mbs-up/.mbs-down on
			// #mbs-section-order-body. Without this guard, both handlers fire on
			// each click after BUG-SORT-006 shows the table for FREE users, causing
			// the row to move twice. .mbs-section-order-fallback is rendered only
			// by class-mbs-tab-formatting-render.php, never by the metabox.
			if ( ! $( '.mbs-section-order-fallback' ).length ) {
				return;
			}
			$( '#mbs-section-order-body' ).on( 'click', '.mbs-up, .mbs-down', function () {
				var $row = $( this ).closest( 'tr' );
				if ( $( this ).hasClass( 'mbs-up' ) ) {
					var $prev = $row.prev( 'tr' );
					if ( $prev.length ) {
						$row.insertBefore( $prev );
					}
				} else {
					var $next = $row.next( 'tr' );
					if ( $next.length ) {
						$row.insertAfter( $next );
					}
				}
				MBS.SectionOrder.syncListFromTable();
				MBS.SectionOrder.updateHidden();
			} );
		},

		// ── Reset to canonical default order ────────────────────────────────

		bindReset: function () {
			$( '.mbs-reset-order' ).on( 'click', function () {
				if ( ! window.confirm( __( 'Reset section order to default?', 'my-book-showroom' ) ) ) {
					return;
				}

				// UX-EDIT-002 Phase 0-E: canonical default order injected via
				// wp_localize_script (mbsSectionOrderData) -- single source of truth
				// is MBS_Section_Helper::get_canonical_keys(). Hardcoded list removed.
				var defaultOrder = ( window.mbsSectionOrderData && window.mbsSectionOrderData.defaultOrder )
					? window.mbsSectionOrderData.defaultOrder
					: [];

				// Reorder <ul> items by moving existing elements (preserves i18n text).
				var $list      = $( '#mbs-section-sortable' );
				var itemsBySlug = {};
				$list.find( 'li' ).each( function () {
					itemsBySlug[ $( this ).data( 'slug' ) ] = $( this );
				} );
				$.each( defaultOrder, function ( i, slug ) {
					if ( itemsBySlug[ slug ] ) {
						$list.append( itemsBySlug[ slug ] );
					}
				} );

				// Reorder <tbody> rows by moving existing elements.
				var $body      = $( '#mbs-section-order-body' );
				var rowsBySlug = {};
				$body.find( 'tr' ).each( function () {
					rowsBySlug[ $( this ).data( 'slug' ) ] = $( this );
				} );
				$.each( defaultOrder, function ( i, slug ) {
					if ( rowsBySlug[ slug ] ) {
						$body.append( rowsBySlug[ slug ] );
					}
				} );

				MBS.SectionOrder.updateHidden();
			} );
		},

		// ── Sync helpers ────────────────────────────────────────────────────

		/**
		 * After a drag, reorder the <tbody> rows to match the <ul> order.
		 * Keeps the arrow-table fallback consistent if the user expands it.
		 */
		syncTableFromList: function () {
			var $list  = $( '#mbs-section-sortable' );
			var $body  = $( '#mbs-section-order-body' );
			var order  = [];
			$list.find( 'li' ).each( function () {
				order.push( $( this ).data( 'slug' ) );
			} );
			var rowsBySlug = {};
			$body.find( 'tr' ).each( function () {
				rowsBySlug[ $( this ).data( 'slug' ) ] = $( this );
			} );
			$.each( order, function ( i, slug ) {
				if ( rowsBySlug[ slug ] ) {
					$body.append( rowsBySlug[ slug ] );
				}
			} );
		},

		/**
		 * After an arrow-button move, reorder the <ul> items to match the table.
		 */
		syncListFromTable: function () {
			var $body  = $( '#mbs-section-order-body' );
			var $list  = $( '#mbs-section-sortable' );
			var order  = [];
			$body.find( 'tr' ).each( function () {
				order.push( $( this ).data( 'slug' ) );
			} );
			var itemsBySlug = {};
			$list.find( 'li' ).each( function () {
				itemsBySlug[ $( this ).data( 'slug' ) ] = $( this );
			} );
			$.each( order, function ( i, slug ) {
				if ( itemsBySlug[ slug ] ) {
					$list.append( itemsBySlug[ slug ] );
				}
			} );
		},

		/**
		 * Write the current order (from whichever widget is active) into the
		 * hidden input so it submits with the Settings form.
		 */
		updateHidden: function () {
			var $list   = $( '#mbs-section-sortable' );
			var $hidden = $( '#mbs_section_order_input' );
			var order   = [];

			if ( $list.length && $list.is( ':visible' ) ) {
				$list.find( 'li' ).each( function () {
					order.push( $( this ).data( 'slug' ) );
				} );
			} else {
				$( '#mbs-section-order-body' ).find( 'tr' ).each( function () {
					order.push( $( this ).data( 'slug' ) );
				} );
			}

			$hidden.val( order.join( ',' ) );
		}
	};

	$( document ).ready( function () {
		MBS.SectionOrder.init();
	} );

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