( function () {
	'use strict';

	function resetLink( link ) {
		link.removeAttribute( 'aria-busy' );
		link.removeAttribute( 'aria-disabled' );
		link.style.pointerEvents = '';
	}

	function handleAction( event ) {
		var link = event.target.closest( 'a[data-action]' );
		if ( ! link ) {
			return;
		}

		var action = link.getAttribute( 'data-action' );
		if ( 'snooze' !== action && 'dismiss' !== action ) {
			return;
		}

		event.preventDefault();
		if ( 'true' === link.getAttribute( 'aria-busy' ) ) {
			return;
		}

		var config = window.seovaultseo_action_center || {};
		if ( ! config.ajax_url || ! config.nonce ) {
			return;
		}

		link.setAttribute( 'aria-busy', 'true' );
		link.setAttribute( 'aria-disabled', 'true' );
		link.style.pointerEvents = 'none';

		var body = new URLSearchParams();
		body.append( 'action', 'seovaultseo_notice_response' );
		body.append( 'nonce', config.nonce );
		body.append( 'notice_action', action );

		fetch( config.ajax_url, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
			},
			body: body.toString(),
			credentials: 'same-origin'
		} )
			.then( function ( response ) {
				if ( ! response.ok ) {
					throw new Error( 'Action Center request failed.' );
				}
				return response.json();
			} )
			.then( function ( response ) {
				if ( ! response || ! response.success ) {
					throw new Error( 'Action Center response was unsuccessful.' );
				}

				var item = link.closest( '.seovaultseo-action-center__item' );
				if ( item ) {
					item.remove();
				}
			} )
			.catch( function () {
				resetLink( link );
			} );
	}

	function init() {
		var centers = document.querySelectorAll( '.seovaultseo-action-center' );
		for ( var i = 0; i < centers.length; i++ ) {
			centers[ i ].addEventListener( 'click', handleAction );
		}
	}

	if ( 'loading' === document.readyState ) {
		document.addEventListener( 'DOMContentLoaded', init );
	} else {
		init();
	}
} )();
