(function ($) {
	"use strict";
	$(document).ready(function () {


		function togglePluginsOverlay(visible) {
			if (visible) {
				$("body").append(
					'<div id="plugins-overlay" class="inslst-page-overlay"><div class="process-feedback"></div></div>'
				);
				$("#plugins-overlay").addClass("inslst-overlay-visible");
			} else {
				$("#plugins-overlay").removeClass("inslst-overlay-visible");
				$("body").remove($("#plugins-overlay"));
			}
		}

		function togglePlugins2Overlay(visible) {
			if (visible) {
				$("body").append(
					'<div id="plugins2-overlay" class="inslst-page-overlay"></div>'
				);
				$("#plugins2-overlay").addClass("inslst-overlay-visible");
			} else {
				$("#plugins2-overlay").removeClass("inslst-overlay-visible");
				$("body").remove($("#plugins2-overlay"));
			}
		}

		function toggleOverlay(visible) {
			if (visible) {
				$("body").append(
					'<div id="inslst-global-overlay" class="inslst-page-overlay"><div id="loader-container"><div class="plgsspinner"></div></div></div>'
				);
				$("#inslst-global-overlay").addClass("inslst-overlay-visible");
			} else {
				$("#inslst-global-overlay").removeClass("inslst-overlay-visible");
				$("body").remove($("#inslst-global-overlay"));
			}
		}

		// #region ADD PLUGIN TO LIST
		$("#add_plugin_button").on("click", function (e) {
			e.preventDefault();
			if ("" === $("#plugin_name").val() || "" === $("#plugin_slug").val()) {
				Swal.fire({
					titleText: "Error",
					text: "Can't find the slug for this plugin.",
					showDenyButton: false,
					showCancelButton: false,
					confirmButtonText: "Ok",
					icon: "error",
					customClass: {
						actions: "my-actions",
						confirmButton: "sweet-yes",
						denyButton: "sweet-no",
					},
				}).then((result) => {
					return;
				});
			} else {
				addPluginToList();
			}
		});

		function addPluginToList() {
			var nonce = $("#_wpnonce").val();
			let pluginName = $("#plugin_name").val();
			let pluginSlug = $("#plugin_slug").val();
			let pluginIcon = $("#plugin_icon").val();
			let pd = pluginIcon + ";" + pluginName + ";" + pluginSlug;
			$("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"><img src="${pluginIcon}" /></div>
				<div class="table-column">${pluginName}</div>
				<div class="table-column">${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>
				`
			);

			$("#plugin_name").val("");
			$("#plugin_slug").val("");
			$("#plugin_icon").val("");
			$("#plugins_result_list").val("");
		}

		// #endregion ADD PLUGIN TO LIST

		// #region REMOVE PLUGIN FROM LIST
		$(document).on("click", ".remove_plugin_button", function (e) {
			e.preventDefault();
			let slug = $(this).data("slug");
			Swal.fire({
				titleText: "Confirm, please.",
				html:
					"Are you sure you want to remove the plugin <strong>" +
					slug +
					"</strong> from the list?",
				showDenyButton: true,
				showCancelButton: false,
				confirmButtonText: "Yes",
				denyButtonText: "No",
				icon: "question",
			}).then((result) => {
				if (result.isConfirmed) {
					$(".table-row#" + slug).remove();
					markPostAsDirty();
				}
			});
		});

		var isDirty;
		// Funzione per segnare il post come modificato
		function markPostAsDirty() {
			isDirty = true;  // Segna lo stato come "modificato"
			window.onbeforeunload = function () {
				if (isDirty) {
					return "You have unsaved changes. Are you sure you want to leave?";
				}
			};
		}

		// Quando l'utente salva il post, rimuovi il listener e resetta lo stato.
		$(document).on("submit", "form", function () {
			isDirty = false;  // Resetta lo stato a "non modificato"
			window.onbeforeunload = null;  // Rimuovi il messaggio di conferma
		});

		// #endregion REMOVE PLUGIN FROM LIST

		function checkRequiredPlugins(pluginSlug, nonce, callback) {
			$.ajax({
				url: ajaxurl,
				method: 'POST',
				data: {
					action: 'inslst_check_required_plugins',
					plugin_slug: pluginSlug,
					nonce: nonce
				},
				success: function (response) {
					if (response.success) {
						console.log('required_plugins');
						console.log(response.data.required_plugins);
						callback(response.data.required_plugins);
					} else {
						console.error('Error checking required plugins:', response.data.message);
						callback([]);
					}
				},
				error: function (xhr, ajaxOptions, thrownError) {
					console.error('AJAX error:', thrownError);
					callback([]);
				}
			});
		}

		// #region INSTALL SELECTED PLUGINS

		let installingSelection = false;
		$("#install_selected_plugins_button").on("click", function (e) {

			if ($(this).hasClass('disabled')) {
				return;
			}
			e.preventDefault();
			var checkedCheckboxes = $('.plugin_to_install:checked');
			if (checkedCheckboxes.length <= 0) {
				// alert();
				// return;
				Swal.fire({
					titleText:
						"No plugin selected",
					text: "Please, select at least one plugin to install and activate.",
					showDenyButton: false,
					showCancelButton: false,
					confirmButtonText: "Ok",
					icon: "warning",
				}).then((result) => {

				});
				return;
			}
			Swal.fire({
				titleText:
					"Please, confirm",
				text: "Do you want to install and activate the selected plugin(s)?",
				showDenyButton: true,
				showCancelButton: false,
				confirmButtonText: "Yes",
				denyButtonText: "No",
				icon: "question",
			}).then((result) => {
				if (result.isConfirmed) {
					installSelectedPlugins();
				}
			});
		});

		function installSelectedPlugins() {
			togglePluginsOverlay(true);
			installingSelection = true;
			// let nonce = $("#_wpnonce_inst_sel").val();
			let plugins = [];
			$.each($(".plugin_to_install"), function () {
				if ($(this).is(":checked")) {
					const slugs = $(this).val().split(';');
					console.log('slug is ' + slugs[slugs.length - 1]);
					plugins.push({ slug: slugs[slugs.length - 1], installed: false });
				}
			});
			$('.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></div><div class="process-feedback-body"></div><div class="process-feedback-footer"><div class="inslst-progressbar-wrapper"><div id="inslst-progress-bar"></div></div><div class="inslst-button-wrapper cancel-button"><button class="inslst-button" id="inslst-cancel-button">Cancel</button></div></div>');
			startProcessing(plugins);
		}

		// #endregion INSTALL SELECTED PLUGINS

		// #region INSTALL ALL PLUGINS
		$("#install_all_plugin_button").on("click", function (e) {
			e.preventDefault();
			Swal.fire({
				titleText: "Confirm, please.",
				text: "Do you want to install and activate all the plugins of this list?",
				showDenyButton: true,
				showCancelButton: false,
				confirmButtonText: "Yes",
				denyButtonText: "No",
				icon: "question",
				customClass: {
					actions: "my-actions",
					confirmButton: "sweet-yes",
					denyButton: "sweet-no",
				},
			}).then((result) => {
				if (result.isConfirmed) {
					let nonce = $(this).data("nonce");
					let post_id = $(this).data("post-id");
					installAllPluginsOfList(nonce, post_id);
				}
			});
		});
		// #endregion INSTALL ALL PLUGINS

		// #region INSTALL ALL PLUGIN OF LIST FROM PLUGIN LIST PAGE (links below list name)
		$(".install_list_link").on("click", function (e) {
			e.preventDefault();
			Swal.fire({
				titleText: "Confirm, please.",
				text: "Do you want to install and activate all the plugins of this list?",
				showDenyButton: true,
				showCancelButton: false,
				confirmButtonText: "Yes",
				denyButtonText: "No",
				icon: "question",
				customClass: {
					actions: "my-actions",
					confirmButton: "sweet-yes",
					denyButton: "sweet-no",
				},
			}).then((result) => {
				if (result.isConfirmed) {
					let nonce = $(this).data("nonce");
					let post_id = $(this).data("post-id");
					installAllPluginsOfList(nonce, post_id);
				}
			});
		});

		/**
		 * Install all plugins when user clicks on the link in the plugin lists page
		 * @param {string} nonce 
		 * @param {int} post_id 
		 */
		function installAllPluginsOfList(nonce, post_id) {
			togglePluginsOverlay(true);
			installingSelection = false;
			$('.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></div><div class="process-feedback-body"></div><div class="process-feedback-footer"><div class="inslst-progressbar-wrapper"><div id="inslst-progress-bar"></div></div><div class="inslst-button-wrapper cancel-button"><button class="inslst-button" id="inslst-cancel-button">Cancel</button></div></div>');
			$.ajax({
				type: "post",
				url: ajaxurl,
				data: {
					nonce: nonce,
					post_id: post_id,
					action: "inslst_get_plugins_in_list",
				},
				success: function (response) {
					if (response.success) {
						const plugins = response.data.plugins;
						plugins.forEach(plugin => {
							checkRequiredPlugins(plugin.slug, nonce, function (requiredPlugins) {
								if (requiredPlugins.length > 0) {
									Swal.fire({
										title: "Required Plugins Found",
										text: `The plugin "${plugin.slug}" requires the following plugins: ${requiredPlugins.join(', ')}. Would you like to add them to the list?`,
										icon: "warning",
										showCancelButton: true,
										confirmButtonText: "Yes, add them",
										cancelButtonText: "No, skip",
									}).then((result) => {
										if (result.isConfirmed) {
											// Aggiungi i plugin richiesti alla lista
											requiredPlugins.forEach(rp => {
												if (!plugins.some(p => p.slug === rp)) {
													plugins.push({ slug: rp, installed: false });
												}
											});
										}
										// Procedi con l'installazione
										startProcessing(plugins);

									});
								} else {
									startProcessing(plugins);
								}
							});
						});
					} else {
						console.error('Error fetching plugin list:', response.data);
						Swal.fire({
							titleText: "Error!",
							text: "Some error occurred trying to install this plugins list.",
							showDenyButton: false,
							showCancelButton: false,
							confirmButtonText: "Ok",
							icon: "error",
						}).then((result) => {
							return false;
						});
					}
				},
				error: function (xhr, ajaxOptions, thrownError) {
					toggleOverlay(false);
					try {
						console.log('Status:', xhr.status);
						console.log('Response Text:', xhr.responseText);
						console.log('Error Thrown:', thrownError);
						// Analizza la risposta JSON
					} catch (e) {
						console.log("Error parsing JSON:", e);
						console.log("Raw response:", xhr.responseText);
					}
				},
			});
		}

		/**
		 * Versione con checkRequiredPlugins
		 * 
		 * 
		 */
		// function installAllPluginsOfList(nonce, post_id) {
		// 	togglePluginsOverlay(true);
		// 	installingSelection = false;
		// 	$('.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></div><div class="process-feedback-body"></div><div class="process-feedback-footer"><div class="inslst-progressbar-wrapper"><div id="inslst-progress-bar"></div></div><div class="inslst-button-wrapper cancel-button"><button class="inslst-button" id="inslst-cancel-button">Cancel</button></div></div>');
		
		// 	$.ajax({
		// 		type: "post",
		// 		url: ajaxurl,
		// 		data: {
		// 			nonce: nonce,
		// 			post_id: post_id,
		// 			action: "inslst_get_plugins_in_list",
		// 		},
		// 		success: function (response) {
		// 			if (response.success) {
		// 				const plugins = response.data.plugins;
		
		// 				// Controlla i plugin richiesti per tutti i plugin in parallelo
		// 				const requiredPluginsChecks = plugins.map(plugin => 
		// 					new Promise((resolve) => {
		// 						checkRequiredPlugins(plugin.slug, nonce, function (requiredPlugins) {
		// 							resolve({ slug: plugin.slug, requiredPlugins });
		// 						});
		// 					})
		// 				);
		
		// 				Promise.all(requiredPluginsChecks).then(results => {
		// 					const allRequiredPlugins = [];
		// 					results.forEach(result => {
		// 						if (result.requiredPlugins.length > 0) {
		// 							allRequiredPlugins.push(...result.requiredPlugins);
		// 						}
		// 					});
		
		// 					if (allRequiredPlugins.length > 0) {
		// 						Swal.fire({
		// 							title: "Required Plugins Found",
		// 							text: `Some plugins in this list require additional plugins to function. Would you like to add them to the list?`,
		// 							icon: "warning",
		// 							showCancelButton: true,
		// 							confirmButtonText: "Yes, add them",
		// 							cancelButtonText: "No, skip",
		// 						}).then((result) => {
		// 							if (result.isConfirmed) {
		// 								// Aggiungi i plugin richiesti alla lista
		// 								allRequiredPlugins.forEach(rp => {
		// 									if (!plugins.some(p => p.slug === rp)) {
		// 										plugins.push({ slug: rp, installed: false });
		// 									}
		// 								});
		// 							}
		// 							// Procedi con l'installazione
		// 							startProcessing(plugins);
		// 						});
		// 					} else {
		// 						// Procedi direttamente con l'installazione se non ci sono richiesti
		// 						startProcessing(plugins);
		// 					}
		// 				});
		// 			} else {
		// 				console.error('Error fetching plugin list:', response.data);
		// 				Swal.fire({
		// 					titleText: "Error!",
		// 					text: "Some error occurred trying to install this plugins list.",
		// 					showDenyButton: false,
		// 					showCancelButton: false,
		// 					confirmButtonText: "Ok",
		// 					icon: "error",
		// 				});
		// 			}
		// 		},
		// 		error: function (xhr, ajaxOptions, thrownError) {
		// 			toggleOverlay(false);
		// 			try {
		// 				console.log('Status:', xhr.status);
		// 				console.log('Response Text:', xhr.responseText);
		// 				console.log('Error Thrown:', thrownError);
		// 			} catch (e) {
		// 				console.log("Error parsing JSON:", e);
		// 				console.log("Raw response:", xhr.responseText);
		// 			}
		// 		},
		// 	});
		// }
		

		// $('.already-installed').children('.installed-check').show();
		let isCancelled = false;
		function startProcessing(plugins) {
			console.log('plugins are ');
			console.log(plugins);
			let index = 0;
			let alreadyInstalled = 0;
			let nonce = $(".install_list_button").data('nonce');
			let inslstProblems = false;

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


				if (index < plugins.length) {
					// console.log("Response for plugin:", plugins[index].slug, "Installed:", plugins[index].installed);

					if (plugins[index].installed === 1) {  // Se il plugin è già installato, salta
						console.log("Skipping already installed plugin:", plugins[index].slug);
						index++;
						processNext();
						return;
					}
					// console.log('plugins[index].installed = ' + plugins[index].installed);
					// console.log('plugins[index].slug = ' + plugins[index].slug);
					// console.log('plugins.length = ' + plugins.length);
					// console.log('plugins slug is ' + plugins[index].slug + ' and installed is ' + plugins[index].installed);
					$('.process-feedback-body').append('<p id="installing"><span class="inslst-spinner"></span>Installing ' + plugins[index].slug + '</p>');

					$.ajax({
						url: ajaxurl,
						method: 'POST',
						timeout: 120000,
						data: {
							action: 'inslst_install_single_plugin',
							plugin_slug: plugins[index].slug,
							nonce: nonce
						},
						success: function (response) {
							alreadyInstalled++;
							if (response.data.status === 'active') {
								$('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 {
								inslstProblems = true;
								$('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>');
							}
							const pluginRow = $('#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) {
								$('#inslst-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);
							inslstProblems = true;
							$('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>');
							index++;
							processNext();
						}
					});

				} else {
					$('#inslst-progress-bar').css('width', '100%'); // Assicurati che arrivi al 100%
					if (inslstProblems) {
						$('.cancel-button').remove();
						$('.inslst-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="inslst-button-wrapper"><button class="inslst-button" id="close-plugins-overlay">Close</button></div>');
					} else {
						$('.cancel-button').remove();
						$('.inslst-progressbar-wrapper').replaceWith('<div class="success notice"><p>Your plugins list have been processed.</p></div><div id="close-button-wrapper" class="inslst-button-wrapper"><button class="inslst-button" id="close-plugins-overlay">Close</button></div>');
						$('.plugin_to_install').attr('checked', false);
					}
					if (alreadyInstalled === plugins.length && !installingSelection) {
						$('#install_all_plugin_button').attr('disabled', 'disabled');
					}
				}

			}

			processNext();
		}

		$(document).on('click', '#close-plugins-overlay', function (e) {
			e.preventDefault();
			togglePluginsOverlay(false);
		});

		$(document).on('click', '#inslst-cancel-button', function (e) {
			e.preventDefault();
			Swal.fire({
				titleText: "Confirm, please.",
				text: "Are you sure you want to stop the installation process?",
				showDenyButton: true,
				showCancelButton: false,
				confirmButtonText: "Yes",
				denyButtonText: "No",
				icon: "question",
			}).then((result) => {
				if (result.isConfirmed) {
					isCancelled = true;
					togglePluginsOverlay(false);
				}
			});
		});

		// #endregion INSTALL ALL PLUGIN OF LIST

		$("#cancel_edit_list").on("click", function () {
			$("#plugin_name").val("");
			$("#plugin_slug").val("");
			$("#plugins_result_list").find(".plugin_found_data").remove();
		});

		var getFileName = function (str) {
			return str.split("\\").pop().split("/").pop();
		};

		$(".export_list_button").on("click", function (e) {
			e.preventDefault();
			Swal.fire({
				titleText: "Confirm, please.",
				text: "Do you want to export this list and start downloading it?",
				showDenyButton: true,
				showCancelButton: true,
				confirmButtonText: "Yes",
				denyButtonText: "No",
				icon: "question",
			}).then((result) => {
				if (result.isConfirmed) {
					var postId = $(this).data("post-id");
					var nonce = $(this).data("nonce");

					// Crea un form temporaneo per il download del file
					var $form = $("<form>", {
						action: ajaxurl,
						method: "post",
					})
						.append(
							$("<input>", {
								type: "hidden",
								name: "action",
								value: "inslst_export_plugin_list",
							})
						)
						.append(
							$("<input>", {
								type: "hidden",
								name: "post_id",
								value: postId,
							})
						)
						.append(
							$("<input>", {
								type: "hidden",
								name: "security",
								value: nonce,
							})
						);

					$("body").append($form);
					$form.submit();
					$form.remove();
					// exportPluginList();
				}
			});
		});

		$("#import_plugin_list_button").on("click", function (e) {
			e.preventDefault();
			if ("" !== $("#import_list").val()) {
				var fakename = $("#import_list").val();
				var fname = getFileName(fakename);
				Swal.fire({
					title: "Do you want to import the plugin list " + fname + "?",
					showDenyButton: true,
					showCancelButton: false,
					confirmButtonText: "Yes",
					denyButtonText: "No",
				}).then((result) => {
					if (result.isConfirmed) {
						var filename = $("#import_list").val().split("\\").pop();
						if ("" !== filename) {
							var ext = filename.split(".").pop();
							if ("csv" !== ext) {
								Swal.fire({
									title: "Sorry, only csv format is accepted.",
									showDenyButton: false,
									showCancelButton: false,
									confirmButtonText: "Ok",
								}).then((result) => {
									$("#import_list").val(null);
									return;
								});
							}
							importPluginList();
						}
					}
				});
			} else {
				Swal.fire({
					title: "Please, select a file before to click the Import button.",
					showDenyButton: false,
					showCancelButton: false,
					confirmButtonText: "Ok",
					icon: "",
					iconColor: "",
					confirmButtonColor: "",
					denyButtonColor: "",
					cancelButtonColor: "",
				}).then((result) => {
					if (result.isConfirmed) {
						return;
					}
				});
			}
		});

		function importPluginList() {
			toggleOverlay(true);
			$("#import_plugin_list_form").ajaxSubmit({
				success: function (data) {
					if (data.result === "success") {
						toggleOverlay(false);
						Swal.fire({
							titleText: "Success!",
							text: "File successfully imported and saved to uploads directory!",
							showDenyButton: false,
							showCancelButton: false,
							confirmButtonText: "Ok",
							icon: "success",
							customClass: {
								actions: "my-actions",
								confirmButton: "sweet-yes",
								denyButton: "sweet-no",
							},
						}).then((result) => {
							return;
						});
						$("#import_list").val(null).trigger("change");
					} else if (data.result === "upgrade_needed") {
						toggleOverlay(false);
						Swal.fire({
							titleText: "Info",
							text: "You need to upgrade to get multi-lists feature.",
							showDenyButton: false,
							showCancelButton: false,
							confirmButtonText: "Ok",
							icon: "info",
						}).then(() => {
							return;
						});
						$("#import_list").val(null).trigger("change");
					}
				},
				error: function (xhr, ajaxOptions, thrownError) {
					toggleOverlay(false);
					try {
						console.log('Status:', xhr.status);
						console.log('Response Text:', xhr.responseText);
						console.log('Error Thrown:', thrownError);
					} catch (e) {
						console.log("Error parsing JSON:", e);
						console.log("Raw response:", xhr.responseText);
					}
				},
			});

			return false;
		}

		function checkFile(e) {
			return "" === $("#import_list").val() ? false : true;
		}

		$("input[type=file]").change(function (e) {
			if (checkFile()) {
				var filename = e.currentTarget.files[0].name;
				$("span#import_list_filename").text(filename);
				$("#import_plugin_list_button").removeAttr("disabled");
			} else {
				$("#import_plugin_list_button").prop("disabled", true);
			}
		});

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

		$("#load_local_plugins:not(.disabled)").on("click", function (e) {
			searchPluginsLocally();
		});
		/**
		 * search for plugins in local files
		 * @param {string} str
		 */
		function searchPluginsLocally() {
			togglePluginsOverlay(true);
			var data = {
				action: "inslst_get_installed_plugins",
			};
			$.post(ajaxurl, data, function (result) {
				if (result) {
					var response = JSON.parse(result);
					$("#plugins_result_list").find(".plugin_found_data").remove();
					var imgurl;
					$.each(response, function (index, entry) {
						if (entry.icons != null) {
							if (!isEmpty(entry.icons["svg"])) {
								imgurl = entry.icons["svg"];
							} else if (!isEmpty(entry.icons["1x"])) {
								imgurl = entry.icons["1x"];
							} else if (!isEmpty(entry.icons["2x"])) {
								imgurl = entry.icons["2x"];
							} else {
								imgurl = entry.icons["default"];
							}
						} else {
							imgurl = entry.imgurl;
						}
						$("#plugins_result_list").append(
							'<div class="plugin_found_data" data-plugin-name="' +
							entry.plugin_name +
							'" data-plugin-slug="' +
							entry.plugin_slug +
							'" data-plugin-icon="' +
							imgurl +
							'"><img src="' +
							imgurl +
							'" /><span>' +
							entry.plugin_name +
							"</span><span>" +
							entry.plugin_slug +
							"</span></div>"
						);
					});
					togglePluginsOverlay(false);
				} else {
					togglePluginsOverlay(false);
				}
			});
		}

		// #region SEARCH PLUGINS FROM REPO
		/**
		 * seacrh plugin using instalist API from codingfix.com
		 * @param {string} str
		 */
		function searchPlugins(str, page) {
			togglePlugins2Overlay(true);
			var data = {
				action: "inslst_get_plugins_from_repo",
				needle: str,
				page: page,
			};
			$.post(ajaxurl, data, function (result) {
				if (result) {
					var response = JSON.parse(result);
					$("#plugins_result_list").find(".plugin_found_data").remove();
					var imgurl;
					// $.each(response.plugins_data, function (key, entry) {
					$.each(response, function (key, entry) {
						if (entry.icons != null) {
							if (!isEmpty(entry.icons["svg"])) {
								imgurl = entry.icons["svg"];
							} else if (!isEmpty(entry.icons["1x"])) {
								imgurl = entry.icons["1x"];
							} else if (!isEmpty(entry.icons["2x"])) {
								imgurl = entry.icons["2x"];
							} else {
								imgurl = entry.icons["default"];
							}
						} else {
							imgurl = entry.imgurl;
						}

						var bgclass = '';
						if (entry.installed === 1) {
							bgclass = 'installed'
						} else {
							bgclass = '';
						}

						$("#plugins_result_list").append(
							'<div class="plugin_found_data ' + bgclass + '" data-plugin-name="' +
							entry.plugin_name +
							'" data-plugin-slug="' +
							entry.plugin_slug +
							'" data-plugin-icon="' +
							imgurl +
							'"><img src="' +
							imgurl +
							'" /><span>' +
							entry.plugin_name +
							"</span><span>" +
							entry.plugin_slug +
							"</span></div>"
						);
					});
					togglePlugins2Overlay(false);
				} else {
				}
			});
		}

		$("#plugin_name").on("keyup", function (e) {
			if (e.which <= 90 && e.which >= 65) {
				const $this = $(this);
				pluginNameKeyup($this);
			}
		});

		//commented because the click on found plugins triggers this event and then is like a click on Next button
		// $("#plugin_name").on("change", function () {
		// 	const $this = $(this);
		// 	pluginNameKeyup($this);
		// });

		function pluginNameKeyup($this) {
			if ("undefined" !== typeof $(".plugin_found_data")) {
				$("#plugins_result_list").find(".plugin_found_data").remove();
			}
			if ($this.val().length === 0) {
				// $("#plugins_result_list").empty();
				if ("undefined" !== typeof $(".plugin_found_data")) {
					$("#plugins_result_list").find(".plugin_found_data").remove();
				}
				$("#plugin_slug").val("");
			}
			if ($this.val().length < 4) {
				if ("undefined" !== typeof $(".plugin_found_data")) {
					$("#plugins_result_list").find(".plugin_found_data").remove();
				}
				return;
			}
			$('#current_page').val('1');
			searchPlugins($this.val(), 1);
		}

		$(document).on('click', '.paginating', function (e) {
			e.preventDefault();
			var el = document.querySelector('#plugins_result_list');

			el.scrollTop = el.scrollHeight;
			el.scrollTop = 0;
			var currentPage = parseInt($('#current_page').val());
			if ($(this).hasClass('paginating-prev')) {
				if (1 === currentPage) {
					return;
				}
				searchPlugins($("#plugin_name").val(), currentPage - 1);
				$('#current_page').val(currentPage - 1);
			}
			if ($(this).hasClass('paginating-next')) {
				searchPlugins($("#plugin_name").val(), currentPage + 1);
				$('#current_page').val(currentPage + 1);
			}

		});
		// #enregion SEARCH PLUGINS FROM REPO

		// the following function is the result of merging what I have dound  at https://stackoverflow.com/questions/7225407/convert-camelcasetext-to-title-case-text and https://stackoverflow.com/questions/68677953/javascript-method-to-capitalize-the-first-letter-of-every-word-and-also-every-wo
		function toSpaceCase(str) {
			return str
				.toLowerCase()
				.replace(/[-_]/g, " ")
				.replace(/(^\w)|([-\s]\w)/g, (match) => match.toUpperCase())
				.replace(/\s+/g, " ")
				.trim();
		}

		$(document).on("click", ".plugin_found_data", function (e) {
			if (!$(this).hasClass('installed')) {
				let pluginFoundName = $(this).data("plugin-name");
				let pluginFoundSlug = $(this).data("plugin-slug");
				let pluginFoundIcon = $(this).data("plugin-icon");
				$("#plugin_name").val(pluginFoundName);
				$("#plugin_slug").val(pluginFoundSlug);
				$("#plugin_icon").val(pluginFoundIcon);
			}
		});

		$("input[type=file]").on("click", function (e) {
			$(this).val(null);
		});

		function noTitleAlert() {
			Swal.fire({
				titleText: "Warning!",
				text: "You must provide a List name before you can save your list.",
				showDenyButton: false,
				showCancelButton: false,
				confirmButtonText: "Ok",
				icon: "warning",
			}).then((result) => {
				return;
			});
		}

		$("form#post").on("submit", function (e) {
			var title = $("#title").val();
			if (!title) {
				noTitleAlert();
				e.preventDefault();
				return false;
			}
		});

		if ($("#post_type").val() === "inslst_plugin_list") {
			$("#title-prompt-text").text("Add Plugin List name");
		}

		checkFile();

		// Verifica se l'utente ha la versione premium

		var isPremium = true; // Implementa la tua logica per verificare la versione premium
		if ($("#import_plugin_list_button").data("is-premium") === "0") {
			isPremium = false;
		}

		if (!isPremium) {
			// Verifica il numero di liste esistenti
			$.ajax({
				url: ajaxurl,
				type: "post",
				data: {
					action: "inslst_check_plugin_list_count",
					security: instalistAdmin.nonce,
				},
				success: function (response) {
					if (response.found_posts >= 1) {
						// Disabilita i pulsanti e i link "Add Plugin List"
						$("a.page-title-action")
							.attr("href", "#")
							.click(function (e) {
								e.preventDefault();
								Swal.fire({
									titleText: "Confirm, please.",
									text: "You cannot create more than one plugin list with the free version. Do you want to upgrade to the Premium version?",
									showDenyButton: true,
									showCancelButton: false,
									confirmButtonText: "Yes",
									icon: "question",
									iconColor: "",
									customClass: {
										confirmButton: "sweet-yes",
										denyButton: "sweet-no",
									},
								}).then((result) => {
									if (result.isConfirmed) {
										return;
									}
								});
							});
						$('a[href*="post-new.php?post_type=inslst_plugin_list"]')
							.attr("href", "#")
							.click(function (e) {
								e.preventDefault();
								Swal.fire({
									titleText: "Confirm, please.",
									text: "You cannot create more than one plugin list with the free version. Do you want to upgrade to the Premium version?",
									showDenyButton: true,
									showCancelButton: false,
									confirmButtonText: "Yes",
									icon: "question",
									iconColor: "",
									customClass: {
										confirmButton: "sweet-yes",
										denyButton: "sweet-no",
									},
								}).then((result) => {
									if (result.isConfirmed) {
										return;
									}
								});
							});
					}
				},
			});
		}
	}); //ready
})(jQuery);
