/**
 * @file assets/js/mbs-format-tabs.js
 * Front-end format selector — updates cover, price, buy links, and metadata on format button click; no AJAX.
 * @package MyBookShowroom
 * @since   1.0.0
 */

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

	/**
	 * Parse formats payload from the selector wrapper's data attribute.
	 * Returns array of format objects, or [] if missing / malformed.
	 *
	 * @param  {jQuery} $selector  The .mbs-format-selector element.
	 * @return {Array}
	 */
	function parseFormats( $selector ) {
		try {
			return JSON.parse( $selector.attr( 'data-mbs-formats' ) || '[]' );
		} catch ( e ) {
			return [];
		}
	}

	/**
	 * Find a format object by format_row_id.
	 *
	 * @param  {Array}  formats
	 * @param  {number} rowId
	 * @return {Object|null}
	 */
	function findFormat( formats, rowId ) {
		return formats.find( function( f ) { return f.format_row_id === rowId; } ) || null;
	}

	/**
	 * Update the per-format metadata block (#mbs-per-format-details) to
	 * reflect the supplied format object.
	 *
	 * @param {Object} fmt  Format data object from the JSON payload.
	 */
	function updateMeta( fmt ) {
		// Subtitle — show/hide the entire row
		var $subWrap = $( '.mbs-per-format-subtitle' );
		var $subSpan = $( '#mbs-format-subtitle' );
		if ( fmt.subtitle ) {
			$subSpan.text( fmt.subtitle );
			$subWrap.show();
		} else {
			$subWrap.hide();
		}

		// Price
		var $priceRow = $( '.mbs-meta-price' );
		var $priceSpan = $( '#mbs-format-price' );
		if ( fmt.price ) {
			$priceSpan.text( fmt.price );
			$priceRow.show();
		} else {
			$priceRow.hide();
		}

		// ISBN-13
		var $isbnRow = $( '.mbs-meta-isbn13' );
		var $isbn13Span = $( '#mbs-format-isbn13' );
		if ( fmt.isbn13 ) {
			$isbn13Span.text( fmt.isbn13 );
			// ISBN-10: only shown when payload carries a pre-computed isbn10 key
			// (set by server when show_isbn10 setting is on); otherwise hidden.
			var $isbn10Wrap = $( '.mbs-isbn10-wrap' );
			var $isbn10Span = $( '#mbs-format-isbn10' );
			if ( fmt.isbn10 ) {
				$isbn10Span.text( fmt.isbn10 );
				$isbn10Wrap.show();
			} else {
				$isbn10Wrap.hide();
			}
			$isbnRow.show();
		} else {
			$isbnRow.hide();
		}

		// Page length (non-audiobook formats)
		var $pageRow = $( '.mbs-meta-page-length' );
		var $pageSpan = $( '#mbs-format-page-length' );
		var $durRow   = $( '.mbs-meta-duration' );
		var $durSpan  = $( '#mbs-format-duration' );

		if ( fmt.format === 'audiobook' ) {
			$pageRow.hide();
			if ( fmt.duration_hh !== null && fmt.duration_hh !== undefined ) {
				var hh = String( fmt.duration_hh ).padStart( 2, '0' );
				var mm = String( fmt.duration_mm !== null ? fmt.duration_mm : 0 ).padStart( 2, '0' );
				$durSpan.text( hh + ':' + mm );
				$durRow.show();
			} else {
				$durRow.hide();
			}
		} else {
			$durRow.hide();
			if ( fmt.page_length ) {
				$pageSpan.text( fmt.page_length );
				$pageRow.show();
			} else {
				$pageRow.hide();
			}
		}
	}

	/**
	 * Update the book cover image src to reflect the selected format's cover.
	 * Scoped to the hero cover within the same .mbs-book-hero container as the
	 * format selector — prevents overwriting shelf/series/author book covers.
	 * Falls back gracefully if no cover_url is provided.
	 *
	 * @param {Object} fmt       Format data object.
	 * @param {jQuery} $selector The .mbs-format-selector element (used for scoping).
	 */
	function updateCover( fmt, $selector ) {
		if ( ! fmt.cover_url ) {
			return;
		}
		var $hero   = $selector ? $selector.closest( '.mbs-book-hero' ) : $();
		var $target = $hero.length
			? $hero.find( '.mbs-book-hero-cover .mbs-cover img, .mbs-book-hero-cover .mbs-cover-img' )
			: $( '.mbs-book-hero-cover .mbs-cover img, .mbs-book-hero-cover .mbs-cover-img' ).first();
		$target.attr( 'src', fmt.cover_url );
	}

	/**
	 * Initialize format tab switching on all .mbs-format-selector instances
	 * on the page (typically only one on single book pages).
	 */
	function init() {
		$( '.mbs-format-selector' ).each( function() {
			var $selector = $( this );
			var formats   = parseFormats( $selector );

			if ( ! formats.length ) {
				return;
			}

			// Activate the first tab on load.
			var $tabs = $selector.find( '.mbs-format-tab' );
			if ( $tabs.length ) {
				$tabs.first().addClass( 'active' );
				var firstId  = parseInt( $tabs.first().data( 'format-row-id' ), 10 );
				var firstFmt = findFormat( formats, firstId );
				if ( firstFmt ) {
					updateCover( firstFmt, $selector );
					updateMeta( firstFmt );
					$( document ).trigger( 'mbs:format:changed', [ firstFmt ] );
				}
			}

			// Tab click handler.
			$tabs.on( 'click', function() {
				$tabs.removeClass( 'active' );
				$( this ).addClass( 'active' );

				var rowId = parseInt( $( this ).data( 'format-row-id' ), 10 );
				var fmt   = findFormat( formats, rowId );
				if ( ! fmt ) {
					return;
				}

				updateCover( fmt, $selector );
				updateMeta( fmt );

				// Emit a custom event so other components (Amazon Reviews §9,
				// Goodreads share §6) can react to the format change.
				$( document ).trigger( 'mbs:format:changed', [ fmt ] );
			} );
		} );
	}

	// -----------------------------------------------------------------------
	// Amazon Reviews format-aware switching (Step 7)
	// Listens for mbs:format:changed and shows the matching panel.
	// If the active format has no ASIN, the entire section is hidden.
	// -----------------------------------------------------------------------

	$( document ).on( 'mbs:format:changed', function( e, fmt ) {
		var $section = $( '#mbs-amazon-reviews-section' );
		if ( ! $section.length ) {
			return;
		}

		var rowId = fmt.format_row_id;

		// Hide all panels first.
		$section.find( '.mbs-amazon-reviews-panel' ).hide();

		if ( ! fmt.asin ) {
			// Active format has no ASIN — hide the entire section (GP-UI-1).
			$section.hide();
			return;
		}

		// Find the panel matching this format row.
		var $panel = $section.find( '.mbs-amazon-reviews-panel[data-format-row-id="' + rowId + '"]' );

		if ( $panel.length ) {
			$section.show();
			$panel.show();
		} else {
			// No reviews for this format's ASIN — hide section (GP-UI-1).
			$section.hide();
		}
	} );

	// Trigger on initial load to sync with the default (first) active format.
	$( function() {
		init();
	} );

})( jQuery );
