/**
 * Sifency Addons Plugin Installer
 *
 * Handles AJAX requests for installing and activating recommended plugins.
 *
 * @since 1.0.4
 */
(function ($) {
	'use strict';

	$(document).ready(function () {
		const installer = {
			// Cache the main container element
			container: $('.sifency-installer-cards-container'),

			/**
			 * Initialize the installer functionality.
			 */
			init: function () {
				if (this.container.length) {
					this.bindEvents();
				}
			},

			/**
			 * Binds all necessary event listeners.
			 */
			bindEvents: function () {
				// Use event delegation for buttons that might be added dynamically
				this.container.on('click', '.plugin-action-btn', this.handleButtonClick.bind(this));
			},

			/**
			 * Handles the click event on an action button.
			 * @param {Event} e The click event.
			 */
			handleButtonClick: function (e) {
				e.preventDefault();
				
				const $button = $(e.currentTarget);

				// Prevent multiple clicks while an action is processing
				if ($button.hasClass('disabled') || $button.hasClass('processing')) {
					return;
				}

				// Get plugin data from the button's data attributes
				const pluginData = {
					slug: $button.data('slug'),
					mainFile: $button.data('mainfile'),
					action: $button.data('action'),
				};

				if (!pluginData.slug || !pluginData.action) {
					console.error('Missing plugin data on the button.');
					return;
				}
				
				this.setButtonState($button, 'processing');
				this.performAjaxRequest($button, pluginData);
			},

			/**
			 * Performs the AJAX request to install or activate a plugin.
			 * @param {jQuery} $button The button that was clicked.
			 * @param {object} pluginData The data for the plugin to be actioned.
			 */
			performAjaxRequest: function ($button, pluginData) {
				const originalText = $button.find('.btn-text').text();

				$.ajax({
					url: sifencyInstaller.ajax_url,
					type: 'POST',
					dataType: 'json',
					data: {
						action: 'sifency_install_plugin', // WP AJAX action hook
						nonce: sifencyInstaller.nonce,
						task: pluginData.action,          // 'install' or 'activate'
						slug: pluginData.slug,
						main_file: pluginData.mainFile
					},
					success: (response) => {
						if (response.success) {
							// On success, update the button to the 'Activated' state
							this.setButtonState($button, 'activated');
						} else {
							// On failure, show an error and revert the button
							alert('Error: ' + response.data.message);
							this.setButtonState($button, 'error', originalText);
						}
					},
					error: (xhr) => {
						// On a network or server error, alert the user
						alert(sifencyInstaller.texts.error);
						console.error('AJAX Error:', xhr.responseText);
						this.setButtonState($button, 'error', originalText);
					}
				});
			},
			
			/**
			 * Updates the button's appearance and state.
			 * @param {jQuery} $button The button to update.
			 * @param {string} state The new state: 'processing', 'activated', or 'error'.
			 * @param {string} [originalText] The original button text, needed for error state.
			 */
			setButtonState: function ($button, state, originalText = '') {
				const $btnText = $button.find('.btn-text');
				const action = $button.data('action');

				$button.removeClass('processing').prop('disabled', false);

				switch (state) {
					case 'processing':
						$button.addClass('processing').prop('disabled', true);
						if (action === 'install') {
							$btnText.text(sifencyInstaller.texts.installing);
						} else {
							$btnText.text(sifencyInstaller.texts.activating);
						}
						break;
						
					case 'activated':
						$button.removeClass('install-btn activate-btn').addClass('activated-btn disabled').prop('disabled', true);
						$button.data('action', ''); // Clear action
						$btnText.text(sifencyInstaller.texts.activated);
						break;
						
					case 'error':
						$button.prop('disabled', false);
						$btnText.text(originalText);
						break;
				}
			}
		};

		// Initialize the installer logic
		installer.init();
	});

})(jQuery);