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

import $ from 'jquery';

export function enableDropdowns() {
	const activeClass = 'dropdown--active';
	const doc = $( document );

	$( '.dropdown__button' ).each( function( index, button ) {
		const dropdown = $( button ).parent();

		$( button ).on( 'click', toggleDropdown );

		function startListening() {
			doc.on( 'click', closeDropdownOnClick );
			doc.on( 'keyup', closeDropdownOnEsc );
		}

		function stopListening() {
			doc.off( 'click', closeDropdownOnClick );
			doc.off( 'keyup', closeDropdownOnEsc );
		}

		function closeDropdownOnClick( evt ) {
			const target = evt.target;

			if ( !( dropdown.has( target ).length || dropdown.is( target ) ) ) {
				dropdown.removeClass( activeClass );

				stopListening();
			}
		}

		function closeDropdownOnEsc( evt ) {
			if ( evt.keyCode === 27 ) {
				dropdown.removeClass( activeClass );

				stopListening();
			}
		}

		function toggleDropdown() {
			dropdown.toggleClass( activeClass );

			if ( dropdown.hasClass( activeClass ) ) {
				startListening();
			} else {
				stopListening();
			}
		}
	} );
}
