(function () {
	'use strict';

	function isEditForm(form) {
		var mode = form.querySelector('[name="pendid_mode"]');
		return Boolean(mode && mode.value === 'edit');
	}

	function getCopy() {
		var config = window.pendidImageWorkspace || {};
		var messages = Array.isArray(config.loadingMessages) ? config.loadingMessages.filter(Boolean) : [];

		return {
			title: config.loadingTitle || 'Pendid is creating your image',
			messages: messages.length ? messages : [
				'Preparing your request...',
				'Building the composition...',
				'Refining the visual details...',
				'Getting the result ready for WordPress...'
			]
		};
	}

	function startCanvasProgress() {
		var stage = document.querySelector('.pendid-ai-studio-preview-stage');
		if (!stage || stage.querySelector('.pendid-v12-generating')) return;

		var copy = getCopy();
		var overlay = document.createElement('div');
		var spinner = document.createElement('span');
		var title = document.createElement('h3');
		var message = document.createElement('p');
		var messageIndex = 0;

		overlay.className = 'pendid-v12-generating';
		overlay.setAttribute('role', 'status');
		overlay.setAttribute('aria-live', 'polite');
		spinner.className = 'pendid-v12-generating-spinner';
		spinner.setAttribute('aria-hidden', 'true');
		title.textContent = copy.title;
		message.className = 'pendid-v12-generating-message';
		message.textContent = copy.messages[0];

		overlay.appendChild(spinner);
		overlay.appendChild(title);
		overlay.appendChild(message);
		stage.appendChild(overlay);
		stage.classList.add('is-generating');

		window.setInterval(function () {
			messageIndex = (messageIndex + 1) % copy.messages.length;
			message.classList.remove('is-visible');
			window.setTimeout(function () {
				message.textContent = copy.messages[messageIndex];
				message.classList.add('is-visible');
			}, 160);
		}, 3600);

		message.classList.add('is-visible');
	}

	document.addEventListener('DOMContentLoaded', function () {
		var forms = document.querySelectorAll('[data-pendid-v12-form]');
		for (var i = 0; i < forms.length; i += 1) {
			(function (form) {
				if (isEditForm(form)) return;
				form.addEventListener('submit', function () {
					if (!form.checkValidity()) return;
					startCanvasProgress();
				});
			}(forms[i]));
		}
	});
}());
