/**
 * Elementor frontend handler — Product Description widget.
 *
 * Drives the optional "read more" clamp: the description is collapsed to a fixed
 * height and a toggle button expands/collapses it. If the content already fits
 * within the collapsed height the button is removed entirely.
 *
 * @package captain-widgets-kit
 * @since   1.4.0
 */
( function ( $, window, document ) {
	'use strict';

	/**
	 * Per-instance handler.
	 *
	 * @param {HTMLElement} root Widget wrapper (.captwiki-pdesc).
	 */
	function setupInstance( root ) {
		if ( ! root || root.captwikiPdescReady ) {
			return;
		}
		root.captwikiPdescReady = true;

		var content = root.querySelector( '.captwiki-pdesc__content' );
		var toggle  = root.querySelector( '.captwiki-pdesc__toggle' );

		if ( ! content || ! toggle ) {
			return;
		}

		var collapsed = parseInt( root.getAttribute( 'data-collapsed-height' ), 10 ) || 160;
		var moreText  = toggle.getAttribute( 'data-more' ) || toggle.textContent;
		var lessText  = toggle.getAttribute( 'data-less' ) || moreText;

		// Content already short enough — no clamp needed.
		if ( content.scrollHeight <= collapsed + 4 ) {
			root.classList.remove( 'is-clamped' );
			toggle.style.display = 'none';
			content.style.maxHeight = '';
			return;
		}

		root.classList.add( 'is-clamped' );
		content.style.maxHeight = collapsed + 'px';
		toggle.textContent = moreText;
		toggle.setAttribute( 'aria-expanded', 'false' );

		toggle.addEventListener( 'click', function () {
			var expanded = root.classList.toggle( 'is-expanded' );

			if ( expanded ) {
				content.style.maxHeight = content.scrollHeight + 'px';
				toggle.textContent = lessText;
				toggle.setAttribute( 'aria-expanded', 'true' );
			} else {
				content.style.maxHeight = collapsed + 'px';
				toggle.textContent = moreText;
				toggle.setAttribute( 'aria-expanded', 'false' );
				root.scrollIntoView( { block: 'nearest', behavior: 'smooth' } );
			}
		} );
	}

	if ( typeof jQuery !== 'undefined' ) {
		$( window ).on( 'elementor/frontend/init', function () {
			if ( window.elementorFrontend && elementorFrontend.hooks ) {
				elementorFrontend.hooks.addAction(
					'frontend/element_ready/captwiki-woo-product-description.default',
					function ( $scope ) {
						setupInstance( $scope[ 0 ].querySelector( '.captwiki-pdesc' ) || $scope[ 0 ] );
					}
				);
			}
		} );
	}

	document.addEventListener( 'DOMContentLoaded', function () {
		document.querySelectorAll( '.captwiki-pdesc' ).forEach( setupInstance );
	} );

} )( window.jQuery, window, document );
