/**
 * 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 = {
			container: $('.sifency-installer-cards-container'),

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

			/**
			 * Binds all necessary event listeners.
			 */
			bindEvents: function () {
				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);

				if ($button.hasClass('disabled') || $button.hasClass('processing')) {
					return;
				}

				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',
						nonce: sifencyInstaller.nonce,
						task: pluginData.action,
						slug: pluginData.slug,
						main_file: pluginData.mainFile
					},
					success: (response) => {
						if (response.success) {
							this.setButtonState($button, 'activated');
						} else {
							alert('Error: ' + response.data.message);
							this.setButtonState($button, 'error', originalText);
						}
					},
					error: (xhr) => {
						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', '');
						$btnText.text(sifencyInstaller.texts.activated);
						break;
						
					case 'error':
						$button.prop('disabled', false);
						$btnText.text(originalText);
						break;
				}
			}
		};

		installer.init();
	});

})(jQuery);