/* global jQuery, wp, nzpIglAdmin */
(function ($) {
	'use strict';

	function syncIds() {
		var ids = [];
		$('#nzp_igl_sortable li').each(function () {
			ids.push($(this).data('id'));
		});
		$('#nzp_igl_image_ids').val(ids.join(','));
	}

	function addThumb(id, url) {
		if ($('#nzp_igl_sortable li[data-id="' + id + '"]').length) {
			return;
		}
		var $li = $('<li class="nzp-igl-admin__thumb" data-id="' + id + '">' +
			'<span class="nzp-igl-admin__thumb-inner">' +
			'<img src="' + url + '" width="80" height="80" alt="" loading="lazy" />' +
			'</span></li>');
		var $btn = $('<button type="button" class="nzp-igl-admin__remove">&times;</button>');
		$btn.attr('aria-label', nzpIglAdmin.removeLabel || '');
		$li.find('.nzp-igl-admin__thumb-inner').append($btn);
		$('#nzp_igl_sortable').append($li);
	}

	$(function () {
		var frame;

		$('#nzp_igl_select_images').on('click', function (e) {
			e.preventDefault();
			if (frame) {
				frame.open();
				return;
			}
			frame = wp.media({
				title: nzpIglAdmin.frameTitle,
				button: { text: nzpIglAdmin.frameButton },
				multiple: true,
				library: { type: 'image' }
			});
			frame.on('select', function () {
				var maxImages = parseInt(nzpIglAdmin.maxImages, 10) || 100;
				var sel = frame.state().get('selection');
				var warned = false;
				sel.each(function (attachment) {
					var n = $('#nzp_igl_sortable li').length;
					if (n >= maxImages) {
						if (!warned && nzpIglAdmin.maxImagesMsg) {
							warned = true;
							window.alert(nzpIglAdmin.maxImagesMsg);
						}
						return;
					}
					var a = attachment.toJSON();
					var id = a.id;
					var url = (a.sizes && a.sizes.thumbnail && a.sizes.thumbnail.url) ? a.sizes.thumbnail.url : a.url;
					addThumb(id, url);
				});
				syncIds();
			});
			frame.open();
		});

		$('#nzp_igl_sortable').on('click', '.nzp-igl-admin__remove', function () {
			$(this).closest('li').remove();
			syncIds();
		});

		if ($.fn.sortable) {
			$('#nzp_igl_sortable').sortable({
				stop: syncIds
			});
		}

		$('#nzp_igl_clear_images').on('click', function (e) {
			e.preventDefault();
			$('#nzp_igl_sortable').empty();
			syncIds();
		});

		$('#nzp-igl-copy-shortcode').on('click', function () {
			var el = document.getElementById('nzp-igl-shortcode-text');
			if (!el) {
				return;
			}
			var text = el.textContent;
			if (navigator.clipboard && navigator.clipboard.writeText) {
				navigator.clipboard.writeText(text).then(function () {
					window.alert(nzpIglAdmin.copied);
				});
			} else {
				var ta = document.createElement('textarea');
				ta.value = text;
				document.body.appendChild(ta);
				ta.select();
				try {
					document.execCommand('copy');
					window.alert(nzpIglAdmin.copied);
				} catch (err) {}
				document.body.removeChild(ta);
			}
		});

		$('.nzp-igl-color-field').wpColorPicker();
	});
})(jQuery);
