(function (window) {
	window.Pluginer = window.Pluginer || {};


	var $pluginName = jQuery('#plugin_name');
	var $pluginSlug = jQuery('#plugin_slug');
	var $addButton = jQuery('#add_plugin_button');
	var $cancelButton = jQuery('#cancel_add_plugin_button');
	var $clearButton = jQuery('#clear_found_plugins');
	var $emptyListButton = jQuery('#empty_plugin_list_button');

	Pluginer.toggleButtons = function () {
		var enabled = jQuery.trim($pluginName.val()) !== '' && jQuery.trim($pluginSlug.val()) !== '';
		$addButton.prop('disabled', !enabled);
		$cancelButton.prop('disabled', !enabled);
		var clear_enabled = jQuery(".plugin_found_data").length > 0;;
		$clearButton.prop('disabled', !clear_enabled);
		var empty_enabled = jQuery("#plugins-list-table .table-body .table-row").length > 0;
		$emptyListButton.prop('disabled', !empty_enabled);
	}

	$clearButton.on('click', function (e) {
		e.preventDefault();
		jQuery("#plugins_result_list").find(".plugin_found_data").remove();
		Pluginer.updatePaginationButtons(1, false, 0);
		Pluginer.toggleButtons();
	})

	$emptyListButton.on('click', function (e) {
		e.preventDefault();
		Swal.fire({
			titleText: "Warning!",
			html: "Are you sure you want to empty the plugin list (he only way to undone is to exit without saving)?",
			showDenyButton: true,
			showCancelButton: false,
			confirmButtonText: "Yes",
			denyButtonText: "No",
			icon:"warning",
		}).then((result) => {
			if (result.isConfirmed) {
				jQuery("#plugins-list-table .table-body").empty();
				Pluginer.toggleButtons();
				markPostAsDirty();
			}
		});
	})

	Pluginer.updatePaginationButtons = function (currentPage, hasMorePages, totalPages) {
		jQuery("#load_prev_plugins").prop("disabled", currentPage === 1);
		jQuery("#load_next_plugins").prop("disabled", !hasMorePages);
		// Aggiorna il contatore delle pagine (es: "Pag. 1 di 10")
		if (totalPages) {
			jQuery("#pagination_info").text(`Page ${currentPage} of ${totalPages}`);
		} else {
			jQuery("#pagination_info").text(`Page ${currentPage}`);
		}
	}

	Pluginer.togglePluginsOverlay = function (visible) {
		if (visible) {
			jQuery("body").append(
				'<div id="plugins-overlay" class="plgnr-page-overlay"><div class="process-feedback"></div></div>'
			);
			jQuery('.process-feedback').empty().append('<div class="process-feedback-header"><h2>Processing plugin list...</h2><p>Please, be patient: this process could take some minutes.</p><p style="font-size:.9rem">In some rare cases, a plugin may not activate as expected (for example if it has missing dependencies, handles its own deactivation, or due to network issues).<br>Pluginer tries to catch these situations and display the proper feedback. If a plugin doesn’t activate automatically, you can always enable it manually from the Plugins page.<br>This doesn’t affect the main benefit: installing and activating multiple plugins with Pluginer is still much faster than the traditional method.</p></div><div class="process-feedback-body"></div><div class="process-feedback-footer"><div class="plgnr-progressbar-wrapper"><div id="plgnr-progress-bar"></div></div><div class="plgnr-button-wrapper cancel-button"><button class="plgnr-button" id="plgnr-cancel-button">Cancel</button></div></div>');
			jQuery("#plugins-overlay").addClass("plgnr-overlay-visible");
		} else {
			jQuery("#plugins-overlay").removeClass("plgnr-overlay-visible");
			jQuery("body").remove(jQuery("#plugins-overlay"));
		}
	}

	Pluginer.togglePlugins2Overlay = function (visible) {
		if (visible) {
			// jQuery('html, body').animate({ scrollTop: '0px' }, 300);
			jQuery("#plugins_result_list").append(
				'<div id="plugins2-overlay" class="plgnr-page-overlay"><div id="loader-container"><div class="plgsspinner"></div></div></div>'
			);
			jQuery("#plugins2-overlay").addClass("plgnr-overlay-visible");
		} else {
			jQuery("#plugins2-overlay").removeClass("plgnr-overlay-visible");
			jQuery("plugins_result_list").remove(jQuery("#plugins2-overlay"));
		}
	}

	Pluginer.toggleOverlay = function (visible) {
		console.log('toggleOverlay ' + visible);
		if (visible) {
			jQuery('html, body').animate({ scrollTop: '0px' }, 300);
			jQuery("body").append(
				'<div id="plgnr-global-overlay" class="plgnr-page-overlay"><div id="loader-container"><div class="plgsspinner"></div><p>Creating list... Please be patient.<br>This process can take sometime, depending on the number of installed plugins.</p></div></div>'
			);
			jQuery("#plgnr-global-overlay").addClass("plgnr-overlay-visible");
		} else {
			jQuery("#plgnr-global-overlay").removeClass("plgnr-overlay-visible");
			jQuery("body").remove(jQuery("#plgnr-global-overlay"));
		}
	}

	Pluginer.checkRequiredPlugins = function (allPlugins) {
		let requiredPlugins = [];
		let checkedCheckboxes = [];
		if (allPlugins) {
			checkedCheckboxes = jQuery('.plugin_to_install');
		} else {
			checkedCheckboxes = jQuery('.plugin_to_install:checked');
		}
		checkedCheckboxes.each(function () {
			const rp = jQuery(this).data('required-plugins'); // Recupera il valore dell'attributo data
			if (rp !== 'NR') {
				requiredPlugins.push(rp); // Aggiunge il valore all'array
			}
		});
		return [...new Set(requiredPlugins)];// this elminates duplicates elements
	}

	Pluginer.autoAddPluginToList = function (pluginName, pluginSlug, pluginIcon) {
		console.log('autoAddPluginToList ' + pluginName + ' ' + pluginSlug + ' ' + pluginIcon);
		let pd = pluginIcon + ";" + pluginName + ";" + pluginSlug;
		jQuery("div#plugins-list-table .table-body").append(
			`<div class="table-row" id="${pluginSlug}">
				<div class="table-column"><input type="checkbox" class="plugin_to_install" name="plugin_to_install" value="${pd}" /></div>
				<div class="table-column pl-icon"><img src="${pluginIcon}" /></div>
				<div class="table-column pl-status"></div>
				<div class="table-column pl-name">${pluginName}</div>
				<div class="table-column pl-slug">${pluginSlug}</div>
				<div class="table-column">
				<button class="button remove_plugin_button" data-slug="${pluginSlug}">Remove</button>
				</div>
					<input type="hidden" class="plugin_name" name="plugin_name[]" value="${pluginName}" />
					<input type="hidden" class="plugin_slug" name="plugin_slug[]" value="${pluginSlug}" />
					<input type="hidden" class="plugin_icon" name="plugin_icon[]" value="${pluginIcon}" />
				</div>
				`
		);
		jQuery("#plugin_name").val("");
		jQuery("#plugin_slug").val("");
		jQuery("#plugin_icon").val("");
		jQuery("#plugins_result_list").val("");
	}

	/**
	 * seacrh required plugin using plugin_api I some plugin is required, it calls class.instalis-admin->plgnr_update_plugin_list() per aggiornare nel database il campo _plgnr_plugin_required_plugins
	 */
	Pluginer.searchRequiredPlugin = function (str, post_id, nonce) {
		return new Promise((resolve, reject) => {
			var data = {
				action: "plgnr_get_required_plugin",
				plugin_name: str,
				page: 1,
			};
			jQuery.post(ajaxurl, data, function (result) {
				if (result) {
					var response = JSON.parse(result);
					var imgurl;
					if (response.icons != null) {
						if (!Pluginer.isEmpty(response.icons["svg"])) {
							imgurl = response.icons["svg"];
						} else if (!Pluginer.sEmpty(response.icons["1x"])) {
							imgurl = response.icons["1x"];
						} else if (!Pluginer.isEmpty(response.icons["2x"])) {
							imgurl = response.icons["2x"];
						} else {
							imgurl = response.icons["default"];
						}
					} else {
						imgurl = response.imgurl;
					}
					let pluginFoundName = response.plugin_name;
					let pluginFoundSlug = response.plugin_slug;
					let pluginFoundIcon = imgurl;
					let pluginNotes = jQuery('#plgnr_plugin_list_notes').val();
					jQuery("#plugin_name").val(pluginFoundName);
					jQuery("#plugin_slug").val(pluginFoundSlug);
					jQuery("#plugin_icon").val(pluginFoundIcon);

					addPluginToList();
					jQuery.ajax({
						url: ajaxurl, // Variabile globale di WordPress
						type: "POST",
						data: {
							action: "plgnr_update_plugin_list",
							security: nonce, // Passa il nonce
							post_id: post_id,
							plugin_name: pluginFoundName,
							plugin_slug: pluginFoundSlug,
							plugin_icon: pluginFoundIcon,
							plugin_list_notes: pluginNotes,
							required_plugin: 'NR',
						},
						success: function (response) {
							if (response.success) {
								jQuery('#' + pluginFoundSlug).find('.plugin_to_install').data('is-required', 'yes');
								jQuery('#' + pluginFoundSlug).find('.plugin-status').append('<img title="<?php echo esc_html( \'This plugin can be installed and activated\' ); ?>" src="<?php echo esc_html( PLUGINER_URL . \'/img/okay3.png\' ); ?>" />');
								Swal.fire({
									title: "Success!",
									text: "Required plugin added to the list.",
									showDenyButton: false,
									showCancelButton: false,
									confirmButtonText: "Ok",
									icon: 'success',
									iconColor: '',
									confirmButtonColor: '',
									denyButtonColor: '',
									cancelButtonColor: '',
								}).then((result) => {
									if (result.isConfirmed) {
										resolve();
									}
								});
							} else {
								Swal.fire({
									title: "Error!",
									text: "Error: " + response.data,
									showDenyButton: false,
									showCancelButton: false,
									confirmButtonText: "Ok",
									icon: 'error',
									iconColor: '',
									confirmButtonColor: '',
									denyButtonColor: '',
									cancelButtonColor: '',
								}).then((result) => {
									if (result.isConfirmed) {
										reject();
									}
								});
							}
						},
						error: function () {
							Swal.fire({
								title: "Error!",
								text: "AJAX Error updating the post.",
								showDenyButton: false,
								showCancelButton: false,
								confirmButtonText: "Ok",
								icon: 'error',
								iconColor: '',
								confirmButtonColor: '',
								denyButtonColor: '',
								cancelButtonColor: '',
							}).then((result) => {
								if (result.isConfirmed) {
									reject();
								}
							});
						}

					});
				}
			});
		});
	}

	Pluginer.isCancelled = false;
	Pluginer.alreadyInstalled = 0;

	Pluginer.startProcessing = function (plugins) {
		Pluginer.togglePluginsOverlay(true);

		let index = 0;

		let nonce = jQuery(".install_list_button").data('nonce');
		let plgnrProblems = false;

		// Funzione per lo scroll automatico
		function scrollToBottom() {
			const feedbackBody = jQuery('.process-feedback-body')[0]; // Seleziona l'elemento DOM
			const lastParagraph = feedbackBody.lastElementChild; // Ottiene l'ultimo paragrafo aggiunto
			if (lastParagraph) {
				const lastParagraphHeight = lastParagraph.offsetHeight; // Calcola l'altezza dell'ultimo paragrafo
				feedbackBody.scrollTop = feedbackBody.scrollHeight - feedbackBody.clientHeight + lastParagraphHeight; // Scroll automatico
			}
		}

		function processNext() {
			if (Pluginer.isCancelled) {
				return;
			}

			if (index < plugins.length) {
				if (plugins[index].installed === 1) {  // Se il plugin è già installato, salta
					index++;
					processNext();
					return;
				}

				// Aggiungi il paragrafo "Installing..."
				jQuery('.process-feedback-body').append('<p id="installing"><span class="plgnr-spinner"></span>Installing ' + plugins[index].slug + '</p>');
				scrollToBottom(); // Scroll automatico

				jQuery.ajax({
					url: ajaxurl,
					method: 'POST',
					timeout: 120000,
					data: {
						action: 'plgnr_install_single_plugin',
						plugin_slug: plugins[index].slug,
						nonce: nonce
					},
					success: function (response) {
						Pluginer.alreadyInstalled++;
						if (response.data.status === 'active') {
							jQuery('p#installing').replaceWith('<p class="installation-response"><span class="ui-success"><svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52"> <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none"/> <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/></svg></span>Successfully installed and activated ' + plugins[index].slug + '</p>');
						} else {
							plgnrProblems = true;
							jQuery('p#installing').replaceWith('<p class="installation-response"><span class="ui-error"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80" height="30" width="30"><circle cx="40" cy="40" r="32" fill="transparent" stroke-width="5" stroke="#F74444" /><path d="M40 40 L40 40" fill="transparent" stroke="#F74444" stroke-width="5" width="5" stroke-linecap="round" opacity="1"><animate id="line1" attributeName="d" from="M40 40 L40 40" to="M25 25 L55 55" dur="0.2" fill="freeze"/><animateTransform attributeName="transform" type="rotate" from="0 40 40" to="90 40 40" dur=".3s" values="20 40 40; 40 40 40; 70 40 40; 100 40 40; 90 40 40" keyTimes="0; .25; .5; .75; 1" begin="line1.end" fill="freeze" repeatCount="1" /></path><path d="M55 25 L55 25" fill="transparent" stroke="#F74444" stroke-width="5" width="5" stroke-linecap="round" opacity="1"><animate id="line1" attributeName="d" from="M55 25 L55 25" to="M25 55 L55 25" dur="0.2" fill="freeze" /><animateTransform attributeName="transform" type="rotate" from="0 40 40" to="90 40 40" dur=".4s" values="20 40 40; 40 40 40; 70 40 40; 100 40 40; 90 40 40" keyTimes="0; .25; .5; .75; 1" begin="line1.end" fill="freeze" repeatCount="1" /></path></svg></span>Could not activate ' + plugins[index].slug + ': ' + response.data.message + '</p>');
						}
						scrollToBottom(); // Scroll automatico dopo l'aggiornamento del paragrafo

						const pluginRow = jQuery('#plugins-list-table .table-row[id="' + plugins[index].slug + '"]');
						pluginRow.removeClass('not-installed').addClass('already-installed').children('.plugin_to_install').hide();
						pluginRow.children('.installed-check').show();

						// Calcola la percentuale di completamento
						const progressPercentage = ((index + 1) / plugins.length) * 100;

						// Imposta la larghezza in modo graduale
						if (index < plugins.length - 1) {
							jQuery('#plgnr-progress-bar').css('width', progressPercentage + '%');
						}
						index++;
						processNext();
					},
					error: function (xhr, ajaxOptions, thrownError) {
						console.log('Status:', xhr.status);
						console.log('Response Text:', xhr.responseText);
						console.log('Error Thrown:', thrownError);
						plgnrProblems = true;
						jQuery('p#installing').replaceWith('<p class="installation-response"><span class="ui-error"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80" height="30" width="30"><circle cx="40" cy="40" r="32" fill="transparent" stroke-width="5" stroke="#F74444" /><path d="M40 40 L40 40" fill="transparent" stroke="#F74444" stroke-width="5" width="5" stroke-linecap="round" opacity="1"><animate id="line1" attributeName="d" from="M40 40 L40 40" to="M25 25 L55 55" dur="0.2" fill="freeze"/><animateTransform attributeName="transform" type="rotate" from="0 40 40" to="90 40 40" dur=".3s" values="20 40 40; 40 40 40; 70 40 40; 100 40 40; 90 40 40" keyTimes="0; .25; .5; .75; 1" begin="line1.end" fill="freeze" repeatCount="1" /></path><path d="M55 25 L55 25" fill="transparent" stroke="#F74444" stroke-width="5" width="5" stroke-linecap="round" opacity="1"><animate id="line1" attributeName="d" from="M55 25 L55 25" to="M25 55 L55 25" dur="0.2" fill="freeze" /><animateTransform attributeName="transform" type="rotate" from="0 40 40" to="90 40 40" dur=".4s" values="20 40 40; 40 40 40; 70 40 40; 100 40 40; 90 40 40" keyTimes="0; .25; .5; .75; 1" begin="line1.end" fill="freeze" repeatCount="1" /></path></svg></span>Something went wrong with ' + plugins[index].slug + '. There is a chance you have to activate it manually</p>');
						scrollToBottom(); // Scroll automatico dopo l'aggiornamento del paragrafo
						index++;
						processNext();
					}
				});

			} else {
				jQuery('#plgnr-progress-bar').css('width', '100%'); // Assicurati che arrivi al 100%
				if (plgnrProblems) {
					jQuery('.cancel-button').remove();
					jQuery('.plgnr-progressbar-wrapper').replaceWith('<div class="error notice"><p>Some problem could have prevented to activate one or more plugins. Please, activate them manually or check their requirements.</p></div><div class="plgnr-button-wrapper"><button class="plgnr-button" id="close-plugins-overlay">Close</button></div>');
				} else {
					jQuery('.cancel-button').remove();
					jQuery('.plgnr-progressbar-wrapper').replaceWith('<div class="success notice"><p>Your plugins list have been processed.</p></div><div id="close-button-wrapper" class="plgnr-button-wrapper"><button class="plgnr-button" id="close-plugins-overlay">Close</button></div>');
					jQuery('.plugin_to_install').attr('checked', false);
				}
				if (Pluginer.alreadyInstalled === plugins.length) {
					jQuery('#install_all_plugin_button').attr('disabled', 'disabled');
				}
			}
		}

		processNext();
	}

	Pluginer.isEmpty = function (value) {
		return (
			value == null ||
			(typeof value === "string" && value.trim().length === 0)
		);
	}

})(window);