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

	const config = window.WPMDEmailTemplates || {};

	if (!config.ajaxUrl && typeof window.ajaxurl !== 'undefined') {
		config.ajaxUrl = window.ajaxurl;
	}

	const app = (window.WPMDEmailTemplatesApp = window.WPMDEmailTemplatesApp || {});

	app.config = config;
	app.services = app.services || {};
	app.queue = app.queue || [];
	app.state = app.state || {
		device: 'desktop',
		htmlEditor: null,
		cssEditor: null,
	};

	app.provide = function (name, service) {
		if (!name) {
			return;
		}

		app.services[name] = service;
	};

	app.resolve = function (name) {
		return app.services[name];
	};

	app.register = function (initializer) {
		if (typeof initializer === 'function') {
			app.queue.push(initializer);
		}
	};

	app.getAjaxUrl = function () {
		if (app.config.ajaxUrl) {
			return app.config.ajaxUrl;
		}

		if (typeof window.ajaxurl !== 'undefined') {
			return window.ajaxurl;
		}

		return '';
	};

	app.utils = app.utils || {
		escapeHtml(string) {
			return String(string)
				.replace(/&/g, '&amp;')
				.replace(/</g, '&lt;')
				.replace(/>/g, '&gt;')
				.replace(/"/g, '&quot;')
				.replace(/'/g, '&#039;');
		},
	};

	$(function () {
		app.$form = $('#wpmd-email-template-form');
		app.$modal = $('#wpmd-preview-modal');
		app.$iframe = $('#wpmd-preview-frame');

		app.queue.forEach((initializer) => {
			try {
				initializer(app);
			} catch (error) {
				if (window.console && typeof window.console.error === 'function') {
					window.console.error('WPMDEmailTemplates module failed to initialise.', error);
				}
			}
		});
	});
})(window, document, jQuery);
