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

/**
 * Wire dismissal of a WordPress admin notice to a REST endpoint
 *
 * Looks up the notice by DOM ID, finds the core `button.notice-dismiss`
 * element WordPress adds for dismissible notices, and on click POSTs
 * the nonce (read from the notice's `data-nonce` attribute) to the
 * caller-provided REST path. The click listener is detached before
 * the network call so a rapid double-click cannot fire two requests;
 * on failure it's re-attached so a subsequent click can retry.
 *
 * Defers to `requestIdleCallback` (falling back to `setTimeout( …, 0 )`)
 * so notice wiring never blocks the main thread during admin init.
 *
 * @param {Object}                  options             Wiring options.
 * @param {string}                  options.noticeId    DOM `id` of the notice container element.
 * @param {string}                  options.dismissPath REST path to POST to (e.g. `/plugin-slug/v1/dismiss-notice`).
 * @param {Object<string,unknown>=} options.extraData   Additional payload merged into the POST body alongside `nonce`.
 *
 * @return {void}
 */
export const wireAdminNoticeDismissal = ( { noticeId, dismissPath, extraData = {} } ) => {
	const callback = () => {
		const notice = document.getElementById( noticeId );
		const dismissButton = notice?.querySelector( 'button.notice-dismiss' );

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

		const nonce = notice.dataset.nonce;

		if ( ! nonce ) {
			return;
		}

		const onClick = async () => {
			dismissButton.removeEventListener( 'click', onClick );

			try {
				await apiFetch( {
					path: dismissPath,
					method: 'POST',
					data: { ...extraData, nonce },
				} );
			} catch ( error ) {
				// eslint-disable-next-line no-console -- Surfacing the failure in the console keeps the dismissal flow debuggable without forcing every caller to provide an onError handler.
				console.error( `Failed to dismiss admin notice "${ noticeId }":`, error );
				dismissButton.addEventListener( 'click', onClick );
			}
		};

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

	if ( 'function' === typeof window.requestIdleCallback ) {
		window.requestIdleCallback( callback );
	} else {
		window.setTimeout( callback, 0 );
	}
};
