/**
 * WordPress dependencies
 */
import apiFetch from '@wordpress/api-fetch';

/**
 * Callback function
 *
 * @return {void}
 */
const callback = () => {
	// Get the object to action on.
	const notice = document.getElementById( 'careers__admin_notice' );
	const dismissButton = notice?.querySelector( 'button.notice-dismiss' );

	if ( ! notice || ! dismissButton ) {
		return;
	}

	// Get the nonce value.
	const nonce = notice.dataset.nonce;

	/**
	 * Action taken on click of the dismiss button
	 *
	 * @return {void}
	 */
	const onClick = () => {
		apiFetch( {
			path: '/careers/v1/admin-notice',
			method: 'POST',
			data: {
				nonce,
			},
		} );

		dismissButton.removeEventListener( 'click', onClick );
	};

	/**
	 * Dismiss the notice
	 *
	 * @return {void}
	 */
	dismissButton.addEventListener( 'click', onClick );
};

/**
 * Queue a callback function to be called during a browser's
 * idle periods so the main thread is not blocked
 */
if ( window.requestIdleCallback instanceof Function ) {
	window.requestIdleCallback( callback );
} else {
	setTimeout( callback, 0 );
}
