(function () {
	'use strict';

	var cfg = window.wppsImageSizesPanelList;
	if (!cfg) {
		return;
	}

	var pop = null;
	var prevFocus = null;
	var focusable = 'button,[href],input';

	function esc(s) {
		return String(s || '')
			.replace(/&/g, '&amp;')
			.replace(/"/g, '&quot;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;');
	}

	function copyUrl(url) {
		if (navigator.clipboard && navigator.clipboard.writeText) {
			return navigator.clipboard.writeText(url);
		}
		return new Promise(function (resolve, reject) {
			var input = document.createElement('input');
			input.value = url;
			input.style.cssText = 'position:fixed;left:-9999px';
			document.body.appendChild(input);
			input.select();
			try {
				document.execCommand('copy');
				resolve();
			} catch (err) {
				reject(err);
			}
			input.remove();
		});
	}

	function centerPopover(el) {
		el.style.left = '50%';
		el.style.top = '50%';
		el.style.bottom = 'auto';
		el.style.transform = 'translate(-50%,-50%)';
	}

	function trapTab(e) {
		if (e.key !== 'Tab' || !pop || pop.style.display === 'none') {
			return;
		}
		var nodes = Array.from(pop.querySelectorAll(focusable)).filter(function (node) {
			return !node.disabled && node.offsetParent;
		});
		if (!nodes.length) {
			return;
		}
		var first = nodes[0];
		var last = nodes[nodes.length - 1];
		if (e.shiftKey) {
			if (document.activeElement === first) {
				e.preventDefault();
				last.focus();
			}
		} else if (document.activeElement === last) {
			e.preventDefault();
			first.focus();
		}
	}

	function getPopover() {
		if (!pop) {
			pop = document.createElement('div');
			pop.id = 'wpps-isp-pop';
			pop.setAttribute('role', 'dialog');
			pop.setAttribute('aria-modal', 'true');
			pop.setAttribute('aria-labelledby', 'wpps-isp-ttl');
			pop.setAttribute('aria-hidden', 'true');
			pop.className = 'wpps-image-sizes-popover';
			pop.innerHTML =
				'<div class="wpps-isp-pop-inner">' +
				'<h3 id="wpps-isp-ttl" class="wpps-isp-pop-title"></h3>' +
				'<div class="wpps-isp-ct"></div>' +
				'</div>';
			document.body.appendChild(pop);
		}
		return pop;
	}

	function bindCopyButtons(container) {
		container.querySelectorAll('.wpps-isp-url').forEach(function (input) {
			input.onclick = function () {
				this.select();
			};
		});
		container.querySelectorAll('.wpps-isp-cpy').forEach(function (btn) {
			btn.onclick = function () {
				var url = btn.getAttribute('data-url');
				if (!url) {
					return;
				}
				copyUrl(url).then(function () {
					var label = btn.textContent;
					btn.textContent = cfg.i18n.copied;
					btn.disabled = true;
					btn.setAttribute('aria-label', cfg.i18n.copied);
					setTimeout(function () {
						btn.textContent = label;
						btn.disabled = false;
						btn.removeAttribute('aria-label');
					}, 1500);
				});
			};
		});
	}

	function renderSizes(container, sizes) {
		var html = '';
		sizes.forEach(function (size) {
			html +=
				'<div class="wpps-isp-pop-row">' +
				'<div class="wpps-isp-pop-meta">' +
				'<strong class="wpps-isp-pop-name">' +
				esc(size.name) +
				'</strong>' +
				'<span class="wpps-isp-pop-dims">' +
				esc(size.dimensions) +
				'</span>' +
				'</div>' +
				'<div class="wpps-isp-pop-url-row">' +
				'<input type="text" class="wpps-isp-url" value="' +
				esc(size.url) +
				'" readonly />' +
				'<button type="button" class="button button-small wpps-isp-cpy" data-url="' +
				esc(size.url) +
				'">' +
				esc(cfg.i18n.copy) +
				'</button>' +
				'</div>' +
				'</div>';
		});
		container.innerHTML = html;
		bindCopyButtons(container);
		var first = container.querySelector('.wpps-isp-url,.wpps-isp-cpy');
		if (first) {
			first.focus();
		}
	}

	function renderEmpty(container) {
		container.innerHTML =
			'<p class="description wpps-isp-pop-empty">' +
			esc(cfg.i18n.none) +
			'</p>' +
			'<p class="description wpps-isp-pop-hint">' +
			esc(cfg.i18n.hint) +
			'</p>' +
			'<a href="' +
			esc(cfg.regen) +
			'" class="button button-small" target="_blank" rel="noopener">' +
			esc(cfg.i18n.open) +
			'</a>';
	}

	function renderError(container) {
		container.innerHTML =
			'<p class="description wpps-isp-pop-error">' + esc(cfg.i18n.err) + '</p>';
	}

	function showPopover(trigger, attachmentId) {
		if (!attachmentId) {
			return;
		}

		prevFocus = document.activeElement;
		var el = getPopover();
		var content = el.querySelector('.wpps-isp-ct');
		var title = el.querySelector('#wpps-isp-ttl');

		title.textContent = cfg.i18n.title;
		content.innerHTML =
			'<div class="wpps-isp-pop-loading">' +
			'<span class="spinner is-active"></span>' +
			'<span>' +
			esc(cfg.i18n.load) +
			'</span>' +
			'</div>';
		el.style.display = 'block';
		el.setAttribute('aria-hidden', 'false');
		centerPopover(el);

		var xhr = new XMLHttpRequest();
		xhr.open('POST', cfg.ajax);
		xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		xhr.onload = function () {
			try {
				var response = JSON.parse(xhr.responseText);
				if (response.success && response.data && response.data.sizes && response.data.sizes.length) {
					renderSizes(content, response.data.sizes);
				} else {
					renderEmpty(content);
				}
			} catch (err) {
				renderError(content);
			}
		};
		xhr.onerror = function () {
			renderError(content);
		};
		xhr.send(
			'action=wpps_image_sizes_panel_get_sizes&nonce=' +
				encodeURIComponent(cfg.nonce) +
				'&attachment_id=' +
				encodeURIComponent(attachmentId)
		);
	}

	function hidePopover() {
		var el = document.getElementById('wpps-isp-pop');
		if (el) {
			el.style.display = 'none';
			el.setAttribute('aria-hidden', 'true');
		}
		if (prevFocus && prevFocus.focus) {
			prevFocus.focus();
		}
	}

	document.addEventListener(
		'click',
		function (e) {
			var trigger = e.target.closest('.wpps-image-sizes-trigger');
			if (trigger) {
				e.preventDefault();
				e.stopPropagation();
				showPopover(trigger, trigger.getAttribute('data-attachment-id'));
				return;
			}
			if (pop && !pop.contains(e.target) && !e.target.closest('.wpps-image-sizes-trigger')) {
				hidePopover();
			}
		},
		true
	);

	document.addEventListener('keydown', function (e) {
		if (e.key === 'Escape') {
			hidePopover();
		} else {
			trapTab(e);
		}
	});
})();
