/**
 * File: assets/js/adminjs/mbs-admin-social-links.js
 *
 * Add-as-you-go social platform UI.
 *
 * Responsibilities:
 *   - Init MBS.SortableList on each .mbs-social-sortable list.
 *   - Search/filter platform picker buttons by label text.
 *   - Add a platform row when a picker button is clicked.
 *   - Remove a row when the remove button is clicked.
 *   - Sync the hidden JSON input before submit.
 *   - Custom platform: prompt for name + URL.
 *
 * Depends on: jquery, mbs-sortable-list.
 * @since 1.4.0 Migrated to MBS.SortableList factory (was manual jQuery UI Sortable).
 */
/* global jQuery */
( function ( $ ) {
	'use strict';
	var __ = wp.i18n.__;
	var sprintf = wp.i18n.sprintf;

	// ── Sync hidden JSON input ─────────────────────────────────────────────────
	function syncJson( $section ) {
		var links = [];
		$section.find( '.mbs-social-row' ).each( function () {
			var $row     = $( this );
			var platform = $row.data( 'platform' );
			var url      = $.trim( $row.find( '.mbs-social-url-input' ).val() );
			if ( ! url ) { return; } // skip blank URLs
			var entry    = { platform: platform, url: url };
			if ( 'custom' === platform ) {
				var customLabel = $.trim( $row.find( '.mbs-social-custom-label-input' ).val() );
				if ( customLabel ) { entry.label = customLabel; }
			}
			links.push( entry );
		} );
		$section.find( '.mbs-social-links-json' ).val( JSON.stringify( links ) );
	}

	// ── Build a new sortable row ──────────────────────────────────────────────
	function buildRow( platform, label, placeholder, abbr ) {
		var isCustom = ( 'custom' === platform );
		// Canonical drag handle (mbs-drag-handle) and up/down fallback (mbs-reorder-controls).
		// Visibility toggled by MBS.SortableList after init; starts visible.
		var $handle   = $( '<span class="mbs-drag-handle dashicons dashicons-menu" aria-hidden="true" />' )
			.attr( 'title', __( 'Drag to reorder', 'my-book-showroom' ) );
		var $fallback = $( '<div class="mbs-reorder-controls" />' )
			.append(
				$( '<button type="button" class="button-link mbs-reorder-move-up" />' )
					.attr( { title: __( 'Move up', 'my-book-showroom' ), 'aria-label': __( 'Move up', 'my-book-showroom' ) } )
					.append( $( '<span class="dashicons dashicons-arrow-up-alt2" aria-hidden="true" />' ) ),
				$( '<button type="button" class="button-link mbs-reorder-move-down" />' )
					.attr( { title: __( 'Move down', 'my-book-showroom' ), 'aria-label': __( 'Move down', 'my-book-showroom' ) } )
					.append( $( '<span class="dashicons dashicons-arrow-down-alt2" aria-hidden="true" />' ) )
			);
		var $li = $( '<li class="mbs-social-row" />' )
			.attr( 'data-platform', platform )
			.append(
				$handle,
				$fallback,
				$( '<span class="mbs-social-icon" />' )
					.addClass( 'mbs-social-icon-' + platform )
					.text( abbr ),
				$( '<span class="mbs-social-row-label" />' ).text( isCustom ? __( 'Custom', 'my-book-showroom' ) : label ),
				$( '<input type="url" class="mbs-social-url-input" />' )
					.attr( { placeholder: placeholder, 'aria-label': sprintf( __( '%s URL', 'my-book-showroom' ), label ) } )
			);
		if ( isCustom ) {
			$li.append(
				$( '<input type="text" class="mbs-social-custom-label-input" />' )
					.attr( { placeholder: __( 'Platform name', 'my-book-showroom' ), 'aria-label': __( 'Custom platform name', 'my-book-showroom' ) } )
			);
		}
		$li.append(
			$( '<button type="button" class="mbs-social-remove-btn button-link" />' )
				.attr( { 'data-platform': platform, 'aria-label': sprintf( __( 'Remove %s', 'my-book-showroom' ), label ) } )
				.html( '&#10005;' )
		);
		return $li;
	}

	// ── Init one section ──────────────────────────────────────────────────────
	function initSection( $section ) {

		var $list = $section.find( '.mbs-social-sortable' );

		// MBS.SortableList handles drag-and-drop (when available) and up/down fallback.
		var sortable = MBS.SortableList.create( {
			container:        $list,
			itemSelector:     '.mbs-social-row',
			handleSelector:   '.mbs-drag-handle',
			controlsSelector: '.mbs-reorder-controls',
			upSelector:       '.mbs-reorder-move-up',
			downSelector:     '.mbs-reorder-move-down',
			placeholderClass: 'mbs-sortable-placeholder',
			onReorder: function() { syncJson( $section ); }
		} );

		// Picker search
		$section.on( 'input', '.mbs-social-picker-search', function () {
			var term = $( this ).val().toLowerCase();
			$section.find( '.mbs-social-picker-btn' ).each( function () {
				var label = $( this ).data( 'label' ) || $( this ).text();
				var match = label.toLowerCase().indexOf( term ) !== -1;
				$( this ).toggle( match );
			} );
			// Hide empty groups
			$section.find( '.mbs-social-picker-group' ).each( function () {
				var anyVisible = $( this ).find( '.mbs-social-picker-btn:visible' ).length > 0;
				$( this ).toggle( anyVisible );
			} );
		} );

		// Add platform
		$section.on( 'click', '.mbs-social-picker-btn:not(:disabled)', function () {
			var $btn      = $( this );
			var platform  = $btn.data( 'platform' );
			var label     = $btn.data( 'label' )       || 'Custom';
			var plh       = $btn.data( 'placeholder' ) || 'https://...';
			var abbr      = $btn.data( 'abbr' )        || '?';

			var $row = buildRow( platform, label, plh, abbr );
			$list.append( $row );
			sortable.refresh();

			// Custom: allow multiple — don't disable the button
			if ( 'custom' !== platform ) {
				$btn.prop( 'disabled', true )
				    .attr( 'aria-pressed', 'true' )
				    .addClass( 'mbs-social-picker-btn--added' );
			}

			// Hide empty state
			$section.find( '.mbs-social-empty-state' ).hide();

			syncJson( $section );
			$row.find( '.mbs-social-url-input' ).trigger( 'focus' );
		} );

		// Remove platform
		$section.on( 'click', '.mbs-social-remove-btn', function () {
			var $row     = $( this ).closest( '.mbs-social-row' );
			var platform = $row.data( 'platform' );

			// Re-enable picker button (non-custom only)
			if ( 'custom' !== platform ) {
				$section.find( '.mbs-social-picker-btn[data-platform="' + platform + '"]' )
					.prop( 'disabled', false )
					.attr( 'aria-pressed', 'false' )
					.removeClass( 'mbs-social-picker-btn--added' );
			}

			$row.remove();

			// Show empty state if no rows remain
			if ( $list.find( '.mbs-social-row' ).length === 0 ) {
				$section.find( '.mbs-social-empty-state' ).show();
			}

			syncJson( $section );
		} );

		// Sync on URL / custom-label change (debounced)
		var syncTimer;
		$section.on( 'input', '.mbs-social-url-input, .mbs-social-custom-label-input', function () {
			clearTimeout( syncTimer );
			var $s = $section;
			syncTimer = setTimeout( function () { syncJson( $s ); }, 250 );
		} );

		// Final sync on form submit (belt-and-suspenders)
		$section.closest( 'form' ).on( 'submit', function () {
			syncJson( $section );
		} );
	}

	// ── Init all sections on DOM ready ────────────────────────────────────────
	$( function () {
		$( '.mbs-author-social-section' ).each( function () {
			initSection( $( this ) );
		} );
	} );

} )( jQuery );
