/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

/**
 * Toggles the height of an element between 0 and its scrollHeight.
 * This is useful for creating collapsible sections.
 * @param {HTMLElement} element - The element to toggle.
 * @param {string} toggleClass - CSS class to add when the element is collapsed.
 * @returns {Promise} - A promise that resolves when setting properties is complete.
 */
export function toggleHeight( element, toggleClass ) {
	return new Promise( resolve => {
		// If no height is present, set it to the scrollHeight.
		if ( element.style.height === '' ) {
			element.style.height = element.scrollHeight + 'px';
		}

		setTimeout( () => {
			if ( element.style.height === '0px' ) {
				element.style.display = 'block';
				element.style.height = element.scrollHeight + 'px';
				element.classList.remove( toggleClass );

				// Remove the height property after the transition ends to allow for reflow.
				element.addEventListener( 'transitionend', () => {
					element.style.height = '';
					resolve( 'visible' );
				}, {
					once: true
				} );
			} else {
				element.style.height = '0px';
				element.classList.add( toggleClass );

				// Remove the height property after the transition ends to allow for reflow.
				element.addEventListener( 'transitionend', () => {
					resolve( 'hidden' );
				}, {
					once: true
				} );
			}
		}, 10 );
	} );
}
