/**
 * @file assets/js/mbs-front-look-inside.js
 * Read-more / collapse toggle for the Look Inside section.
 *
 * Reads translated labels from data-more and data-less attributes on the
 * toggle button (set by PHP esc_attr_e() in tab-look-inside.php).
 * Loaded only on singular book pages with Look Inside content.
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

/* global jQuery */

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

	/**
	 * Read-more / collapse toggle for the Look Inside panel.
	 *
	 * @namespace MBS.LookInsideReadMore
	 */
	MBS.LookInsideReadMore = {

		MAX_HEIGHT_PX: 480,

		/**
		 * Bind toggle click and tab-activation listeners; run initial setup.
		 *
		 * @return {void}
		 */
		init: function() {
			var self = this;
			$( document ).on( 'click', '.mbs-look-inside-toggle', this.toggle );
			this.setup(); // handles case where look-inside is the default active tab
		},

		/**
		 * Collapse long Look Inside bodies on page load and tab reveal.
		 *
		 * @return {void}
		 */
		setup: function() {
			$( '.mbs-look-inside-body' ).each( function() {
				var $body = $( this );
				// Skip elements already expanded by the user -- do not re-collapse.
				if ( $body.attr( 'data-expanded' ) === 'true' ) { return; }
				if ( $body.find( '.mbs-look-inside-text' ).outerHeight()
						> MBS.LookInsideReadMore.MAX_HEIGHT_PX ) {
					$body.addClass( 'mbs-look-inside-collapsed' );
					$body.next( '.mbs-look-inside-toggle' ).show();
				}
			} );
		},

		/**
		 * Toggle the read-more / collapse state on button click.
		 *
		 * @return {void}
		 */
		toggle: function() {
			var $btn     = $( this );
			var $body    = $btn.prev( '.mbs-look-inside-body' );
			var expanded = $body.attr( 'data-expanded' ) === 'true';
			$body.attr( 'data-expanded', expanded ? 'false' : 'true' );
			$body.toggleClass( 'mbs-look-inside-collapsed', expanded );
			$btn.text( expanded ? $btn.data( 'more' ) : $btn.data( 'less' ) );
		}
	};

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

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