(function (window, $) {
	'use strict';

	const app = window.WPMDEmailTemplatesApp;

	if (!app) {
		return;
	}

	app.register(() => {
		const notices = app.resolve('notices');

		$(document).on('click', '.wpmd-variable', function (event) {
			const token = $(event.currentTarget).data('token');

			if (!token) {
				return;
			}

			const text = '{{' + token + '}}';
			const successMessage = app.config.i18n && app.config.i18n.copySuccess ? app.config.i18n.copySuccess : 'Copied.';
			const errorMessage = app.config.i18n && app.config.i18n.copyError ? app.config.i18n.copyError : 'Copy failed.';

			if (navigator.clipboard && navigator.clipboard.writeText) {
				navigator.clipboard
					.writeText(text)
					.then(() => {
						if (notices) {
							notices.show(successMessage);
						}
					})
					.catch(() => {
						window.alert(errorMessage);
					});
				return;
			}

			const $temp = $('<input type="text" style="position:absolute;left:-9999px;" />');
			$('body').append($temp);
			$temp.val(text).select();

			try {
				document.execCommand('copy');
				if (notices) {
					notices.show(successMessage);
				}
			} catch (error) {
				window.alert(errorMessage);
			}

			$temp.remove();
		});
	});
})(window, jQuery);
