/**
 * Responsive tabs burger menu — close on tab selection.
 * Inline onclick is stripped by wp_kses on the frontend, so this is the
 * reliable close path (capture-phase, once per document).
 */

/**
 * @param {ParentNode|null|undefined} tabsRoot
 */
export function closeBmTabsMenu( tabsRoot ) {
	const check = tabsRoot?.querySelector?.( '.bm-tabs__menu-check' );
	if ( check ) {
		check.checked = false;
	}
}

/**
 * @param {Event} event
 */
function onClickCapture( event ) {
	const target = event.target;
	if ( ! target || typeof target.closest !== 'function' ) {
		return;
	}
	const label = target.closest( '.bm-tabs__label' );
	if ( ! label ) {
		return;
	}
	const root = label.closest( '.bm-tabs' );
	if ( ! root?.querySelector?.( '.bm-tabs__menu-check' ) ) {
		return;
	}
	// Let the radio activate first, then collapse the floating menu.
	requestAnimationFrame( () => {
		closeBmTabsMenu( root );
	} );
}

/**
 * Bind once per document (or iframe document).
 *
 * @param {Document} [doc]
 */
export function initBmTabsNav( doc = document ) {
	if ( ! doc || doc.__bmTabsNavBound ) {
		return;
	}
	doc.__bmTabsNavBound = true;
	doc.addEventListener( 'click', onClickCapture, true );
}
