/**
 * assets/js/adminjs/admin-book-club.js
 *
 * Book Club Resources — Admin UI
 *
 * Handles three interactive UI features in the Book Club Resources metabox:
 *   1. Sortable question rows (jQuery UI Sortable, handle-only drag)
 *   2. Add / remove question rows dynamically
 *   3. WP media frame for file attachment picker with per-file label input
 *
 * Localized values injected via wp_localize_script( 'mbs-admin-book-club', 'mbsBookClub', {...} ).
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

( function ( $ ) {
	'use strict';

	var __ = wp.i18n.__;
	var escAttr = MBS_AdminUtils.escAttr;

	// __ Question rows _________________________________________________________

	/**
	 * Build a new question list-item element.
	 *
	 * @param {string} value Initial input value.
	 * @return {jQuery}
	 */
	function makeQuestionRow( value ) {
		value = value || '';

		var $li = $(
			'<li class="mbs-book-club-question-row"'
			+ ' style="display:flex;align-items:center;gap:8px;margin-bottom:6px;">'
			+ '<span class="dashicons dashicons-menu mbs-question-drag-handle"'
			+ ' style="cursor:grab;color:#aaa;flex-shrink:0;" aria-hidden="true"></span>'
			+ '<span class="mbs-question-fallback" style="display:none;flex-shrink:0;">'
			+ '<button type="button" class="button button-small mbs-question-move-up"'
			+ ' title="' + escAttr( __( 'Move up', 'my-book-showroom' ) ) + '" aria-label="' + escAttr( __( 'Move up', 'my-book-showroom' ) ) + '">&#9650;</button>'
			+ '<button type="button" class="button button-small mbs-question-move-down"'
			+ ' title="' + escAttr( __( 'Move down', 'my-book-showroom' ) ) + '" aria-label="' + escAttr( __( 'Move down', 'my-book-showroom' ) ) + '">&#9660;</button>'
			+ '</span>'
			+ '<input type="text" name="mbs_book_club_question[]"'
			+ ' class="regular-text" style="flex:1;" />'
			+ '<button type="button"'
			+ ' class="button button-small mbs-book-club-remove-question">'
			+ '<span class="dashicons dashicons-trash" aria-hidden="true"></span>'
			+ '</button>'
			+ '</li>'
		);

		$li.find( 'input' )
			.val( value )
			.attr( 'placeholder', __( 'Enter a discussion question…', 'my-book-showroom' ) );

		$li.find( 'button' )
			.attr( 'aria-label', __( 'Remove question', 'my-book-showroom' ) );

		return $li;
	}

	/** Initialize jQuery UI Sortable on the question list, with ▲▼ fallback. */
	function initQuestionSortable() {
		var $list = $( '#mbs-book-club-questions-list' );
		if ( ! $list.length ) {
			return;
		}

		if ( typeof $.fn.sortable !== 'undefined' ) {
			// Drag available — hide fallback buttons.
			$list.find( '.mbs-question-fallback' ).hide();
			$list.sortable( {
				handle:               '.mbs-question-drag-handle',
				axis:                 'y',
				placeholder:          'mbs-sortable-placeholder',
				forcePlaceholderSize: true,
				tolerance:            'pointer',
			} );
		} else {
			// No sortable — hide drag handles, reveal ▲▼ buttons.
			$list.find( '.mbs-question-drag-handle' ).hide();
			$list.find( '.mbs-question-fallback' ).show();
		}

		// ▲▼ click handlers (work regardless of sortable availability).
		$( document ).on( 'click', '.mbs-question-move-up', function () {
			var $row  = $( this ).closest( '.mbs-book-club-question-row' );
			var $prev = $row.prev( '.mbs-book-club-question-row' );
			if ( $prev.length ) { $row.insertBefore( $prev ); }
		} );

		$( document ).on( 'click', '.mbs-question-move-down', function () {
			var $row  = $( this ).closest( '.mbs-book-club-question-row' );
			var $next = $row.next( '.mbs-book-club-question-row' );
			if ( $next.length ) { $row.insertAfter( $next ); }
		} );
	}

	$( document ).on( 'click', '#mbs-book-club-add-question', function () {
		var $list        = $( '#mbs-book-club-questions-list' );
		var $row         = makeQuestionRow( '' );
		var hasSortable  = typeof $.fn.sortable !== 'undefined';
		$row.find( '.mbs-question-fallback' ).toggle( ! hasSortable );
		$row.find( '.mbs-question-drag-handle' ).toggle( hasSortable );
		$list.append( $row );
		// Notify jQuery UI Sortable about the new item (only if sortable was initialized).
		if ( hasSortable && $list.data( 'ui-sortable' ) ) {
			$list.sortable( 'refresh' );
		}
		$row.find( 'input' ).trigger( 'focus' );
	} );

	$( document ).on( 'click', '.mbs-book-club-remove-question', function () {
		$( this ).closest( '.mbs-book-club-question-row' ).remove();
	} );

	// __ File rows _____________________________________________________________

	var mediaFrame;

	/**
	 * Build a new file row element.
	 *
	 * @param {number} id       Attachment ID.
	 * @param {string} url      Attachment URL.
	 * @param {string} filename Display filename.
	 * @param {string} label    Pre-filled label value (empty string for new rows).
	 * @return {jQuery}
	 */
	function makeFileRow( id, url, filename, label ) {
		label    = label    || '';
		filename = filename || url.split( '/' ).pop();

		// Escape filename for display (prevent HTML injection from filename string).
		var safeFilename = $( '<span>' ).text( filename ).html();

		var $row = $(
			'<div class="mbs-book-club-file-row"'
			+ ' style="display:flex;align-items:center;gap:8px;margin-bottom:8px;'
			+ 'padding:8px;background:#fff;border:1px solid #ddd;border-radius:3px;">'
			+ '<span class="dashicons dashicons-media-default"'
			+ ' aria-hidden="true" style="flex-shrink:0;"></span>'
			+ '<input type="hidden" name="mbs_book_club_file_ids[]" />'
			+ '<div style="flex:1;min-width:0;">'
			+ '<a href="" target="_blank" rel="noopener"'
			+ ' style="display:block;font-size:12px;color:#666;margin-bottom:4px;'
			+ 'overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">'
			+ safeFilename
			+ '</a>'
			+ '<input type="text" name="mbs_book_club_file_labels[]" class="widefat" />'
			+ '</div>'
			+ '<button type="button"'
			+ ' class="button button-small mbs-book-club-remove-file"'
			+ ' style="flex-shrink:0;"></button>'
			+ '</div>'
		);

		$row.attr( 'data-id', id );
		$row.find( 'input[type="hidden"]' ).val( id );
		$row.find( 'a' ).attr( 'href', url );
		$row.find( 'input[type="text"]' )
			.val( label )
			.attr( 'placeholder', __( 'File label (optional, e.g. Discussion Guide PDF)', 'my-book-showroom' ) );
		$row.find( 'button' )
			.text( __( 'Remove', 'my-book-showroom' ) )
			.attr( 'aria-label', __( 'Remove file', 'my-book-showroom' ) );

		return $row;
	}

	$( document ).on( 'click', '#mbs-book-club-add-file', function () {
		if ( mediaFrame ) {
			mediaFrame.open();
			return;
		}

		mediaFrame = wp.media( {
			title:    __( 'Select Files for Book Club', 'my-book-showroom' ),
			button:   { text: __( 'Add File', 'my-book-showroom' ) },
			multiple: true,
			library:  { type: '' }, // All file types.
		} );

		mediaFrame.on( 'select', function () {
			mediaFrame.state().get( 'selection' ).each( function ( attachment ) {
				var a  = attachment.toJSON();
				var id = a.id;

				// Skip duplicates.
				if ( $( '#mbs-book-club-files-list [data-id="' + id + '"]' ).length ) {
					return;
				}

				var fn = a.filename || a.url.split( '/' ).pop();
				$( '#mbs-book-club-files-list' ).append( makeFileRow( id, a.url, fn, '' ) );
			} );
		} );

		mediaFrame.open();
	} );

	$( document ).on( 'click', '.mbs-book-club-remove-file', function () {
		$( this ).closest( '.mbs-book-club-file-row' ).remove();
	} );

	// __ Init __________________________________________________________________

	$( function () {
		// jQuery UI Sortable requires the container to be visible at init time so
		// it can correctly measure item offsets. The editor shell hides all panels
		// at DOMReady and then shows only the active tab. Using setTimeout(0) lets
		// the shell's own DOMReady handler run first.
		setTimeout( function () {
			var $list = $( '#mbs-book-club-questions-list' );
			if ( ! $list.length ) { return; }

			if ( $list.is( ':visible' ) ) {
				// Book Club tab is already active — init immediately.
				initQuestionSortable();
			} else {
				// Lazy-init: fire once the first time the tab is clicked.
				var sortableReady = false;
				$( document ).on( 'click.mbsBookClub', '[data-mbs-domain="book-club"]', function () {
					if ( sortableReady ) { return; }
					sortableReady = true;
					// setTimeout(0) lets the shell show the panel before we measure.
					setTimeout( initQuestionSortable, 0 );
				} );
			}
		}, 0 );
	} );

} )( jQuery );
