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

		// #region DISABLE ADD AND CANCEL BUTTONS

		// #endregion DISABLE ADD AND CANCEL BUTTONS

		// #region ADD PLUGIN TO LIST
		$("#add_plugin_button").on("click", async function (e) {
			e.preventDefault();
			let $this = $(this);
			var curOffset = $(this).offset().top - $(document).scrollTop();
			if ("" === $("#plugin_name").val() || "" === $("#plugin_slug").val()) {
				await 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",
					},
				});
				return;
			} else {
				addPluginToList($this, curOffset);
			}
			Pluginer.toggleButtons();
		});

		function addPluginToList($this, curOffset) {
			var nonce = $("#_wpnonce").val();
			let pluginName = $("#plugin_name").val();
			let pluginSlug = $("#plugin_slug").val().toLowerCase();

			// Blocca Pluginer e Pluginer Premium
			if ('pluginer' === pluginSlug || 'pluginer-premium' === pluginSlug) {
				Swal.fire({
					titleText: "Error",
					text: "You cannot add Pluginer or Pluginer Premium to your list. They have to be installed manually in order to use the plugin lists 😉.",
					icon: "error",
					confirmButtonText: "Ok",
					customClass: {
						actions: "my-actions",
						confirmButton: "sweet-yes"
					}
				}).then(() => {
					$("#plugin_name").val('');
					$("#plugin_slug").val('');
					$("#plugin_icon").val('');
				});
				return;
			}

			// NUOVO CHECK: verifica se il plugin è già in lista
			if ($(`div#plugins-list-table .table-row#${pluginSlug}`).length > 0) {

				Swal.fire({
					titleText: "Already in the list",
					text: `"${pluginName}" is already added to your list.`,
					icon: "warning",
					confirmButtonText: "Ok",
					customClass: {
						actions: "my-actions",
						confirmButton: "sweet-yes"
					}
				}).then(() => {
					// adesso la modale è chiusa, possiamo scrollare
					$('html, body').animate({ scrollTop: 0 }, 300);
					// highlight del plugin nella tabella
					const $row = $(`div#plugins-list-table .table-row#${pluginSlug}`);
					// scroll della tabella interna, non della pagina
					const $tableBody = $("div#plugins-list-table .table-body");
					$tableBody.scrollTop($row.position().top + $tableBody.scrollTop() - $tableBody.height() / 2);
					$row.addClass('highlight');
					setTimeout(() => $row.removeClass('highlight'), 3000);
					$("#plugin_name").val("");
					$("#plugin_slug").val("");
					$("#plugin_icon").val("");
				});
				return; // esce senza aggiungere
			}

			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 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>`
			);

			$(document).scrollTop($this.offset().top - curOffset);
			$("#plugin_name").val("");
			$("#plugin_slug").val("");
			$("#plugin_icon").val("");
			$("#plugins_result_list").val("");
			markPostAsDirty();
		}

		$("#cancel_add_plugin_button").on("click", function () {
			$("#plugin_name").val("");
			$("#plugin_slug").val("");
			Pluginer.updatePaginationButtons(1, false, 0);
			$("#plugins_result_list").find(".plugin_found_data").remove();
			Pluginer.toggleButtons();
		});

		// #endregion ADD PLUGIN TO LIST

		$(document).on("click", ".remove_plugin_button", function (e) {
			e.preventDefault();
			let slug = $(this).data("slug");
			let isRequired = $(this).parents('.table-row').data('is-required');
			let titleText, myicon, txt = '';
			if (isRequired === 'yes') {
				txt = "This plugin is required by one or more plugins in the list. Do you want to remove it anyway?";
				titleText = "Warning";
				myicon = "warning";
			} else {
				txt = "Are you sure you want to remove the plugin <strong>" + slug + "</strong> from the list?";
				titleText = "Confirm, please.";
				myicon = "question";
			}
			Swal.fire({
				titleText: titleText,
				html: txt,
				showDenyButton: true,
				showCancelButton: false,
				confirmButtonText: "Yes",
				denyButtonText: "No",
				icon: myicon,
			}).then((result) => {
				if (result.isConfirmed) {
					$(".table-row#" + slug).remove();
					markPostAsDirty();
				}
			}, 'json').fail(function (xhr, status, error) {
				// Handle invalid/non-JSON responses or server errors
				Pluginer.togglePlugins2Overlay(false);
				console.error('Search plugins error:', status, error);
				try {
					console.log('Response Text:', xhr.responseText);
				} catch (e) {}
			});
		});

		// #region DETECT POST CHANGES

		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
		});

		$(document).on('input change', 'textarea', function () {
			markPostAsDirty();
		});

		// #endregion DETECT POST CHANGES

		// #region INSTALL ALL PLUGINS
		$(".install_list_action").on("click", function (e) {
			e.preventDefault();
			let plugins = [];
			$.each($(".plugin_to_install"), function () {
				const slugs = $(this).val().split(';');
				plugins.push({ slug: slugs[slugs.length - 1], installed: false });
			});
			let requiredPlugins = Pluginer.checkRequiredPlugins(true);
			// Filtra i plugin richiesti che non sono già nella lista plugins
			let newRequiredPlugins = requiredPlugins.filter(rp => !plugins.some(p => p.slug === rp));
			if (newRequiredPlugins.length > 0 && requiredPlugins[0] !== '') {
				Swal.fire({
					titleText:
						"Warning",
					html: "<p>Some of the selected plugin(s) requires to install the following plugin(s): " + requiredPlugins.join(', ') + ".</p><p>If you proceed without installing the required plugins, Pluginer won't be able to activate all the installed plugins.</p><p>On the other hand, Pluginer can add required plugins to your list and save it automatically. When all required plugins will have been added, you'll have to click the Install all button again.</p><p>Do you want Pluginer add the required plugins to your list?</p>",
					showDenyButton: true,
					showCancelButton: true,
					confirmButtonText: "Yes",
					denyButtonText: "No",
					icon: "warning",
				}).then((result) => {
					if (result.isDenied) {
						let nonce = $(this).data("nonce");
						let post_id = $(this).data("post-id");
						installAllPluginsOfList(nonce, post_id);
					}
					if (result.isConfirmed) {
						let nonce = $(this).data("nonce");
						let post_id = $(this).data("post-id");
						Promise.all(requiredPlugins.map(rp => Pluginer.searchRequiredPlugin(rp, post_id, nonce)))
							.then(() => {
								location.reload();
							})
							.catch(() => {
								console.error('Errore durante l\'aggiunta dei plugin richiesti.');
							});
					}
				});
			} else {
				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 in the list.
		 * @param {string} nonce 
		 * @param {int} post_id 
		 */
		function installAllPluginsOfList(nonce, post_id) {
			$.ajax({
				type: "post",
				url: ajaxurl,
				data: {
					nonce: nonce,
					post_id: post_id,
					action: "plgnr_get_plugins_in_list",
				},
				success: function (response) {
					if (response.success) {
						const plugins = response.data.plugins;
						let requiredPlugins = Pluginer.checkRequiredPlugins(true);
						// Sposta i plugin richiesti in cima alla lista plugins
						plugins.sort((a, b) => {
							if (requiredPlugins.includes(a.slug) && !requiredPlugins.includes(b.slug)) {
								return -1;
							}
							if (!requiredPlugins.includes(a.slug) && requiredPlugins.includes(b.slug)) {
								return 1;
							}
							return 0;
						});
						Pluginer.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) {
					Pluginer.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);
					}
				},
			});
		}
		// #endregion INSTALL ALL PLUGINS

		// #region INSTALLATION OF PLUGINS GUI
		$(document).on('click', '#close-plugins-overlay', function (e) {
			e.preventDefault();
			Pluginer.togglePluginsOverlay(false);
		});

		$(document).on('click', '#plgnr-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) {
					Pluginer.isCancelled = true;
					Pluginer.togglePluginsOverlay(false);
				}
			});
		});

		// #endregion INSTALLATION OF PLUGINS GUI

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

		// #region IMPORT/EXPORT PLUGIN LIST
		$(".export_list_button").on("click", function (e) {
			e.preventDefault();
			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: "plgnr_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();
		});

		$("#import_list").on("change", function () {
			checkIfFileSelected();
		});

		function checkIfFileSelected() {
			if ($("#import_list").length > 0) {
				if ('' !== $("#import_list").val()) {
					let filename = $("#import_list").val().split("\\").pop();
					var ext;
					if (filename !== "") {
						ext = filename.split('.');
						ext = ext[ext.length - 1];
					}
					console.log('filename: ', filename);
					console.log('ext: ', ext);
					if ("" !== filename && ext === "csv") {
						$("#import_plugin_list_button").removeAttr("disabled");
					} else {
						if ("" === filename) {
							$("#import_list").val(null);
							$("#import_plugin_list_button").prop("disabled", true);
							return;
						} else if (ext !== "csv") {
							Swal.fire({
								title: "Sorry, only csv format is accepted. " + ext,
								showDenyButton: false,
								showCancelButton: false,
								confirmButtonText: "Ok",
							}).then((result) => {
								$("#import_list").val(null);
								$("#import_plugin_list_button").prop("disabled", true);
								return;
							});
						}
					}
				} else {
					$("#import_plugin_list_button").prop("disabled", true);
				}
			}
		}

		$("#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: "You are going to import the plugin list " + fname + ".",
					showDenyButton: true,
					showCancelButton: false,
					confirmButtonText: "Import list",
					denyButtonText: "Cancel",
				}).then((result) => {
					if (result.isConfirmed) {
						importPluginList();
					}
				});
			}
		});

		function importPluginList() {
			Pluginer.toggleOverlay(true);
			$("#import_plugin_list_form").ajaxSubmit({
				url: ajaxurl, // <-- fondamentale
				type: 'POST',
				dataType: 'json',
				success: function (data) {
					console.log('data: ', data);
					console.log('data result: ' + data.result);
					if (data.result === "success") {
						Pluginer.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(() => {
							return;
						});
						$("#import_list").val(null).trigger("change");
					} else if (data.result === "invalid_file_type") {
						Swal.fire({
							titleText: "Error",
							text: "Invalid file type. Please upload a CSV file.",
							showDenyButton: false,
							showCancelButton: false,
							confirmButtonText: "Ok",
							icon: "error",
						}).then(() => {
							return;
						});
						$("#import_list").val(null).trigger("change");
					} else if (data.result === "upgrade_needed") {
						Pluginer.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(() => {
							location.reload();
						});
						$("#import_list").val(null).trigger("change");
					}
				},
				error: function (xhr, ajaxOptions, thrownError) {
					Pluginer.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;
		}

		$("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);
			}
		});

		// #endregion IMPORT/EXPORT PLUGIN LIST

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


		// #region SEARCH PLUGINS FROM REPO

		/**
		 * seacrh plugin in the repository using plugin_api
		 * @param {string} str
		 */
		function searchPlugins(str, page) {
			$("#plugins_result_list").empty(); // Rimuove TUTTI i risultati precedenti
			Pluginer.togglePlugins2Overlay(true);
			var data = {
				action: "plgnr_get_plugins_from_repo",
				needle: str,
				page: page,
				timestamp: new Date().getTime(), // Evita la cache
				security: pluginerAdmin.nonce,
			};
			// Request JSON and let jQuery parse it; handle parse errors via .fail
			$.post(ajaxurl, data, function (response) {
				if (response) {
					$("#plugins_result_list").find(".plugin_found_data").remove();
					var imgurl;
					if (response.plugins && response.plugins.length > 0) {
						$("#plugins_result_list").empty();
						$.each(response.plugins, function (key, entry) {
							if (entry.icons != null) {
								if (!Pluginer.isEmpty(entry.icons["svg"])) {
									imgurl = entry.icons["svg"];
								} else if (!Pluginer.isEmpty(entry.icons["1x"])) {
									imgurl = entry.icons["1x"];
								} else if (!Pluginer.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>"
							);
							Pluginer.toggleButtons();
						});
						// 🔹 Aggiorna i pulsanti di paginazione
						Pluginer.updatePaginationButtons(page, response.has_more, response.total_pages);
						// togglePlugins2Overlay(false);
					} else {
						$("#plugins_result_list").empty();
						$("#plugins_result_list").append(
							'<div style="display:flex;justify-content:center;align-items:center;height:100%;width:100%;"><p>No plugins found. Try a different search.</p></div>');
					}
				}
			}, 'json').fail(function (xhr, status, error) {
				Pluginer.togglePlugins2Overlay(false);
				console.error('Search plugins error:', status, error);
				try {
					console.log('Response Text:', xhr.responseText);
				} catch (e) {}
			});
		}

		let searchTimeout;
		$("#plugin_name").on("keyup", function (e) {
			if (
				(e.which >= 65 && e.which <= 90) || // Lettere A-Z
				e.which === 32 || // Spazio
				e.which === 8 ||  // Backspace
				e.which === 46    // Delete
			) {
				clearTimeout(searchTimeout); // Cancella il timer precedente
				const $this = $(this);
				searchTimeout = setTimeout(() => {
					pluginNameKeyup($this); // Avvia la ricerca dopo il ritardo
				}, 500); // Aspetta 500ms prima di chiamare l'API
			}
		});

		function pluginNameKeyup($this) {
			if ("undefined" !== typeof $(".plugin_found_data")) {
				$("#plugins_result_list").find(".plugin_found_data").remove();
			}
			if ($this.val().length === 0) {
				$("#plugin_slug").val("");
			}
			if ($this.val().length < 4) {
				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);
			}

		});

		// #endregion SEARCH PLUGINS FROM REPO

		// the following function is the result of merging what I have found  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);
				Pluginer.toggleButtons();
			}
		});

		$("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() === "plgnr_plugin_list") {
			$("#title-prompt-text").text("Add Plugin List name");
		}

		// #region IS_PREMIUM
		// 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: "plgnr_check_plugin_list_count",
					security: pluginerAdmin.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=plgnr_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;
									}
								});
							});
					}
				},
			});
		}

		// Aggiunge overlay alle righe della tabella che non sono la prima lista
		$('tr.type-plgnr_plugin_list.restricted td').each(function () {
			$(this).css('position', 'relative');
			const overlay = $('<div class="no-license-overlay"></div>');
			$(overlay).css({
				'position': 'absolute',
				'top': 0,
				'left': 0,
				'right': 0,
				'bottom': 0,
				'background': 'rgba(225,225,225,0.8)',
				'display': 'flex',
				'justify-content': 'center',
				'align-items': 'center',
				'font-size': '14px',
				'font-weight': 'bold',
				'color': '#444',
				'text-align': 'center',
				'z-index': 100
			});

			$(this).append(overlay);
		});

		// #endregion IS_PREMIUM

		$('.video-thumb').on('click', function () {
			var videoSrc = $(this).data('video');
			$('#modal-video').attr('src', videoSrc);
			$('#video-modal').fadeIn(300).css('display', 'flex');
		});

		$('.close, #video-modal').on('click', function (e) {
			if (e.target !== this) return;
			$('#video-modal').fadeOut(300, function () {
				$('#modal-video').attr('src', ''); // stoppa il video
			});
		});

		Pluginer.toggleButtons();
		checkFile();
		checkIfFileSelected();

	}); //ready
})(jQuery);
