/**
 * Limb Chatbot Deactivation Feedback Modal
 *
 * Handles the deactivation feedback popup when user tries to deactivate the plugin.
 *
 * @package Limb_Chatbot
 * @since 1.0.9
 */
(function ($) {
	'use strict';

	const LbaicDeactivationFeedback = {
		/**
		 * Initialize the deactivation feedback functionality
		 */
		init: function () {
			// lbaicDeactivation is defined via wp_localize_script
			if ( typeof lbaicDeactivation === 'undefined' ) {
				return;
			}

			this.deactivateLink = $('tr[data-plugin="' + lbaicDeactivation.pluginBasename + '"] .deactivate a');
			this.modal = $('#lbaic-deactivation-modal');
			this.form = $('#lbaic-deactivation-form');
			this.submitBtn = $('#lbaic-deactivation-submit');
			this.skipBtn = $('#lbaic-deactivation-skip');
			this.closeBtn = $('.lbaic-deactivation-modal-close');
			this.deactivateUrl = '';

			this.bindEvents();
		},

		/**
		 * Bind event handlers
		 */
		bindEvents: function () {
			const self = this;

			// Intercept deactivation click
			this.deactivateLink.on('click', function (e) {
				e.preventDefault();
				self.deactivateUrl = $(this).attr('href');
				self.openModal();
			});

			// Submit button click
			this.submitBtn.on('click', function (e) {
				e.preventDefault();
				self.submitFeedback();
			});

			// Skip button click
			this.skipBtn.on('click', function (e) {
				e.preventDefault();
				self.submitFeedback(true); // true = skip
			});

			// Close button click
			this.closeBtn.on('click', function (e) {
				e.preventDefault();
				self.closeModal();
			});

			// Update button state/visibility when radio selection changes
			this.form.on('change', 'input[name="lbaic_deactivation_reason"]', function () {
				const reason = $(this).val();
				const otherTextarea = self.form.find('textarea[name="lbaic_deactivation_reason_other"]');

				if (reason === 'other') {
					otherTextarea.show();
				} else {
					otherTextarea.hide();
				}
			});

			// Close on overlay click
			this.modal.on('click', function (e) {
				if ($(e.target).hasClass('lbaic-deactivation-modal-overlay')) {
					self.closeModal();
				}
			});

			// Close on escape key
			$(document).on('keyup', function (e) {
				if (e.key === 'Escape' && self.modal.is(':visible')) {
					self.closeModal();
				}
			});
		},

		/**
		 * Open the modal dialog
		 */
		openModal: function () {
			this.modal.show();
			this.form.find('input[type="radio"]').prop('checked', false);
			this.form.find('textarea').hide().val(''); // Reset and hide textareas
		},

		/**
		 * Close the modal dialog
		 */
		closeModal: function () {
			this.modal.hide();
		},

		/**
		 * Submit feedback and deactivate
		 * @param {boolean} skip Whether to skip feedback
		 */
		submitFeedback: function (skip = false) {
			const self = this;
			let reason = 'no_reason';
			let additionalDetails = '';

			if (!skip) {
				const selectedReason = this.form.find('input[name="lbaic_deactivation_reason"]:checked').val();
				if (selectedReason) {
					reason = selectedReason;
				}
				// Get additional details if 'other' is selected
				if (reason === 'other') {
					additionalDetails = this.form.find('textarea[name="lbaic_deactivation_reason_other"]').val();
				}
			}

			const data = {
				site_url: lbaicDeactivation.siteUrl,
				site_mode: lbaicDeactivation.siteMode,
				reason: reason,
				additional_details: additionalDetails,
				date: new Date().toISOString()
			};

			// Disable buttons during submission
			this.submitBtn.prop('disabled', true);
			this.skipBtn.prop('disabled', true);
			this.submitBtn.addClass('updating-message');

			// Submit via REST API (backend will forward to external API)
			$.ajax({
				url: lbaicDeactivation.restUrl + 'plugin/deactivation',
				method: 'POST',
				data: JSON.stringify(data),
				contentType: 'application/json',
				beforeSend: function (xhr) {
					xhr.setRequestHeader('X-WP-Nonce', lbaicDeactivation.nonce);
				},
				timeout: 5000, // 5 second timeout
				complete: function () {
					// Always deactivate regardless of success/failure
					window.location.href = self.deactivateUrl;
				}
			});
		}
	};

	// Initialize on document ready
	$(document).ready(function () {
		LbaicDeactivationFeedback.init();
	});

})(jQuery);
