/**
 * @file assets/js/adminjs/admin-inline-edit.js
 * Quick-edit panel pre-population from mbs_book_data column; wraps inlineEditPost.edit() for each opened row.
 * @package MyBookShowroom
 * @since   1.0.0
 */

( function ( $ ) {
	'use strict';

	// Guard: inlineEditPost is only present on list-table screens.
	if ( typeof inlineEditPost === 'undefined' ) {
		return;
	}

	/**
	 * Map of term-data keys to their quick edit list element IDs.
	 * Series is handled separately (single-select, not a checklist).
	 */
	var TAX_MAP = {
		authors:     'mbs-qe-authors',
		tags:        'mbs-qe-tags',
		collections: 'mbs-qe-collections',
		universes:   'mbs-qe-universes',
		themes:      'mbs-qe-themes',
		warnings:    'mbs-qe-warnings',
	};

	// Wrap inlineEditPost.edit so we can inject our pre-population after
	// WordPress has finished rendering the panel.
	var originalEdit = inlineEditPost.edit;

	inlineEditPost.edit = function ( id ) {
		// Always call the original first.
		originalEdit.apply( this, arguments );

		// Resolve the post ID regardless of how WP called us.
		var postId = ( typeof id === 'object' )
			? parseInt( inlineEditPost.getId( id ), 10 )
			: parseInt( id, 10 );

		if ( ! postId ) {
			return;
		}

		// Find the hidden data span in the list-table row for this post.
		var $row  = $( '#post-' + postId );
		var $data = $row.find( '.mbs-inline-edit-data' );
		if ( ! $data.length ) {
			return;
		}

		// Parse the JSON term data.
		var terms;
		try {
			terms = JSON.parse( $data.attr( 'data-mbs-terms' ) || '{}' );
		} catch ( e ) {
			return;
		}

		// ── Series: single-select ────────────────────────────────────────────
		var $seriesSelect = $( '#mbs-qe-series' );
		if ( $seriesSelect.length && terms.series !== undefined ) {
			$seriesSelect.val( terms.series ? String( terms.series ) : '' );
		}

		// ── Series Position ────────────────────────────────────────────────────
		var $posInput = $( '#mbs-qe-series-position' );
		if ( $posInput.length ) {
			$posInput.val( terms.series_position || '' );
		}

		// ── Reading Order position (read-only display) ────────────────────
		var $roPos = $( '#mbs-qe-reading-order-pos' );
		if ( $roPos.length ) {
			$roPos.text( terms.reading_order_pos ? String( terms.reading_order_pos ) : '\u2014' );
		}

		// ── Flat taxonomy checkboxes ─────────────────────────────────────────
		$.each( TAX_MAP, function ( key, listId ) {
			var $list = $( '#' + listId );
			if ( ! $list.length ) {
				return; // continue $.each
			}

			// Uncheck all checkboxes in this list first.
			$list.find( 'input[type="checkbox"]' ).prop( 'checked', false );

			// Re-check the ones matching the book's current term IDs.
			var ids = Array.isArray( terms[ key ] ) ? terms[ key ] : [];
			$.each( ids, function ( i, termId ) {
				$list
					.find( 'input[type="checkbox"][value="' + parseInt( termId, 10 ) + '"]' )
					.prop( 'checked', true );
			} );
		} );
	};

	// When series dropdown changes in Quick Edit, clear the reading order display.
	// Position within the newly selected series is unknown client-side.
	$( document ).on( 'change', '#mbs-qe-series', function () {
		$( '#mbs-qe-reading-order-pos' ).text( '\u2014' );
	} );

} )( jQuery );
