/**
 * @file assets/js/mbs-front-wc.js
 * S15-4: WooCommerce cart price update on format tab switch.
 *
 * When the user selects a different book format, updates the displayed price
 * in the .mbs-wc-add-to-cart section to match the selected format price.
 * No product record in the database is modified -- display only.
 * Loaded only on WooCommerce-active installs.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

/* global jQuery */

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

	/**
	 * WooCommerce price display sync on format tab change.
	 *
	 * @namespace MBS.WCPriceUpdate
	 */
	MBS.WCPriceUpdate = {

		/**
		 * Bind format tab click listener.
		 *
		 * @return {void}
		 */
		init: function() {
			if ( ! $( '.mbs-wc-add-to-cart' ).length ) {
				return;
			}

			$( document ).on( 'click', '.mbs-format-tab', function() {
				var $tab      = $( this );
				var $selector = $tab.closest( '.mbs-format-selector' );
				var formats   = $selector.data( 'mbs-formats' );

				if ( ! formats ) {
					return;
				}

				var rowId  = parseInt( $tab.data( 'format-row-id' ), 10 );
				var entry  = null;

				for ( var i = 0; i < formats.length; i++ ) {
					if ( parseInt( formats[ i ].format_row_id, 10 ) === rowId ) {
						entry = formats[ i ];
						break;
					}
				}

				if ( ! entry ) {
					return;
				}

				// Update the displayed price -- DOM text only, no DB write.
				var $priceEl = $( '.mbs-wc-product-price' );
				if ( $priceEl.length && entry.price ) {
					$priceEl.text( entry.price );
				}
			} );
		}
	};

	MBS.register( function() {
		MBS.WCPriceUpdate.init();
	} );

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