( function () {
	'use strict';

	var config = window.dsmDiviCacheClear;

	if ( ! config || ! config.ajaxUrl || ! config.action || ! config.nonce ) {
		return;
	}

	var strings = config.strings || {};
	var scopes = Array.isArray( config.scopes ) ? config.scopes : [];
	var isRunning = false;

	function getAdminBarLink() {
		return document.querySelector(
			'#wp-admin-bar-dsm-clear-divi-cache > a.ab-item'
		);
	}

	function setAdminBarLabel( text ) {
		var link = getAdminBarLink();

		if ( link ) {
			link.textContent = text;
		}
	}

	function restoreAdminBarLabel( originalText ) {
		window.setTimeout( function () {
			setAdminBarLabel( originalText );
		}, 3000 );
	}

	function findScopeItem( scopeId ) {
		for ( var i = 0; i < scopes.length; i += 1 ) {
			if ( scopes[ i ].scope === scopeId ) {
				return scopes[ i ];
			}
		}

		return null;
	}

	function getSuccessMessage( scopeId, serverMessage ) {
		if ( serverMessage ) {
			return serverMessage;
		}

		if ( scopeId === 'post' ) {
			return strings.successPost || strings.successAll || strings.success;
		}

		if ( scopeId === 'home' ) {
			return strings.successHome || strings.successAll || strings.success;
		}

		return strings.successAll || strings.success || 'Divi static cache cleared.';
	}

	function requestClear( scopeId, postId, onDone ) {
		if ( isRunning ) {
			return;
		}

		isRunning = true;

		var body = new URLSearchParams( {
			action: config.action,
			nonce: config.nonce,
			scope: scopeId || 'all',
		} );

		if ( postId ) {
			body.set( 'post_id', String( postId ) );
		}

		fetch( config.ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded',
			},
			body: body.toString(),
		} )
			.then( function ( response ) {
				return response.json();
			} )
			.then( function ( json ) {
				onDone( json );
			} )
			.catch( function () {
				onDone( { success: false } );
			} )
			.finally( function () {
				isRunning = false;
			} );
	}

	document.addEventListener( 'click', function ( event ) {
		var target = event.target;

		if ( ! ( target instanceof Element ) ) {
			return;
		}

		var scopeLink = target.closest(
			'[id^="wp-admin-bar-dsm-clear-divi-cache-"] > a.ab-item'
		);

		if ( ! scopeLink ) {
			var rootLink = target.closest(
				'#wp-admin-bar-dsm-clear-divi-cache > a.ab-item'
			);

			if ( rootLink ) {
				event.preventDefault();
			}

			return;
		}

		event.preventDefault();

		var scopeNode = scopeLink.closest( '[id^="wp-admin-bar-dsm-clear-divi-cache-"]' );

		if ( ! scopeNode || ! scopeNode.id ) {
			return;
		}

		var scopeId = scopeNode.id.replace(
			'wp-admin-bar-dsm-clear-divi-cache-',
			''
		);
		var scopeItem = findScopeItem( scopeId );
		var postId = scopeItem && scopeItem.post_id ? scopeItem.post_id : 0;
		var originalText =
			strings.parentLabel ||
			getAdminBarLink()?.textContent ||
			'Clear Divi Cache';

		setAdminBarLabel( strings.clearing || 'Clearing…' );

		requestClear( scopeId, postId, function ( json ) {
			if ( json && json.success ) {
				var message =
					json.data && json.data.deferred
						? strings.deferred || json.data.message
						: getSuccessMessage(
								scopeId,
								json.data && json.data.message
							);

				setAdminBarLabel( message || originalText );
				restoreAdminBarLabel( originalText );

				return;
			}

			var errorMessage =
				( json && json.data && json.data.message ) ||
				strings.error ||
				'Could not clear Divi static cache.';

			setAdminBarLabel( errorMessage );
			restoreAdminBarLabel( originalText );
		} );
	} );
} )();
