(function () {
	'use strict';

	const config = window.tmsmtpFreeRouting || {};
	const labels = config.labels || {};
	const formRoot = config.formRoot || 'tmsmtp_free_routing';
	let uniqueCounter = 0;

	function escapeHtml(value) {
		return String(value == null ? '' : value).replace(/[&<>'"]/g, function (character) {
			return {
				'&': '&amp;',
				'<': '&lt;',
				'>': '&gt;',
				"'": '&#039;',
				'"': '&quot;'
			}[character];
		});
	}

	function text(name, fallback) {
		return escapeHtml(Object.prototype.hasOwnProperty.call(labels, name) ? labels[name] : fallback);
	}

	function updateMailerFields(card) {
		if (!card) {
			return;
		}
		const select = card.querySelector('.tms-mailer-select');
		if (!select) {
			return;
		}
		card.querySelectorAll('.tms-mailer-field').forEach(function (row) {
			row.style.display = row.classList.contains('tms-mailer-' + select.value) ? '' : 'none';
		});
	}

	function uniqueKey(prefix) {
		uniqueCounter += 1;
		return prefix + '_' + Date.now() + '_' + uniqueCounter;
	}

	function routeHtml(routeKey) {
		const groupKey = uniqueKey('group');
		return `<div class="tms-route-box" data-route-box data-route-key="${routeKey}"><div class="tms-route-top"><div class="tms-route-top-main"><span class="tms-route-copy">${text('sendWith', 'Send with')}</span><select class="tms-select-large" name="${formRoot}[routes][${routeKey}][connection_id]">${config.connectionOptions || ''}</select><span class="tms-route-copy">${text('conditionsMet', 'if the following conditions are met...')}</span></div><div class="tms-route-tools"><button type="button" class="tms-icon-btn" data-route-up title="${text('moveUp', 'Move up')}">↑</button><button type="button" class="tms-icon-btn" data-route-down title="${text('moveDown', 'Move down')}">↓</button><button type="button" class="tms-icon-btn tms-mini-btn--danger" data-route-delete title="${text('delete', 'Delete')}">🗑</button></div></div><div class="tms-route-groups" data-route-groups>${groupHtml(routeKey, groupKey, true)}</div><button type="button" class="tms-mini-btn" data-add-group>${text('addGroup', 'Add New Group')}</button></div>`;
	}

	function groupHtml(routeKey, groupKey, first) {
		const ruleKey = uniqueKey('rule');
		return `<div class="tms-route-group" data-group data-group-key="${groupKey}">${first ? '' : '<div class="tms-or-label">' + text('or', 'or') + '</div>'}${ruleHtml(routeKey, groupKey, ruleKey)}<button type="button" class="tms-mini-btn" data-add-rule>${text('addAnd', 'Add And')}</button> <button type="button" class="tms-mini-btn tms-mini-btn--danger" data-delete-group>${text('deleteGroup', 'Delete Group')}</button></div>`;
	}

	function ruleHtml(routeKey, groupKey, ruleKey) {
		return `<div class="tms-rule-row" data-rule><select class="tms-select-medium" name="${formRoot}[routes][${routeKey}][groups][${groupKey}][rules][${ruleKey}][property]">${config.propertyOptions || ''}</select><select class="tms-select-medium" name="${formRoot}[routes][${routeKey}][groups][${groupKey}][rules][${ruleKey}][operator]">${config.operatorOptions || ''}</select><input type="text" name="${formRoot}[routes][${routeKey}][groups][${groupKey}][rules][${ruleKey}][value]" value=""><button type="button" class="tms-icon-btn tms-mini-btn--danger" data-delete-rule title="${text('deleteRule', 'Delete rule')}">🗑</button></div>`;
	}

	function routeKeyFromBox(routeBox) {
		if (routeBox.dataset.routeKey) {
			return routeBox.dataset.routeKey;
		}
		const select = routeBox.querySelector('select[name*="[connection_id]"]');
		const match = select && select.name ? select.name.match(/routes\]\[(.*?)\]\[/) : null;
		return match && match[1] ? match[1] : uniqueKey('route');
	}

	function refreshOrLabels(routeBox) {
		routeBox.querySelectorAll('[data-group]').forEach(function (group, index) {
			let label = group.querySelector(':scope > .tms-or-label');
			if (index === 0 && label) {
				label.remove();
			} else if (index > 0 && !label) {
				group.insertAdjacentHTML('afterbegin', '<div class="tms-or-label">' + text('or', 'or') + '</div>');
			}
		});
	}

	function init() {
		document.querySelectorAll('.tms-connection-card').forEach(updateMailerFields);
		document.addEventListener('change', function (event) {
			if (event.target && event.target.classList.contains('tms-mailer-select')) {
				updateMailerFields(event.target.closest('.tms-connection-card'));
			}
		});
		document.addEventListener('click', function (event) {
			const target = event.target instanceof Element ? event.target : null;
			if (!target) {
				return;
			}
			const routeList = document.getElementById('tms-route-list');
			const addRouteButton = target.closest('#tms-add-route');
			if (addRouteButton && routeList) {
				event.preventDefault();
				routeList.insertAdjacentHTML('beforeend', routeHtml(uniqueKey('route')));
				return;
			}
			const routeBox = target.closest('[data-route-box]');
			if (target.closest('[data-route-delete]') && routeBox) {
				event.preventDefault();
				routeBox.remove();
				return;
			}
			if (target.closest('[data-route-up]') && routeBox) {
				event.preventDefault();
				const previous = routeBox.previousElementSibling;
				if (previous) {
					previous.before(routeBox);
				}
				return;
			}
			if (target.closest('[data-route-down]') && routeBox) {
				event.preventDefault();
				const next = routeBox.nextElementSibling;
				if (next) {
					next.after(routeBox);
				}
				return;
			}
			if (target.closest('[data-add-group]') && routeBox) {
				event.preventDefault();
				const groups = routeBox.querySelector('[data-route-groups]');
				if (groups) {
					const first = groups.querySelectorAll('[data-group]').length === 0;
					groups.insertAdjacentHTML('beforeend', groupHtml(routeKeyFromBox(routeBox), uniqueKey('group'), first));
					refreshOrLabels(routeBox);
				}
				return;
			}
			const deleteGroup = target.closest('[data-delete-group]');
			if (deleteGroup) {
				event.preventDefault();
				const group = deleteGroup.closest('[data-group]');
				const owner = deleteGroup.closest('[data-route-box]');
				if (group) {
					group.remove();
					if (owner) {
						refreshOrLabels(owner);
					}
				}
				return;
			}
			const addRule = target.closest('[data-add-rule]');
			if (addRule) {
				event.preventDefault();
				const group = addRule.closest('[data-group]');
				const owner = addRule.closest('[data-route-box]');
				if (!group || !owner) {
					return;
				}
				const groupKey = group.dataset.groupKey || uniqueKey('group');
				group.dataset.groupKey = groupKey;
				addRule.insertAdjacentHTML('beforebegin', ruleHtml(routeKeyFromBox(owner), groupKey, uniqueKey('rule')));
				return;
			}
			const deleteRule = target.closest('[data-delete-rule]');
			if (deleteRule) {
				event.preventDefault();
				const rule = deleteRule.closest('[data-rule]');
				if (rule) {
					rule.remove();
				}
			}
		});
	}

	if (document.readyState === 'loading') {
		document.addEventListener('DOMContentLoaded', init);
	} else {
		init();
	}
}());
