/* global window, document */
(function (window, document) {
	'use strict';

	const config = window.MailDoctorAdmin || {};
	const queue = [];
	const services = {};
	const app = {
		config,
		ajaxUrl: config.ajaxUrl || '',
		adminPostUrl: config.adminPostUrl || '',
		nonces: config.nonces || {},
		i18n: config.i18n || {},
		woo: config.woo || {},
		screen: config.screen || '',
		provide(name, service) {
			if (!name) {
				return;
			}

			services[name] = service;
		},
		register(callback) {
			if (typeof callback === 'function') {
				queue.push(callback);
			}
		},
		registerService(name, service) {
			if (!name) {
				return;
			}

			services[name] = service;
		},
		resolve(name) {
			if (!name || !Object.prototype.hasOwnProperty.call(services, name)) {
				return null;
			}

			return services[name];
		},
		utils: {
			formatNumber(value) {
				if (typeof Intl !== 'undefined' && Intl.NumberFormat) {
					return new Intl.NumberFormat(undefined, { maximumFractionDigits: 0 }).format(Number(value) || 0);
				}

				const numeric = Number(value) || 0;
				return String(Math.round(numeric));
			},
		},
	};

	window.MailDoctorAdminApp = app;

	function runQueue() {
		if (app._ready) {
			return;
		}

		app._ready = true;
		while (queue.length) {
			const task = queue.shift();
			try {
				task(app);
			} catch (error) {
				// Keep other initializers running even if one fails.
				if (window.console && typeof window.console.error === 'function') {
					window.console.error('Mail Doctor admin init failed', error);
				}
			}
		}
	}

	if ('complete' === document.readyState || 'interactive' === document.readyState) {
		window.setTimeout(runQueue, 0);
	} else {
		document.addEventListener('DOMContentLoaded', runQueue, false);
	}
})(window, document);
