(function () {
	'use strict';

	document.addEventListener('click', function (event) {
		var button = event.target.closest('[data-wpdude-dc-copy-address]');
		if (!button) {
			return;
		}

		var text = button.getAttribute('data-wpdude-dc-copy-address') || '';
		if (!text) {
			return;
		}

		var feedback = button.parentNode
			? button.parentNode.querySelector('.wpdude-dc-order-detail__copy-feedback')
			: null;

		function showCopied() {
			if (!feedback) {
				return;
			}
			feedback.hidden = false;
			window.setTimeout(function () {
				feedback.hidden = true;
			}, 2000);
		}

		if (navigator.clipboard && navigator.clipboard.writeText) {
			navigator.clipboard.writeText(text).then(showCopied).catch(function () {
				fallbackCopy(text, showCopied);
			});
			return;
		}

		fallbackCopy(text, showCopied);
	});

	function fallbackCopy(text, onSuccess) {
		var area = document.createElement('textarea');
		area.value = text;
		area.setAttribute('readonly', '');
		area.style.position = 'absolute';
		area.style.left = '-9999px';
		document.body.appendChild(area);
		area.select();
		try {
			document.execCommand('copy');
			onSuccess();
		} catch (e) {
			// Ignore.
		}
		document.body.removeChild(area);
	}
})();
