( function ( $ ) {
	var deactivateUrl = '';
	var $modal = $( '#shc4wc-deactivation-feedback' );
	var $reason = $( '#shc4wc-deactivation-reason' );
	var $error = $modal.find( '.shc4wc-deactivation-feedback__error' );
	var $submit = $( '#shc4wc-deactivation-submit' );

	if ( ! $modal.length || typeof shc4wcDeactivationFeedback === 'undefined' ) {
		return;
	}

	function openModal( url ) {
		deactivateUrl = url;
		$reason.val( '' );
		$error.prop( 'hidden', true ).text( '' );
		$submit.prop( 'disabled', false ).text( shc4wcDeactivationFeedback.i18n.submit );
		$modal.removeAttr( 'hidden' ).attr( 'aria-hidden', 'false' ).addClass( 'is-visible' );
		$reason.trigger( 'focus' );
	}

	function closeModal() {
		$modal.removeClass( 'is-visible' ).attr( 'aria-hidden', 'true' ).attr( 'hidden', 'hidden' );
		deactivateUrl = '';
	}

	function goDeactivate() {
		if ( deactivateUrl ) {
			window.location.href = deactivateUrl;
		}
	}

	$( document ).on(
		'click',
		'tr[data-plugin="' + shc4wcDeactivationFeedback.pluginBasename + '"] .deactivate a',
		function ( event ) {
			event.preventDefault();
			openModal( $( this ).attr( 'href' ) );
		}
	);

	$modal.on( 'click', '[data-shc4wc-deactivation-close]', function () {
		closeModal();
	} );

	$modal.on( 'click', '[data-shc4wc-deactivation-skip]', function () {
		goDeactivate();
	} );

	$submit.on( 'click', function () {
		var reason = $.trim( $reason.val() );

		if ( ! reason ) {
			$error.prop( 'hidden', false ).text( shc4wcDeactivationFeedback.i18n.reasonRequired );
			$reason.trigger( 'focus' );
			return;
		}

		$error.prop( 'hidden', true ).text( '' );
		$submit.prop( 'disabled', true ).text( shc4wcDeactivationFeedback.i18n.submitting );

		$.post( shc4wcDeactivationFeedback.ajaxUrl, {
			action: 'shc4wc_deactivation_feedback',
			nonce: shc4wcDeactivationFeedback.nonce,
			reason: reason,
		} ).always( function () {
			goDeactivate();
		} );
	} );

	$( document ).on( 'keydown', function ( event ) {
		if ( event.key === 'Escape' && $modal.hasClass( 'is-visible' ) ) {
			closeModal();
		}
	} );
}( jQuery ) );
