(function () {
	'use strict';

	window.SubmissionInbox = window.SubmissionInbox || {};

	var activeHelp = null;
	var floatingHelp = null;
	var attentionNoticeStorageKey = 'subinInboxAttentionNoticeDismissed';

	restoreDismissedAttentionNotice();
	document.addEventListener('DOMContentLoaded', initAutoReplyRuleEditor);

	document.addEventListener('click', function (event) {
		var button = event.target.closest('.subin-copy-shortcode, .subin-shortcode-copy');

		if (!button) {
			return;
		}

		var shortcode = button.getAttribute('data-subin-copy');
		var originalText = button.textContent;
		var feedback = findCopyFeedback(button);

		if (!shortcode || !navigator.clipboard || !navigator.clipboard.writeText) {
			if (feedback) {
				feedback.textContent = 'Select and copy manually';
				window.setTimeout(function () {
					feedback.textContent = '';
				}, 2200);
			}
			return;
		}

		navigator.clipboard.writeText(shortcode).then(function () {
			button.textContent = 'Copied';
			button.classList.add('subin-copy-shortcode--copied');
			if (feedback) {
				feedback.textContent = 'Copied';
			}

			window.setTimeout(function () {
				button.textContent = originalText;
				button.classList.remove('subin-copy-shortcode--copied');
				if (feedback) {
					feedback.textContent = '';
				}
			}, 1800);
		}).catch(function () {
			if (feedback) {
				feedback.textContent = 'Select and copy manually';
				window.setTimeout(function () {
					feedback.textContent = '';
				}, 2200);
			}
		});
	});

	document.addEventListener('click', function (event) {
		var openButton = event.target.closest('[data-subin-open-template-picker]');
		if (openButton) {
			event.preventDefault();
			if (openButton.disabled || openButton.getAttribute('aria-disabled') === 'true') {
				return;
			}
			openTemplatePicker();
			return;
		}

		var disabledAutoReplyLink = event.target.closest('[data-subin-auto-reply-link-control][aria-disabled="true"]');
		if (disabledAutoReplyLink) {
			event.preventDefault();
			return;
		}

		var closeButton = event.target.closest('[data-subin-close-template-picker]');
		if (closeButton) {
			event.preventDefault();
			closeTemplatePicker();
			return;
		}

		var useButton = event.target.closest('[data-subin-use-template]');
		if (useButton) {
			event.preventDefault();
			selectAutoReplyTemplate(useButton.getAttribute('data-subin-use-template'));
			closeTemplatePicker();
		}
	});

	document.addEventListener('click', function (event) {
		var dismiss = event.target.closest('[data-subin-dismiss-attention-notice]');

		if (!dismiss) {
			return;
		}

		var notice = dismiss.closest('[data-subin-attention-notice]');
		if (!notice) {
			return;
		}

		notice.classList.add('is-hidden');

		try {
			window.localStorage.setItem(attentionNoticeStorageKey, '1');
		} catch (error) {
			// The notice is already hidden for this page when storage is unavailable.
		}
	});

	document.addEventListener('change', function (event) {
		if (event.target.matches('[data-subin-auto-reply-toggle]')) {
			updateAutoReplyDisabledState(event.target.checked);
		}

		if (event.target.matches('[data-subin-notification-recipient-mode]')) {
			updateNotificationRecipientState();
		}

		if (event.target.matches('[data-subin-notification-email]')) {
			var notificationPreserved = document.querySelector('[data-subin-notification-email-preserved]');
			if (notificationPreserved) {
				notificationPreserved.value = event.target.value;
			}
		}

		if (event.target.matches('#subin-auto-reply-recipient')) {
			var preserved = document.querySelector('[data-subin-auto-reply-recipient-preserved]');
			if (preserved) {
				preserved.value = event.target.value;
			}
		}

		if (event.target.matches('#subin-rule-provider')) {
			updateAutoReplyRuleProvider(event.target);
		}

		if (event.target.matches('[data-subin-rule-form-select]')) {
			updateAutoReplyRuleEmailFields();
		}
	});

	document.addEventListener('keydown', function (event) {
		if (event.key === 'Escape') {
			closeTemplatePicker();
			hideFloatingHelp();
		}
	});

	document.addEventListener('mouseover', function (event) {
		var help = event.target.closest('[data-subin-help-text]');
		if (help) {
			showFloatingHelp(help);
		}
	});

	document.addEventListener('mouseout', function (event) {
		var help = event.target.closest('[data-subin-help-text]');
		if (help && (!event.relatedTarget || !help.contains(event.relatedTarget))) {
			hideFloatingHelp();
		}
	});

	document.addEventListener('focusin', function (event) {
		var help = event.target.closest('[data-subin-help-text]');
		if (help) {
			showFloatingHelp(help);
		}
	});

	document.addEventListener('focusout', function (event) {
		var help = event.target.closest('[data-subin-help-text]');
		if (help) {
			hideFloatingHelp();
		}
	});

	window.addEventListener('scroll', function () {
		if (activeHelp) {
			positionFloatingHelp(activeHelp);
		}
	}, true);

	window.addEventListener('resize', function () {
		if (activeHelp) {
			positionFloatingHelp(activeHelp);
		}
	});

	function findCopyFeedback(button) {
		var sibling = button.nextElementSibling;
		if (sibling && sibling.classList.contains('subin-copy-feedback')) {
			return sibling;
		}

		var wrap = button.closest('.subin-shortcode-box, td, .subin-form-editor__actions, .subin-design-toolbar__shortcode, .subin-variable-card, .subin-settings-shortcode-row');
		return wrap ? wrap.querySelector('.subin-copy-feedback') : null;
	}

	function restoreDismissedAttentionNotice() {
		try {
			if (window.localStorage.getItem(attentionNoticeStorageKey) !== '1') {
				return;
			}
		} catch (error) {
			return;
		}

		document.addEventListener('DOMContentLoaded', function () {
			document.querySelectorAll('[data-subin-attention-notice]').forEach(function (notice) {
				notice.classList.add('is-hidden');
			});
		});
	}

	function openTemplatePicker() {
		var modal = document.querySelector('[data-subin-template-picker-modal]');
		if (!modal) {
			return;
		}

		modal.hidden = false;
		document.body.classList.add('subin-template-picker-open');
	}

	function closeTemplatePicker() {
		var modal = document.querySelector('[data-subin-template-picker-modal]');
		if (!modal || modal.hidden) {
			return;
		}

		modal.hidden = true;
		document.body.classList.remove('subin-template-picker-open');
	}

	function selectAutoReplyTemplate(templateId) {
		if (!templateId) {
			return;
		}

		var input = document.querySelector('[data-subin-auto-reply-template-input]');
		var preview = document.querySelector('[data-subin-selected-template-preview]');
		var template = findSelectedTemplate(templateId);

		if (input) {
			input.value = templateId;
			input.dispatchEvent(new Event('change', { bubbles: true }));
		}

		if (preview && template) {
			preview.innerHTML = '';
			preview.appendChild(template.content.cloneNode(true));
		}
	}

	function findSelectedTemplate(templateId) {
		var templates = document.querySelectorAll('[data-subin-selected-template]');
		var expected = String(templateId);

		for (var index = 0; index < templates.length; index++) {
			if (templates[index].getAttribute('data-subin-selected-template') === expected) {
				return templates[index];
			}
		}

		return null;
	}

	function showFloatingHelp(help) {
		var text = help.getAttribute('data-subin-help-text') || '';
		if (!text) {
			return;
		}

		activeHelp = help;
		if (!floatingHelp) {
			floatingHelp = document.createElement('div');
			floatingHelp.className = 'subin-floating-tooltip';
			floatingHelp.setAttribute('role', 'tooltip');
			document.body.appendChild(floatingHelp);
		}

		floatingHelp.textContent = text;
		floatingHelp.classList.add('is-visible');
		positionFloatingHelp(help);
	}

	function hideFloatingHelp() {
		activeHelp = null;
		if (floatingHelp) {
			floatingHelp.classList.remove('is-visible');
		}
	}

	function positionFloatingHelp(help) {
		if (!floatingHelp) {
			return;
		}

		var spacing = 10;
		var viewportPadding = 12;
		var helpRect = help.getBoundingClientRect();

		floatingHelp.style.left = '0px';
		floatingHelp.style.top = '0px';

		var tipRect = floatingHelp.getBoundingClientRect();
		var left = helpRect.left + (helpRect.width / 2) - (tipRect.width / 2);
		left = Math.max(viewportPadding, Math.min(left, window.innerWidth - tipRect.width - viewportPadding));

		var top = helpRect.top - tipRect.height - spacing;
		if (top < viewportPadding) {
			top = helpRect.bottom + spacing;
		}
		if (top + tipRect.height > window.innerHeight - viewportPadding) {
			top = Math.max(viewportPadding, window.innerHeight - tipRect.height - viewportPadding);
		}

		floatingHelp.style.left = Math.round(left) + 'px';
		floatingHelp.style.top = Math.round(top) + 'px';
	}

	function updateNotificationRecipientState() {
		var customInput = document.querySelector('[data-subin-notification-email]');
		var customMode = document.querySelector('[data-subin-notification-recipient-mode][value="custom"]');
		var fieldWrap = document.querySelector('[data-subin-notification-custom-recipient]');
		var preserved = document.querySelector('[data-subin-notification-email-preserved]');

		if (!customInput || !customMode) {
			return;
		}

		if (customMode.checked) {
			customInput.disabled = false;
			customInput.value = '';
		} else {
			customInput.value = fieldWrap ? (fieldWrap.getAttribute('data-subin-default-notification-recipient') || '') : '';
			customInput.disabled = true;
		}

		if (preserved) {
			preserved.value = customInput.value;
		}
	}

	function updateAutoReplyDisabledState(isEnabled) {
		var settings = document.querySelector('[data-subin-auto-reply-settings]');
		var helper = document.querySelector('[data-subin-auto-reply-disabled-helper]');

		if (settings) {
			settings.classList.toggle('is-disabled', !isEnabled);
			settings.querySelectorAll('[data-subin-auto-reply-control], [data-subin-open-template-picker]').forEach(function (control) {
				control.disabled = !isEnabled;
			});
			settings.querySelectorAll('[data-subin-auto-reply-link-control]').forEach(function (control) {
				control.classList.toggle('disabled', !isEnabled);
				if (isEnabled) {
					control.removeAttribute('aria-disabled');
					control.removeAttribute('tabindex');
				} else {
					control.setAttribute('aria-disabled', 'true');
					control.setAttribute('tabindex', '-1');
				}
			});
			settings.querySelectorAll('.subin-auto-reply-template-selected, .subin-auto-reply-template-empty').forEach(function (card) {
				card.classList.toggle('is-disabled', !isEnabled);
			});
		}

		if (helper) {
			helper.hidden = isEnabled;
		}
	}

	function initAutoReplyRuleEditor() {
		var provider = document.querySelector('#subin-rule-provider');
		if (!provider) {
			return;
		}

		updateAutoReplyRuleProvider(provider, true);
	}

	function updateAutoReplyRuleProvider(providerSelect, preserveSelection) {
		var provider = providerSelect.value;
		var formSelect = document.querySelector('[data-subin-rule-form-select]');

		if (!formSelect) {
			return;
		}

		var selectedStillVisible = false;
		Array.prototype.forEach.call(formSelect.options, function (option) {
			if (!option.value) {
				option.hidden = false;
				return;
			}

			var isVisible = option.getAttribute('data-subin-provider') === provider;
			option.hidden = !isVisible;
			if (isVisible && option.selected) {
				selectedStillVisible = true;
			}
		});

		if (!preserveSelection || !selectedStillVisible) {
			formSelect.value = '';
		}

		updateAutoReplyRuleEmailFields(preserveSelection);
	}

	function updateAutoReplyRuleEmailFields(preserveSelection) {
		var providerSelect = document.querySelector('#subin-rule-provider');
		var formSelect = document.querySelector('[data-subin-rule-form-select]');
		var emailSelect = document.querySelector('[data-subin-rule-email-field-select]');

		if (!providerSelect || !formSelect || !emailSelect) {
			return;
		}

		var provider = providerSelect.value;
		var formValue = formSelect.value;
		var selectedStillVisible = false;
		var hasVisible = false;

		Array.prototype.forEach.call(emailSelect.options, function (option) {
			if (!option.value) {
				option.hidden = false;
				return;
			}

			var isVisible = option.getAttribute('data-subin-provider') === provider;
			if (formValue) {
				isVisible = isVisible && option.getAttribute('data-subin-form-value') === formValue;
			} else {
				isVisible = false;
			}

			option.hidden = !isVisible;
			if (isVisible) {
				hasVisible = true;
			}
			if (isVisible && option.selected) {
				selectedStillVisible = true;
			}
		});

		if (!preserveSelection || !selectedStillVisible) {
			emailSelect.value = '';
		}

		emailSelect.disabled = !hasVisible;
	}

})();
