(function ($) {
	'use strict';

	var $dialog = null;
	var callback = null;

	function ensureDialog() {
		if ($dialog && $dialog.length) return;
		$('body').append(
			'<div id="rc-confirm-dialog" class="rc-confirm-dialog" hidden>' +
				'<div class="rc-confirm-backdrop"></div>' +
				'<div class="rc-confirm-box">' +
					'<p class="rc-confirm-message" id="rc-confirm-message"></p>' +
					'<div class="rc-confirm-actions">' +
						'<button type="button" class="button button-primary rc-confirm-ok"></button>' +
						'<button type="button" class="button rc-modal-cancel rc-confirm-cancel"></button>' +
					'</div>' +
				'</div>' +
			'</div>'
		);
		$dialog = $('#rc-confirm-dialog');
		$dialog.on('click', '.rc-confirm-ok', function () {
			$dialog.prop('hidden', true);
			if (typeof callback === 'function') callback(true);
			callback = null;
		});
		$dialog.on('click', '.rc-confirm-backdrop, .rc-confirm-cancel', function () {
			$dialog.prop('hidden', true);
			if (typeof callback === 'function') callback(false);
			callback = null;
		});
		$(document).on('keydown', function (e) {
			if (e.key === 'Escape' && !$dialog.prop('hidden')) {
				$dialog.prop('hidden', true);
				if (typeof callback === 'function') callback(false);
				callback = null;
			}
		});
	}

	window.rcConfirm = function (message, cb, opts) {
		opts = opts || {};
		ensureDialog();
		callback = cb;
		$('#rc-confirm-message').text(message);
		$dialog.find('.rc-confirm-ok').text(opts.okLabel || rcConfirmL10n.ok);
		$dialog.find('.rc-confirm-cancel').text(opts.cancelLabel || rcConfirmL10n.cancel);
		$dialog.prop('hidden', false);
		$dialog.find('.rc-confirm-ok').trigger('focus');
	};

})(jQuery);
