(function () {
	'use strict';

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

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

	restoreDismissedAttentionNotice();
	document.addEventListener('DOMContentLoaded', initAutoReplyRuleEditor);
	document.addEventListener('DOMContentLoaded', initInboxBulkActions);
	document.addEventListener('DOMContentLoaded', initTeamAccess);
	document.addEventListener('DOMContentLoaded', initSettingsExperience);

	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 button = event.target.closest('[data-subin-copy-report]');
		if (!button) {
			return;
		}

		var target = document.getElementById(button.getAttribute('data-subin-copy-report') || '');
		if (!target) {
			return;
		}

		var originalText = button.textContent;
		var copiedLabel = button.getAttribute('data-subin-copied-label') || originalText;
		var manualLabel = button.getAttribute('data-subin-manual-label') || originalText;
		var feedback = findCopyFeedback(button);
		var showFeedback = function (message) {
			if (feedback) {
				feedback.textContent = message;
			}
			window.setTimeout(function () {
				button.textContent = originalText;
				if (feedback) {
					feedback.textContent = '';
				}
			}, 1800);
		};
		var selectManually = function () {
			target.focus();
			target.select();
			showFeedback(manualLabel);
		};

		if (!navigator.clipboard || !navigator.clipboard.writeText) {
			selectManually();
			return;
		}

		navigator.clipboard.writeText(target.value).then(function () {
			button.textContent = copiedLabel;
			showFeedback(copiedLabel);
		}).catch(selectManually);
	});

	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();
		}

		if (event.target.matches('[data-subin-team-preset]')) {
			updateTeamAccessForm(event.target.closest('[data-subin-team-access-form]'));
		}
	});

	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, .subin-health-support__body');
		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 initSettingsExperience() {
		var forms = Array.prototype.slice.call(document.querySelectorAll('[data-subin-settings-form]'));
		if (!forms.length) {
			return;
		}

		document.querySelectorAll('[data-subin-settings-confirm]').forEach(function (button) {
			button.addEventListener('click', function (event) {
				var message = button.getAttribute('data-subin-settings-confirm') || '';
				if (message && !window.confirm(message)) {
					event.preventDefault();
					return;
				}

				var form = button.form;
				if (!form) {
					return;
				}
				var confirmation = form.querySelector('input[name="subin_cloud_confirm"]');
				if (!confirmation) {
					confirmation = document.createElement('input');
					confirmation.type = 'hidden';
					confirmation.name = 'subin_cloud_confirm';
					form.appendChild(confirmation);
				}
				confirmation.value = button.value;
			});
		});

		forms.forEach(function (form) {
			var savebar = form.querySelector('[data-subin-settings-savebar]');
			var state = savebar ? savebar.querySelector('[data-subin-settings-state]') : null;
			var discard = savebar ? savebar.querySelector('[data-subin-settings-discard]') : null;
			var initialSnapshot = settingsFormSnapshot(form);
			form.querySelectorAll('[data-subin-requires-saved-settings]').forEach(function (control) {
				control.setAttribute('data-subin-initial-disabled', control.disabled ? '1' : '0');
			});

			function updateDirtyState() {
				var isDirty = settingsFormSnapshot(form) !== initialSnapshot;
				form.setAttribute('data-subin-settings-dirty', isDirty ? '1' : '0');
				if (savebar) {
					savebar.classList.toggle('is-dirty', isDirty);
				}
				if (state && savebar) {
					state.textContent = isDirty ? savebar.getAttribute('data-subin-dirty-label') : savebar.getAttribute('data-subin-clean-label');
				}
				if (discard) {
					discard.hidden = !isDirty;
				}
				form.querySelectorAll('[data-subin-requires-saved-settings]').forEach(function (control) {
					var disabled = isDirty || control.getAttribute('data-subin-initial-disabled') === '1';
					control.disabled = disabled;
					control.setAttribute('aria-disabled', disabled ? 'true' : 'false');
				});
				updateSettingsTestState();
			}

			form.addEventListener('input', function () {
				updateSettingsDependencies(form);
				updateDirtyState();
			});
			form.addEventListener('change', function () {
				updateSettingsDependencies(form);
				updateDirtyState();
			});
			form.addEventListener('submit', function () {
				form.setAttribute('data-subin-settings-submitting', '1');
			});

			if (discard) {
				discard.addEventListener('click', function () {
					form.reset();
					updateSettingsDependencies(form);
					updateDirtyState();
				});
			}

			updateSettingsDependencies(form);
			updateDirtyState();
		});

		window.addEventListener('beforeunload', function (event) {
			var hasDirtyForm = forms.some(function (form) {
				return form.getAttribute('data-subin-settings-dirty') === '1' && form.getAttribute('data-subin-settings-submitting') !== '1';
			});
			if (!hasDirtyForm) {
				return;
			}

			event.preventDefault();
			event.returnValue = '';
		});
	}

	function settingsFormSnapshot(form) {
		var values = [];
		Array.prototype.slice.call(form.elements).forEach(function (control) {
			if (!control.name || control.disabled || ['submit', 'button', 'reset'].indexOf(control.type) !== -1) {
				return;
			}
			if ((control.type === 'checkbox' || control.type === 'radio') && !control.checked) {
				return;
			}
			values.push(control.name + '=' + String(control.value));
		});

		return values.sort().join('&');
	}

	function settingsNamedCheckbox(form, name) {
		var controls = Array.prototype.slice.call(form.elements);
		for (var index = 0; index < controls.length; index += 1) {
			if (controls[index].name === name && controls[index].type === 'checkbox') {
				return controls[index];
			}
		}

		return null;
	}

	function updateSettingsDependencies(form) {
		form.querySelectorAll('[data-subin-show-when]').forEach(function (element) {
			var names = (element.getAttribute('data-subin-show-when') || '').split(',').filter(Boolean);
			var visible = names.length > 0 && names.every(function (name) {
				var control = settingsNamedCheckbox(form, name.trim());
				return control && control.checked;
			});
			element.hidden = !visible;
		});

		form.querySelectorAll('[data-subin-show-when-not]').forEach(function (element) {
			var control = settingsNamedCheckbox(form, element.getAttribute('data-subin-show-when-not') || '');
			element.hidden = !!(control && control.checked);
		});
	}

	function updateSettingsTestState() {
		var sendingForm = document.querySelector('[data-subin-sending-settings]');
		var testSubmit = document.querySelector('[data-subin-settings-test-submit]');
		if (!sendingForm || !testSubmit) {
			return;
		}

		var disabled = sendingForm.getAttribute('data-subin-settings-dirty') === '1';
		testSubmit.disabled = disabled;
		testSubmit.setAttribute('aria-disabled', disabled ? 'true' : 'false');
	}

	function initTeamAccess() {
		document.querySelectorAll('[data-subin-team-access-form]').forEach(function (form) {
			updateTeamAccessForm(form);
		});
	}

	function updateTeamAccessForm(form) {
		if (!form) {
			return;
		}

		var preset = form.querySelector('[data-subin-team-preset]');
		var exportControl = form.querySelector('[data-subin-team-export]');
		var submit = form.querySelector('[data-subin-team-submit]');
		if (!preset || !exportControl || !submit) {
			return;
		}

		var isCustom = preset.value === '';
		var isNone = preset.value === 'none';
		if (isNone) {
			exportControl.checked = false;
		}
		exportControl.disabled = isNone || isCustom;
		submit.disabled = isCustom;
		submit.setAttribute('aria-disabled', isCustom ? 'true' : 'false');
	}

	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;
	}

	function initInboxBulkActions() {
		var form = document.querySelector('#subin-inbox-bulk-form');
		var selectAll = document.querySelector('[data-subin-select-all]');

		if (!form || !selectAll) {
			return;
		}

		var leadCheckboxes = Array.prototype.slice.call(document.querySelectorAll('[data-subin-lead-select]'));
		var submitButton = form.querySelector('[data-subin-bulk-submit]');
		var selectedCount = form.querySelector('[data-subin-selected-count]');
		var actionSelect = form.querySelector('[data-subin-bulk-action]');
		var actionTargets = Array.prototype.slice.call(form.querySelectorAll('[data-subin-bulk-target]'));

		function updateActionTargets() {
			var action = actionSelect ? actionSelect.value : '';
			var actionIsValid = action !== '';

			actionTargets.forEach(function (target) {
				var isActive = target.getAttribute('data-subin-bulk-target') === action;
				target.hidden = !isActive;

				Array.prototype.slice.call(target.querySelectorAll('input, select')).forEach(function (control) {
					control.disabled = !isActive;
					var isRequired = control.getAttribute('data-subin-bulk-required') !== null;
					control.required = isActive && isRequired;
					if (isActive && isRequired && String(control.value || '').trim() === '') {
						actionIsValid = false;
					}
				});
			});

			return actionIsValid;
		}

		function updateBulkState() {
			var checkedCount = leadCheckboxes.filter(function (checkbox) {
				return checkbox.checked;
			}).length;
			var canSubmit = checkedCount > 0 && updateActionTargets();

			selectAll.checked = leadCheckboxes.length > 0 && checkedCount === leadCheckboxes.length;
			selectAll.indeterminate = checkedCount > 0 && checkedCount < leadCheckboxes.length;

			if (submitButton) {
				submitButton.disabled = !canSubmit;
				submitButton.setAttribute('aria-disabled', canSubmit ? 'false' : 'true');
			}

			if (selectedCount) {
				var oneSelected = selectedCount.getAttribute('data-subin-selected-one') || '1 selected';
				var manySelected = selectedCount.getAttribute('data-subin-selected-many') || '%d selected';
				selectedCount.textContent = checkedCount === 1 ? oneSelected : manySelected.replace('%d', String(checkedCount));
			}
		}

		selectAll.addEventListener('change', function () {
			leadCheckboxes.forEach(function (checkbox) {
				checkbox.checked = selectAll.checked;
			});
			updateBulkState();
		});

		leadCheckboxes.forEach(function (checkbox) {
			checkbox.addEventListener('change', updateBulkState);
		});

		if (actionSelect) {
			actionSelect.addEventListener('change', updateBulkState);
		}

		actionTargets.forEach(function (target) {
			Array.prototype.slice.call(target.querySelectorAll('input, select')).forEach(function (control) {
				control.addEventListener('change', updateBulkState);
				control.addEventListener('input', updateBulkState);
			});
		});

		form.addEventListener('submit', function (event) {
			var action = actionSelect ? actionSelect.value : '';
			var confirmation = '';
			if (action === 'archived') {
				confirmation = form.getAttribute('data-subin-confirm-archive') || '';
			} else if (action === 'clear_follow_up') {
				confirmation = form.getAttribute('data-subin-confirm-clear-follow-up') || '';
			}

			if (confirmation && !window.confirm(confirmation)) {
				event.preventDefault();
			}
		});

		updateBulkState();
	}

})();
