( function ( $ ) {
	'use strict';

	$( document ).ready( function () {

		var $deactivateLink = $( 'tr[data-plugin="' + vserpb_deactivation.plugin_id + '"] .deactivate a' );

		if ( ! $deactivateLink.length ) {
			return;
		}

		var deactivateUrl = $deactivateLink.attr( 'href' );

		$deactivateLink.on( 'click', function ( e ) {
			e.preventDefault();
			$( '#vserpb-deactivation-overlay' ).fadeIn( 200 );
		} );

		// Enable Submit only when a reason is selected.
		$( 'input[name="vserpb_reason"]' ).on( 'change', function () {
			$( '#vserpb-submit-deactivate' ).prop( 'disabled', false );
		} );

		// Skip — no data sent.
		$( '#vserpb-skip-deactivate' ).on( 'click', function () {
			window.location.href = deactivateUrl;
		} );

		// Submit — send reason then deactivate.
		$( '#vserpb-submit-deactivate' ).on( 'click', function () {
			var $btn   = $( this );
			var reason = $( 'input[name="vserpb_reason"]:checked' ).val();

			$btn.prop( 'disabled', true ).text( 'Sending\u2026' );

			$.post(
				vserpb_deactivation.ajax_url,
				{
					action: 'vserpb_deactivation_feedback',
					nonce:  vserpb_deactivation.nonce,
					reason: reason,
				},
				function () {
					window.location.href = deactivateUrl;
				}
			).fail( function () {
				window.location.href = deactivateUrl;
			} );
		} );

		// Close on overlay click.
		$( '#vserpb-deactivation-overlay' ).on( 'click', function ( e ) {
			if ( $( e.target ).is( '#vserpb-deactivation-overlay' ) ) {
				$( '#vserpb-deactivation-overlay' ).fadeOut( 200 );
			}
		} );

	} );

} )( jQuery );
