( function ( $ ) {
	$( document ).on( 'click', '.shc4wc-onboarding-enable-gateway', function ( event ) {
		event.preventDefault();

		var $btn = $( this );
		var $notice = $btn.closest( '.shc4wc-onboarding-step__content' ).find( '.shc4wc-onboarding-gateway-notice' );
		var label = $btn.text();

		$btn.prop( 'disabled', true ).text( shc4wcOnboarding.i18n.enabling );
		$notice.removeClass( 'is-success is-error' ).text( '' );

		$.post( shc4wcOnboarding.ajaxUrl, {
			action: 'shc4wc_onboarding_enable_gateway',
			nonce: shc4wcOnboarding.nonce,
		} )
			.done( function ( res ) {
				if ( res && res.success ) {
					$notice.addClass( 'is-success' ).text( res.data && res.data.message ? res.data.message : shc4wcOnboarding.i18n.enabled );
					$btn.hide();
					setTimeout( function () {
						window.location.reload();
					}, 800 );
				} else {
					$notice.addClass( 'is-error' ).text( shc4wcOnboarding.i18n.failed );
					$btn.prop( 'disabled', false ).text( label );
				}
			} )
			.fail( function () {
				$notice.addClass( 'is-error' ).text( shc4wcOnboarding.i18n.failed );
				$btn.prop( 'disabled', false ).text( label );
			} );
	} );

	$( document ).on( 'click', '.shc4wc-ai-troubleshoot-btn', function ( event ) {
		event.preventDefault();

		var $btn = $( this );
		var $panel = $btn.closest( '.shc4wc-onboarding-ai-panel' );
		var $response = $panel.find( '.shc4wc-onboarding-ai-response' );
		var $question = $panel.find( '#shc4wc-ai-question' );
		var label = $btn.text();
		var question = $question.val() ? String( $question.val() ).trim() : '';

		if ( ! question ) {
			$response.removeAttr( 'hidden' ).addClass( 'is-error' ).html( '<p>' + shc4wcOnboarding.i18n.aiFailed + '</p>' );
			return;
		}

		$btn.prop( 'disabled', true ).text( shc4wcOnboarding.i18n.aiLoading );
		$response.removeAttr( 'hidden' ).removeClass( 'is-error' ).html( '<p>' + shc4wcOnboarding.i18n.aiLoading + '</p>' );

		$.post( shc4wcOnboarding.ajaxUrl, {
			action: 'shc4wc_ai_troubleshoot',
			nonce: shc4wcOnboarding.aiNonce,
			question: question,
			oauth_status: shc4wcOnboarding.oauthStatus || '',
		} )
			.done( function ( res ) {
				if ( res && res.success && res.data && res.data.answer ) {
					$response.removeClass( 'is-error' ).html( '<div class="shc4wc-ai-answer">' + res.data.answer + '</div>' );
				} else {
					$response.addClass( 'is-error' ).html( '<p>' + shc4wcOnboarding.i18n.aiFailed + '</p>' );
				}
			} )
			.fail( function ( xhr ) {
				var msg = shc4wcOnboarding.i18n.aiFailed;
				if ( xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message ) {
					msg = xhr.responseJSON.data.message;
				}
				$response.addClass( 'is-error' ).html( '<p>' + msg + '</p>' );
			} )
			.always( function () {
				$btn.prop( 'disabled', false ).text( label );
			} );
	} );
}( jQuery ) );
