(function () {
	'use strict';

	var activeModal = null;
	var lastFocused = null;

	function getFocusableElements(dialog) {
		return Array.prototype.slice.call(
			dialog.querySelectorAll(
				'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
			)
		).filter(function (element) {
			return !element.hasAttribute('hidden') && element.offsetParent !== null;
		});
	}

	function openModal(modal, opener) {
		if (!modal) {
			return;
		}

		var dialog = modal.querySelector('[role="dialog"]');
		lastFocused = opener || document.activeElement;
		activeModal = modal;
		modal.hidden = false;
		document.body.classList.add('pendid-ai-studio-modal-open');

		window.requestAnimationFrame(function () {
			if (dialog) {
				dialog.focus();
			}
		});
	}

	function closeModal(modal) {
		if (!modal) {
			return;
		}

		modal.hidden = true;
		activeModal = null;
		document.body.classList.remove('pendid-ai-studio-modal-open');

		if (lastFocused && typeof lastFocused.focus === 'function') {
			lastFocused.focus();
		}
	}

	Array.prototype.forEach.call(document.querySelectorAll('.pendid-ai-studio-open-connect-modal'), function (opener) {
		opener.addEventListener('click', function (event) {
			event.preventDefault();
			openModal(document.getElementById('pendid-ai-studio-connect-modal'), opener);
		});
	});

	Array.prototype.forEach.call(document.querySelectorAll('[data-pendid-modal-open]'), function (opener) {
		opener.addEventListener('click', function (event) {
			var modalId = opener.getAttribute('data-pendid-modal-open');
			var modal = modalId ? document.getElementById(modalId) : null;

			if (modal) {
				event.preventDefault();
				openModal(modal, opener);
			}
		});
	});

	Array.prototype.forEach.call(document.querySelectorAll('.pendid-ai-studio-modal'), function (modal) {
		Array.prototype.forEach.call(modal.querySelectorAll('[data-pendid-modal-close]'), function (closer) {
			closer.addEventListener('click', function () {
				closeModal(modal);
			});
		});
	});

	document.addEventListener('keydown', function (event) {
		if (!activeModal || activeModal.hidden) {
			return;
		}

		if (event.key === 'Escape') {
			event.preventDefault();
			closeModal(activeModal);
			return;
		}

		if (event.key !== 'Tab') {
			return;
		}

		var dialog = activeModal.querySelector('[role="dialog"]');
		var focusable = dialog ? getFocusableElements(dialog) : [];

		if (!focusable.length) {
			event.preventDefault();
			if (dialog) {
				dialog.focus();
			}
			return;
		}

		var first = focusable[0];
		var last = focusable[focusable.length - 1];

		if (event.shiftKey && document.activeElement === first) {
			event.preventDefault();
			last.focus();
		} else if (!event.shiftKey && document.activeElement === last) {
			event.preventDefault();
			first.focus();
		}
	});

	var generationForm = document.querySelector('[data-pendid-generation-form]');

	if (generationForm) {
		var generateButton = generationForm.querySelector('[data-pendid-generate-button]');
		var generateLabel = generationForm.querySelector('[data-pendid-generate-label]');
		var generateIcon = generationForm.querySelector('[data-pendid-generate-icon]');
		var generateSpinner = generationForm.querySelector('[data-pendid-generate-spinner]');
		var generationStatus = generationForm.querySelector('[data-pendid-generation-status]');
		var originalLabel = generateLabel ? generateLabel.textContent : '';
		var loadingLabel = generationForm.getAttribute('data-pendid-loading-label') || originalLabel;
		var isSubmitting = false;

		function resetGenerationForm() {
			isSubmitting = false;
			generationForm.classList.remove('is-submitting');
			generationForm.removeAttribute('aria-busy');

			if (generateButton) {
				generateButton.disabled = false;
				generateButton.removeAttribute('aria-disabled');
			}

			if (generateLabel) {
				generateLabel.textContent = originalLabel;
			}

			if (generateIcon) {
				generateIcon.hidden = false;
			}

			if (generateSpinner) {
				generateSpinner.hidden = true;
			}

			if (generationStatus) {
				generationStatus.hidden = true;
			}
		}

		generationForm.addEventListener('submit', function (event) {
			if (isSubmitting) {
				event.preventDefault();
				return;
			}

			if (typeof generationForm.checkValidity === 'function' && !generationForm.checkValidity()) {
				return;
			}

			isSubmitting = true;
			generationForm.classList.add('is-submitting');
			generationForm.setAttribute('aria-busy', 'true');

			if (generateButton) {
				generateButton.disabled = true;
				generateButton.setAttribute('aria-disabled', 'true');
			}

			if (generateLabel) {
				generateLabel.textContent = loadingLabel;
			}

			if (generateIcon) {
				generateIcon.hidden = true;
			}

			if (generateSpinner) {
				generateSpinner.hidden = false;
			}

			if (generationStatus) {
				generationStatus.hidden = false;
			}
		});

		window.addEventListener('pageshow', resetGenerationForm);
	}

	var autoOpenModal = document.querySelector('.pendid-ai-studio-modal[data-pendid-auto-open="true"]');

	if (autoOpenModal) {
		window.requestAnimationFrame(function () {
			openModal(autoOpenModal, null);
		});
	}

	var toneInputs = document.querySelectorAll('[data-pendid-tone-input]');
	var selectedToneLabel = document.querySelector('[data-pendid-selected-tone]');
	var toneCards = document.querySelectorAll('[data-pendid-tone-card]');
	var toneThumbs = document.querySelectorAll('[data-pendid-tone-value]');

	function updateToneSelection(input) {
		if (!input) {
			return;
		}

		var value = input.value;
		var title = input.getAttribute('data-pendid-tone-title') || value;

		Array.prototype.forEach.call(toneCards, function (card) {
			card.classList.toggle('is-active', card.getAttribute('data-pendid-tone-value') === value);
		});

		Array.prototype.forEach.call(toneThumbs, function (thumb) {
			thumb.classList.toggle('is-active', thumb.getAttribute('data-pendid-tone-value') === value);
		});

		if (selectedToneLabel) {
			selectedToneLabel.textContent = title;
		}
	}

	Array.prototype.forEach.call(toneInputs, function (input) {
		input.addEventListener('change', function () {
			updateToneSelection(input);
			var modal = document.getElementById('pendid-ai-studio-tone-modal');
			window.setTimeout(function () {
				closeModal(modal);
			}, 120);
		});
	});

	var referenceInput = document.querySelector('[data-pendid-reference-input]');
	var referencePreview = document.querySelector('[data-pendid-reference-preview]');
	var referenceObjectUrl = null;

	if (referenceInput && referencePreview) {
		referenceInput.addEventListener('change', function () {
			var file = referenceInput.files && referenceInput.files[0] ? referenceInput.files[0] : null;

			if (referenceObjectUrl) {
				URL.revokeObjectURL(referenceObjectUrl);
				referenceObjectUrl = null;
			}

			referencePreview.innerHTML = '';

			if (!file) {
				var icon = document.createElement('span');
				icon.className = 'dashicons dashicons-format-image';
				icon.setAttribute('aria-hidden', 'true');
				referencePreview.appendChild(icon);
				return;
			}

			referenceObjectUrl = URL.createObjectURL(file);
			var image = document.createElement('img');
			image.src = referenceObjectUrl;
			image.alt = '';
			image.setAttribute('aria-hidden', 'true');
			referencePreview.appendChild(image);
		});
	}

})();
