document.addEventListener( 'DOMContentLoaded', function() {
	const button = document.querySelector( '[data-wira-setup-action="install"]' );
	const activateButton = document.querySelector( '[data-wira-setup-action="activate"]' );
	const setupButton = button || activateButton;

	if ( ! setupButton || ! window.wp || ! wp.ajax || ! window.WiraSetupData ) {
		return;
	}

	setupButton.addEventListener( 'click', function( event ) {
		event.preventDefault();

		if ( setupButton.disabled ) {
			return;
		}

		const originalText = setupButton.textContent;
		const action = setupButton.getAttribute( 'data-wira-setup-action' );

		setupButton.disabled = true;
		setupButton.textContent = WiraSetupData.labels.processing;

		const redirectToSetup = function() {
			window.location.href = WiraSetupData.openUrl;
		};

		const activatePlugin = function() {
			wp.ajax.post( 'activate-plugin', {
				_wpnonce: WiraSetupData.installNonce,
				slug: WiraSetupData.pluginSlug,
				plugin: WiraSetupData.pluginFile,
				name: WiraSetupData.pluginName,
			} ).done( redirectToSetup ).fail( function() {
				setupButton.disabled = false;
				setupButton.textContent = originalText;
				window.alert( WiraSetupData.labels.failed );
			} );
		};

		if ( 'activate' === action ) {
			activatePlugin();
			return;
		}

		wp.ajax.post( 'install-plugin', {
			_wpnonce: WiraSetupData.installNonce,
			slug: WiraSetupData.pluginSlug,
		} ).done( function( response ) {
			if ( response && response.activateUrl ) {
				activatePlugin();
				return;
			}

			redirectToSetup();
		} ).fail( function() {
			setupButton.disabled = false;
			setupButton.textContent = originalText;
			window.alert( WiraSetupData.labels.failed );
		} );
	} );
} );
