/**
 * Captain Widgets Kit – Button Widget JS
 * File: assets/js/widgets/button/captwiki-button.js
 *
 * Responsibilities:
 *  - Tooltip: show/hide on hover & focus for accessibility
 *  - Keyboard: Enter/Space on <a role="button"> acts as click
 *
 * Architecture: event delegation — ONE listener on document.
 * No jQuery. Loaded only when captwiki-button widget is active.
 *
 * @since 1.2.0
 */
( function () {
	'use strict';

	/* ── Tooltip via event delegation ────────────────────── */

	/**
	 * Update tooltip ARIA visibility.
	 *
	 * @param {HTMLElement} btn
	 * @param {boolean}     visible
	 */
	function setTooltipVisible( btn, visible ) {
		const tip = btn.querySelector( '.cw-btn-tooltip' );
		if ( ! tip ) {
			return;
		}
		tip.setAttribute( 'aria-hidden', visible ? 'false' : 'true' );
	}

	/* Mouseenter / focus → show */
	document.addEventListener( 'mouseenter', function ( e ) {
		const btn = e.target.closest( '.cw-btn--has-tooltip' );
		if ( btn ) {
			setTooltipVisible( btn, true );
		}
	}, true );

	document.addEventListener( 'focusin', function ( e ) {
		const btn = e.target.closest( '.cw-btn--has-tooltip' );
		if ( btn ) {
			setTooltipVisible( btn, true );
		}
	} );

	/* Mouseleave / blur → hide */
	document.addEventListener( 'mouseleave', function ( e ) {
		const btn = e.target.closest( '.cw-btn--has-tooltip' );
		if ( btn ) {
			setTooltipVisible( btn, false );
		}
	}, true );

	document.addEventListener( 'focusout', function ( e ) {
		const btn = e.target.closest( '.cw-btn--has-tooltip' );
		if ( btn ) {
			setTooltipVisible( btn, false );
		}
	} );

	/* Escape key closes tooltip */
	document.addEventListener( 'keydown', function ( e ) {
		if ( 'Escape' === e.key ) {
			document.querySelectorAll( '.cw-btn--has-tooltip' ).forEach( function ( btn ) {
				setTooltipVisible( btn, false );
				btn.blur();
			} );
		}
	} );

	/* ── Keyboard activation for <a role="button"> ────────── */
	document.addEventListener( 'keydown', function ( e ) {
		if ( 'Enter' === e.key || ' ' === e.key ) {
			const btn = e.target.closest( '.cw-btn[role="button"]' );
			if ( btn ) {
				e.preventDefault();
				btn.click();
			}
		}
	} );

} )();
