(function () {
	'use strict';

	var activeDynamicModal = null;
	var activeDynamicOpener = null;
	var scriptSource = document.currentScript && document.currentScript.src ? document.currentScript.src : '';

	function isPersian() {
		var lang = document.documentElement && document.documentElement.lang ? document.documentElement.lang : '';
		return /^fa(?:-|_|$)/i.test(lang);
	}

	function uiText(english, persian) {
		return isPersian() ? persian : english;
	}

	function formatNumber(value) {
		return Number(value || 0).toLocaleString(isPersian() ? 'fa-IR' : 'en-US');
	}

	function creditsText(value) {
		return isPersian() ? formatNumber(value) + ' اعتبار' : formatNumber(value) + ' credits';
	}

	function referenceLimitText(max) {
		return isPersian()
			? 'برای پلن فعلی پن‌دید می‌توانید حداکثر ' + formatNumber(max) + ' عکس آپلود کنید.'
			: 'You can upload up to ' + formatNumber(max) + ' images for the current Pendid plan.';
	}

	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.hidden && element.offsetParent !== null;
		});
	}

	function openDynamicModal(modal, opener) {
		if (!modal) return;
		activeDynamicModal = modal;
		activeDynamicOpener = opener || document.activeElement;
		modal.hidden = false;
		document.body.classList.add('pendid-ai-studio-modal-open');
		window.requestAnimationFrame(function () {
			var dialog = modal.querySelector('[role="dialog"]');
			if (dialog) dialog.focus();
		});
	}

	function closeDynamicModal(modal) {
		if (!modal) return;
		modal.hidden = true;
		if (activeDynamicModal === modal) activeDynamicModal = null;
		document.body.classList.remove('pendid-ai-studio-modal-open');
		if (activeDynamicOpener && typeof activeDynamicOpener.focus === 'function') {
			activeDynamicOpener.focus();
		}
		activeDynamicOpener = null;
	}

	function createModal(id, title, description, extraModalClass, extraDialogClass) {
		var root = document.querySelector('.pendid-v12-wrap') || document.body;
		var modal = document.createElement('div');
		var backdrop = document.createElement('div');
		var dialog = document.createElement('section');
		var closeButton = document.createElement('button');
		var eyebrow = document.createElement('p');
		var heading = document.createElement('h2');
		var body = document.createElement('div');

		modal.id = id;
		modal.className = 'pendid-ai-studio-modal' + (extraModalClass ? ' ' + extraModalClass : '');
		modal.hidden = true;
		backdrop.className = 'pendid-ai-studio-modal-backdrop';
		dialog.className = 'pendid-ai-studio-modal-dialog' + (extraDialogClass ? ' ' + extraDialogClass : '');
		dialog.setAttribute('role', 'dialog');
		dialog.setAttribute('aria-modal', 'true');
		dialog.setAttribute('aria-labelledby', id + '-title');
		dialog.setAttribute('tabindex', '-1');
		closeButton.type = 'button';
		closeButton.className = 'pendid-ai-studio-modal-close';
		closeButton.setAttribute('aria-label', uiText('Close dialog', 'بستن پنجره'));
		closeButton.innerHTML = '<span class="dashicons dashicons-no-alt" aria-hidden="true"></span>';
		eyebrow.className = 'pendid-ai-studio-eyebrow';
		eyebrow.textContent = 'Pendid Image';
		heading.id = id + '-title';
		heading.textContent = title;
		dialog.appendChild(closeButton);
		dialog.appendChild(eyebrow);
		dialog.appendChild(heading);

		if (description) {
			var paragraph = document.createElement('p');
			paragraph.className = 'pendid-ai-studio-modal-description';
			paragraph.textContent = description;
			dialog.appendChild(paragraph);
		}

		body.className = 'pendid-v12-modal-body';
		dialog.appendChild(body);
		modal.appendChild(backdrop);
		modal.appendChild(dialog);
		root.appendChild(modal);
		backdrop.addEventListener('click', function () { closeDynamicModal(modal); });
		closeButton.addEventListener('click', function () { closeDynamicModal(modal); });
		return { modal: modal, dialog: dialog, body: body };
	}

	document.addEventListener('keydown', function (event) {
		if (!activeDynamicModal || activeDynamicModal.hidden) return;
		if (event.key === 'Escape') {
			event.preventDefault();
			closeDynamicModal(activeDynamicModal);
			return;
		}
		if (event.key !== 'Tab') return;
		var dialog = activeDynamicModal.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();
		}
	});

	function parseConfig(form) {
		try {
			return JSON.parse(form.getAttribute('data-pendid-price-config') || '{}');
		} catch (error) {
			return {};
		}
	}

	function selectedTier(form) {
		var node = form.querySelector('input[name="pendid_model_tier"]:checked');
		return node ? node.value : 'standard';
	}

	function selectedOutputSize(form) {
		var node = form.querySelector('input[name="pendid_output_size"]:checked');
		return node ? node.value : '1:1';
	}

	function isPrimarySize(size) {
		return size === '1:1' || size === '3:2' || size === '2:3';
	}

	function hasUploadedInput(form) {
		if ((form.querySelector('[name="pendid_mode"]') || {}).value === 'edit') return true;
		var files = form.querySelector('[data-pendid-v12-inputs]');
		return Boolean(files && files.files && files.files.length);
	}

	function brandKitChecked(form) {
		var brand = form.querySelector('input[name="pendid_brand_kit"]');
		return Boolean(brand && brand.checked && !brand.disabled);
	}

	function brandKitState(form) {
		var config = parseConfig(form);
		var pricing = config.pricing || {};
		return pricing.brand_kit && typeof pricing.brand_kit === 'object' ? pricing.brand_kit : {};
	}

	function hasEffectiveInput(form) {
		if (hasUploadedInput(form)) return true;
		var state = brandKitState(form);
		return brandKitChecked(form) && state.configured === true && state.has_logo === true;
	}

	function sizeSurcharge(config, size) {
		var rows = Array.isArray(config.surcharges) ? config.surcharges : [];
		for (var i = 0; i < rows.length; i += 1) {
			if (rows[i].model_value === size && rows[i].is_active) {
				return Number(rows[i].extra_credit_cost || 0);
			}
		}
		return 0;
	}

	function updatePrice(form) {
		var target = form.querySelector('[data-pendid-v12-price]');
		if (!target) return;
		var config = parseConfig(form);
		var pricing = config.pricing || {};
		var variants = Array.isArray(pricing.variants) ? pricing.variants : [];
		var tier = selectedTier(form);
		var size = selectedOutputSize(form);
		var input = hasEffectiveInput(form);
		var cost = Number(pricing.credit_cost || 0);

		for (var i = 0; i < variants.length; i += 1) {
			if (variants[i].key !== tier) continue;
			if (tier === 'standard' && !input && isPrimarySize(size) && variants[i].text_only_is_active) {
				cost = Number(variants[i].text_only_credit_cost || variants[i].credit_cost || cost);
			} else {
				cost = Number(variants[i].credit_cost || cost);
			}
			break;
		}

		cost += sizeSurcharge(config, size);
		target.textContent = cost > 0 ? creditsText(cost) : '—';
	}

	function syncBrandKitControl(form) {
		var input = form.querySelector('input[name="pendid_brand_kit"]');
		if (!input) return;
		var wrapper = input.closest('.pendid-v12-switch');
		var state = brandKitState(form);
		if (!state || Object.keys(state).length === 0) {
			input.disabled = true;
			if (wrapper) wrapper.hidden = true;
			return;
		}
		if (state.allowed !== true) {
			input.checked = false;
			input.disabled = true;
			if (wrapper) wrapper.hidden = true;
			return;
		}
		if (wrapper) wrapper.hidden = false;
		if (state.configured !== true) {
			input.checked = false;
			input.disabled = true;
			if (wrapper) {
				var helper = wrapper.querySelector('small');
				if (helper) helper.textContent = uiText('Configure Brand Kit in your Pendid account first.', 'ابتدا کیت برند را در حساب پن‌دید تنظیم کنید.');
			}
			return;
		}
		input.disabled = false;
	}

	function enhancePurposePicker(form) {
		var fieldset = form.querySelector('.pendid-ai-studio-purpose-fieldset');
		var grid = fieldset ? fieldset.querySelector('.pendid-ai-studio-purpose-grid') : null;
		if (!fieldset || !grid) return;
		var radios = grid.querySelectorAll('input[name="pendid_image_purpose"]');
		if (!radios.length) return;
		if (!form.id) form.id = 'pendid-v12-generation-form';
		for (var i = 0; i < radios.length; i += 1) radios[i].setAttribute('form', form.id);

		var trigger = document.createElement('button');
		var triggerCopy = document.createElement('span');
		var triggerTitle = document.createElement('strong');
		var triggerHelper = document.createElement('small');
		var triggerIcon = document.createElement('span');
		trigger.type = 'button';
		trigger.className = 'pendid-v12-purpose-trigger';
		triggerCopy.className = 'pendid-v12-purpose-trigger-copy';
		triggerIcon.className = 'dashicons dashicons-arrow-right-alt2';
		triggerIcon.setAttribute('aria-hidden', 'true');
		triggerCopy.appendChild(triggerTitle);
		triggerCopy.appendChild(triggerHelper);
		trigger.appendChild(triggerCopy);
		trigger.appendChild(triggerIcon);
		fieldset.insertBefore(trigger, grid);

		var modalParts = createModal(
			'pendid-v12-purpose-modal',
			uiText('Choose the image purpose', 'کاربرد تصویر را انتخاب کنید'),
			uiText('Pick what the image is for. This helps Pendid shape the composition for your website.', 'مشخص کنید تصویر برای چه بخشی است تا پندید ترکیب‌بندی مناسب‌تری برای سایت بسازد.'),
			'pendid-v12-purpose-modal',
			'pendid-v12-purpose-dialog'
		);
		grid.classList.add('pendid-v12-purpose-modal-grid');
		modalParts.body.appendChild(grid);

		function updatePurposeSelection() {
			var selected = null;
			for (var index = 0; index < radios.length; index += 1) {
				if (radios[index].checked) { selected = radios[index]; break; }
			}
			if (!selected) selected = radios[0];
			if (!selected) return;
			var label = selected.closest('label');
			var title = label ? label.querySelector('strong') : null;
			var helper = label ? label.querySelector('small') : null;
			triggerTitle.textContent = title ? title.textContent : selected.value;
			triggerHelper.textContent = helper ? helper.textContent : '';
		}

		trigger.addEventListener('click', function () { openDynamicModal(modalParts.modal, trigger); });
		for (var j = 0; j < radios.length; j += 1) {
			radios[j].addEventListener('change', function (event) {
				if (!event.target.checked) return;
				updatePurposeSelection();
				closeDynamicModal(modalParts.modal);
			});
		}
		updatePurposeSelection();
	}

	function pluginAssetBase() {
		if (!scriptSource) return '';
		return scriptSource.replace(/assets\/image-workspace\.js(?:\?.*)?$/i, 'assets/images/tones/');
	}

	function toneImageUrl(toneId) {
		if (!toneId || toneId === 'free' || !/^[a-z0-9-]+$/i.test(toneId)) return '';
		var allowed = ['professional','sales','luxury','modern','minimal','friendly','happy','playful','bold','formal','tech','natural','editorial'];
		if (allowed.indexOf(toneId) === -1) return '';
		var base = pluginAssetBase();
		return base ? base + 'tone-' + toneId + '.webp' : '';
	}

	function createTonePlaceholder() {
		var placeholder = document.createElement('span');
		var icon = document.createElement('span');
		placeholder.className = 'pendid-ai-studio-tone-placeholder';
		icon.className = 'dashicons dashicons-art';
		icon.setAttribute('aria-hidden', 'true');
		placeholder.appendChild(icon);
		return placeholder;
	}

	function createToneVisual(toneId) {
		var url = toneImageUrl(toneId);
		if (!url) return createTonePlaceholder();
		var image = document.createElement('img');
		image.src = url;
		image.alt = '';
		image.loading = 'lazy';
		image.setAttribute('aria-hidden', 'true');
		image.addEventListener('error', function () {
			if (image.parentNode) image.parentNode.replaceChild(createTonePlaceholder(), image);
		});
		return image;
	}

	function enhanceTonePicker(form) {
		var select = form.querySelector('select[name="pendid_image_tone"]');
		if (!select) return;
		var field = select.closest('.pendid-ai-studio-field');
		if (!field) return;
		var originalLabel = field.querySelector('label');
		var options = Array.prototype.slice.call(select.options || []);
		if (!options.length) return;
		field.classList.add('pendid-v12-tone-picker');
		select.classList.add('pendid-v12-native-hidden');
		select.setAttribute('aria-hidden', 'true');
		if (originalLabel) originalLabel.classList.add('pendid-v12-native-hidden');

		var titleRow = document.createElement('div');
		var titleCopy = document.createElement('div');
		var title = document.createElement('strong');
		var helper = document.createElement('small');
		var chooseButton = document.createElement('button');
		var strip = document.createElement('div');
		var current = document.createElement('p');
		var currentStrong = document.createElement('strong');
		titleRow.className = 'pendid-ai-studio-section-title-row';
		title.textContent = originalLabel ? originalLabel.textContent : uiText('Image mood', 'حس‌وحال تصویر');
		helper.textContent = uiText('Choose a visual direction for the image.', 'یک جهت بصری برای تصویر انتخاب کنید.');
		titleCopy.appendChild(title);
		titleCopy.appendChild(helper);
		chooseButton.type = 'button';
		chooseButton.className = 'button button-link';
		chooseButton.textContent = uiText('Choose', 'انتخاب');
		titleRow.appendChild(titleCopy);
		titleRow.appendChild(chooseButton);
		strip.className = 'pendid-ai-studio-tone-strip pendid-v12-tone-strip';
		current.className = 'pendid-ai-studio-selected-tone';
		current.appendChild(document.createTextNode(uiText('Current selection: ', 'انتخاب فعلی: ')));
		current.appendChild(currentStrong);
		field.appendChild(titleRow);
		field.appendChild(strip);
		field.appendChild(current);

		var modalParts = createModal(
			'pendid-v12-tone-modal',
			uiText('Choose the image mood', 'حس‌وحال تصویر را انتخاب کنید'),
			uiText('The mood guides composition, color and visual energy. Your prompt remains the main instruction.', 'حس‌وحال، ترکیب‌بندی، رنگ و انرژی بصری را هدایت می‌کند و توضیح شما همچنان دستور اصلی است.'),
			'pendid-ai-studio-tone-modal',
			'pendid-ai-studio-tone-dialog'
		);
		var toneGrid = document.createElement('div');
		toneGrid.className = 'pendid-ai-studio-tone-grid';
		modalParts.body.appendChild(toneGrid);
		var cards = [];

		for (var i = 0; i < options.length; i += 1) {
			(function (option) {
				var card = document.createElement('button');
				var visual = document.createElement('span');
				var copy = document.createElement('span');
				var cardTitle = document.createElement('strong');
				card.type = 'button';
				card.className = 'pendid-ai-studio-tone-card pendid-v12-tone-choice';
				card.setAttribute('data-pendid-tone-value', option.value);
				visual.className = 'pendid-ai-studio-tone-card-image';
				visual.appendChild(createToneVisual(option.value));
				copy.className = 'pendid-ai-studio-tone-card-copy';
				cardTitle.textContent = option.textContent;
				copy.appendChild(cardTitle);
				card.appendChild(visual);
				card.appendChild(copy);
				card.addEventListener('click', function () {
					select.value = option.value;
					select.dispatchEvent(new Event('change', { bubbles: true }));
					updateToneSelection();
					closeDynamicModal(modalParts.modal);
				});
				toneGrid.appendChild(card);
				cards.push(card);
			}(options[i]));
		}

		function renderToneStrip() {
			strip.innerHTML = '';
			var currentValue = select.value;
			var visualOptions = options.filter(function (option) { return option.value !== 'free'; });
			var visible = visualOptions.slice(0, 5);
			if (currentValue === 'free') {
				visible = [options.filter(function (option) { return option.value === 'free'; })[0]].concat(visualOptions.slice(0, 4));
			} else if (!visible.some(function (option) { return option.value === currentValue; })) {
				var selectedOption = options.filter(function (option) { return option.value === currentValue; })[0];
				if (selectedOption) visible[visible.length >= 5 ? 4 : visible.length] = selectedOption;
			}
			for (var index = 0; index < visible.length; index += 1) {
				if (!visible[index]) continue;
				var thumb = document.createElement('button');
				thumb.type = 'button';
				thumb.className = 'pendid-ai-studio-tone-thumb' + (visible[index].value === currentValue ? ' is-active' : '');
				thumb.setAttribute('aria-label', visible[index].textContent);
				thumb.appendChild(createToneVisual(visible[index].value));
				thumb.addEventListener('click', function () { openDynamicModal(modalParts.modal, this); });
				strip.appendChild(thumb);
			}
		}

		function updateToneSelection() {
			var selected = options.filter(function (option) { return option.value === select.value; })[0] || options[0];
			currentStrong.textContent = selected ? selected.textContent : '';
			for (var index = 0; index < cards.length; index += 1) {
				cards[index].classList.toggle('is-active', cards[index].getAttribute('data-pendid-tone-value') === select.value);
			}
			renderToneStrip();
		}

		chooseButton.addEventListener('click', function () { openDynamicModal(modalParts.modal, chooseButton); });
		select.addEventListener('change', updateToneSelection);
		updateToneSelection();
	}

	function modernizeUploadCopy(form) {
		var card = form.querySelector('.pendid-ai-studio-reference-card');
		if (!card) return;
		var strong = card.querySelector('.pendid-ai-studio-reference-copy strong');
		var small = card.querySelector('.pendid-ai-studio-reference-copy small');
		if (strong) strong.textContent = uiText('Upload images', 'آپلود عکس');
		if (small) {
			var input = card.querySelector('[data-pendid-v12-inputs]');
			var max = Number(input ? input.getAttribute('data-max-inputs') || 1 : 1);
			small.textContent = isPersian()
				? 'JPG، PNG یا WebP. حداکثر ' + formatNumber(max) + ' عکس.'
				: 'JPG, PNG or WebP. Up to ' + formatNumber(max) + ' images.';
		}
	}

	function bindForm(form) {
		var professionalSelect = form.querySelector('[data-pendid-professional-size]');
		var primary = form.querySelectorAll('input[name="pendid_output_size"]');
		var inputs = form.querySelector('[data-pendid-v12-inputs]');
		for (var i = 0; i < primary.length; i += 1) primary[i].setAttribute('data-primary-value', primary[i].value);

		if (professionalSelect) {
			professionalSelect.addEventListener('change', function () {
				var checked = form.querySelector('input[name="pendid_output_size"]:checked');
				if (!checked) return;
				var base = checked.getAttribute('data-primary-value') || '1:1';
				checked.value = professionalSelect.value || base;
				updatePrice(form);
			});
		}

		for (var j = 0; j < primary.length; j += 1) {
			primary[j].addEventListener('change', function (event) {
				if (!event.target.checked) return;
				var base = event.target.getAttribute('data-primary-value') || event.target.value;
				event.target.value = base;
				if (professionalSelect) professionalSelect.value = '';
				updatePrice(form);
			});
		}

		if (inputs) {
			inputs.addEventListener('change', function () {
				var max = Number(inputs.getAttribute('data-max-inputs') || 1);
				if (inputs.files && inputs.files.length > max) {
					window.alert(referenceLimitText(max));
					inputs.value = '';
				}
				updatePrice(form);
			});
		}

		syncBrandKitControl(form);
		modernizeUploadCopy(form);
		form.addEventListener('change', function () { updatePrice(form); });
		form.addEventListener('submit', function () {
			var button = form.querySelector('button[type="submit"]');
			if (button) {
				button.disabled = true;
				button.classList.add('is-busy');
			}
		});
		if ((form.querySelector('[name="pendid_mode"]') || {}).value !== 'edit') {
			enhancePurposePicker(form);
			enhanceTonePicker(form);
		}
		updatePrice(form);
	}

	document.addEventListener('DOMContentLoaded', function () {
		var forms = document.querySelectorAll('[data-pendid-v12-form]');
		for (var i = 0; i < forms.length; i += 1) bindForm(forms[i]);
	});
}());
