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

	const app = window.WPMDEmailTemplatesApp;

	if (!app) {
		return;
	}

	const modalService = {
		open(html) {
			if (!app.$modal || !app.$modal.length || !app.$iframe || !app.$iframe.length) {
				return;
			}

			try {
				const doc = app.$iframe[0].contentDocument || app.$iframe[0].contentWindow.document;
				doc.open();
				doc.write(html);
				doc.close();
			} catch (error) {
				if (window.console && typeof window.console.error === 'function') {
					window.console.error(error);
				}
			}

			app.$modal.removeAttr('hidden').addClass('is-open');
			modalService.applyDevice();
		},
		close() {
			if (!app.$modal || !app.$modal.length) {
				return;
			}

			app.$modal.attr('hidden', true).removeClass('is-open');

			if (app.$iframe && app.$iframe.length) {
				app.$iframe.attr('src', 'about:blank');
			}
		},
		applyDevice() {
			if (!app.$iframe || !app.$iframe.length) {
				return;
			}

			const device = app.state.device || 'desktop';
			let width;

			switch (device) {
				case 'mobile':
					width = 390;
					break;
				case 'tablet':
					width = 768;
					break;
				case 'desktop':
				default:
					width = '100%';
					break;
			}

			if (width === '100%') {
				app.$iframe.css({ width: '100%', margin: '0 auto' });
			} else {
				app.$iframe.css({ width: width + 'px', margin: '0 auto', display: 'block' });
			}
		},
		setDevice(device) {
			app.state.device = device || 'desktop';
			modalService.applyDevice();

			try {
				window.localStorage.setItem('wpmdPreviewDevice', app.state.device);
			} catch (error) {
				// ignore storage errors
			}
		},
	};

	app.provide('modal', modalService);

	app.register(() => {
		if (!app.$modal || !app.$modal.length) {
			return;
		}

		app.$modal.on('click', '.wpmd-modal__close, .wpmd-modal__backdrop', function (event) {
			event.preventDefault();
			modalService.close();
		});

		$(document).on('keyup.wpmdModal', function (event) {
			if (event.key === 'Escape' && app.$modal.hasClass('is-open')) {
				modalService.close();
			}
		});

		try {
			const saved = window.localStorage.getItem('wpmdPreviewDevice');
			if (saved) {
				app.state.device = saved;
			}
		} catch (error) {
			// ignore storage errors
		}

		modalService.applyDevice();
	});
})(window, jQuery);
