/**
 * WP Blog Agent – KI-Überarbeitung (Post Editor Integration)
 *
 * Works in both Gutenberg and Classic Editor.
 * Uses the existing wbag_revise_post AJAX endpoint.
 *
 * @since 1.3.29
 */
(function ($) {
	'use strict';

	$(function () {
		var $btn    = $('#wbag-editor-revise-btn');
		var $input  = $('#wbag-editor-revise-input');
		var $status = $('#wbag-editor-revise-status');
		var config  = window.wbag_editor_revise || {};

		if (!$btn.length || !config.ajax_url) {
			return;
		}

		$btn.on('click', function () {
			var instructions = $.trim($input.val());

			if (!instructions) {
				$status.css('color', '#d63638').text(config.i18n.empty);
				$input.focus();
				return;
			}

			// Disable UI during request.
			$btn.prop('disabled', true);
			$input.prop('disabled', true);
			$status.css('color', '#2271b1').text(config.i18n.working);

			$.ajax({
				url:      config.ajax_url,
				method:   'POST',
				dataType: 'json',
				timeout:  300000, // 5 min – Claude can be slow on long articles
				data: {
					action:       'wbag_revise_post',
					nonce:        config.nonce,
					post_id:      config.post_id,
					instructions: instructions
				},
				success: function (response) {
					if (response.success) {
						$status.css('color', '#00a32a').text(config.i18n.success);

						// Reload the editor after a short delay so WP picks up the updated content.
						setTimeout(function () {
							window.location.reload();
						}, 1500);
					} else {
						var msg = (response.data && response.data.message) ? response.data.message : 'Unbekannter Fehler';
						$status.css('color', '#d63638').text(config.i18n.error + msg);
						$btn.prop('disabled', false);
						$input.prop('disabled', false);
					}
				},
				error: function (xhr, textStatus) {
					var msg = textStatus === 'timeout' ? 'Zeitüberschreitung – bitte erneut versuchen.' : 'Netzwerkfehler.';
					$status.css('color', '#d63638').text(config.i18n.error + msg);
					$btn.prop('disabled', false);
					$input.prop('disabled', false);
				}
			});
		});

		// Allow Ctrl+Enter to submit.
		$input.on('keydown', function (e) {
			if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
				e.preventDefault();
				$btn.trigger('click');
			}
		});
	});
})(jQuery);
