( function( $ ) {
	$( document ).on( 'click', '.ap773pro-reset-to-cm', function() {
		var $btn   = $( this );
		var role   = $btn.data( 'role' );
		var label  = $btn.data( 'label' );

		if ( ! confirm(
			'' + (window.pnlrdbRoles ? window.pnlrdbRoles.i18n.reset : '') + '' + ' ' + label +
			' ' + (window.pnlrdbRoles ? window.pnlrdbRoles.i18n.resetConfirmSuffix : '') + ''
		) ) { return; }

		$btn.prop( 'disabled', true ).text( '' + (window.pnlrdbRoles ? window.pnlrdbRoles.i18n.resetting : '') + '' );

		$.post( ajaxurl, {
			action: 'pnlrdbpro_reset_role_to_cm',
			nonce:  '' + (window.pnlrdbRoles ? window.pnlrdbRoles.nonce : '') + '',
			role:   role
		}, function( res ) {
			if ( ! res.success ) {
				alert( '' + (window.pnlrdbRoles ? window.pnlrdbRoles.i18n.error : '') + '' );
				$btn.prop( 'disabled', false ).text( '' + (window.pnlrdbRoles ? window.pnlrdbRoles.i18n.resetToPreset : '') + '' );
				return;
			}

			// Update checkboxes based on the returned preset
			var preset  = res.data.preset;
			var $card   = $btn.closest( '.ap773-role-card' );

			$card.find( 'input[type="checkbox"]' ).each( function() {
				var val     = $( this ).val();
				var checked = preset.indexOf( val ) !== -1;
				$( this ).prop( 'checked', checked );
			} );

			$btn.prop( 'disabled', false ).text( '' + (window.pnlrdbRoles ? window.pnlrdbRoles.i18n.resetToPreset : '') + '' );

			// Visual feedback
			$btn.css( 'color', '#15803d' ).text( '✓ ' + (window.pnlrdbRoles ? window.pnlrdbRoles.i18n.done : '') + '' );
			setTimeout( function() {
				$btn.css( 'color', '#6366f1' ).text( '' + (window.pnlrdbRoles ? window.pnlrdbRoles.i18n.resetToPreset : '') + '' );
			}, 2000 );
		} );
	} );
} )( jQuery );
