(() => {
	const config = window.foodordDeactivationFeedback;
	if (!config || !config.pluginFile) {
		return;
	}

	const boot = () => {
		if (window.foodordDeactivationFeedbackBooted) {
			return true;
		}

		const modal = document.getElementById('foodord-deactivation-feedback');
		if (!modal) {
			return false;
		}

		const form = modal.querySelector('[data-foodord-deactivation-feedback-form]');
		const backdrop = modal.querySelector('[data-foodord-deactivation-feedback-backdrop]');
		const btnsCancel = modal.querySelectorAll('[data-foodord-deactivation-feedback-cancel]');
		const btnSkip = modal.querySelector('[data-foodord-deactivation-feedback-skip]');
		const errorEl = modal.querySelector('[data-foodord-deactivation-feedback-error]');
		const btnSubmit = modal.querySelector('[data-foodord-deactivation-feedback-submit]');

		const missingFeatureDetails = modal.querySelector('[data-foodord-deactivation-feedback-details="missing_feature"]');
		const missingFeatureTextarea = modal.querySelector('[data-foodord-deactivation-feedback-textarea="missing_feature"]');
		const otherWrap = modal.querySelector('[data-foodord-deactivation-feedback-other]');
		const otherDetails = modal.querySelector('[data-foodord-deactivation-feedback-details="other"]');
		const otherTextarea = modal.querySelector('[data-foodord-deactivation-feedback-textarea="other"]');

		let pendingHref = '';
		let pendingEvent = 'deactivate';
		let lastFocused = null;

		const showError = (message) => {
			if (!errorEl) {
				return;
			}

			errorEl.textContent = message;
			errorEl.hidden = false;
		};

		const clearError = () => {
			if (!errorEl) {
				return;
			}
			errorEl.textContent = '';
			errorEl.hidden = true;
		};

		const hideOptionalFields = () => {
			if (missingFeatureDetails) {
				missingFeatureDetails.hidden = true;
			}
			if (otherWrap) {
				otherWrap.hidden = true;
			}
			if (otherDetails) {
				otherDetails.hidden = true;
			}
		};

		const updateFieldsVisibility = () => {
			const selectedReason = form
				? form.querySelector('input[name="foodord_deactivation_feedback_reason"]:checked')
				: null;
			const reasonValue = selectedReason ? selectedReason.value : '';

			hideOptionalFields();
			clearError();

			if ('missing_feature' === reasonValue) {
				if (missingFeatureDetails) {
					missingFeatureDetails.hidden = false;
				}
				return;
			}

			if ('other' === reasonValue) {
				if (otherWrap) {
					otherWrap.hidden = false;
				}

				const selectedOther = form
					? form.querySelector('input[name="foodord_deactivation_feedback_other_reason"]:checked')
					: null;
				if (selectedOther && otherDetails) {
					otherDetails.hidden = false;
				}
			}
		};

		const focusFirstInput = () => {
			const first = modal.querySelector('input[name="foodord_deactivation_feedback_reason"]');
			if (first) {
				first.focus();
			}
		};

		const openModal = (href, eventType) => {
			pendingHref = href;
			pendingEvent = eventType;
			lastFocused = document.activeElement;

			clearError();
			hideOptionalFields();
			if (form) {
				form.reset();
			}
			if (missingFeatureTextarea) {
				missingFeatureTextarea.value = '';
			}
			if (otherTextarea) {
				otherTextarea.value = '';
			}

			modal.hidden = false;
			modal.setAttribute('aria-hidden', 'false');
			focusFirstInput();
		};

		const closeModal = () => {
			modal.hidden = true;
			modal.setAttribute('aria-hidden', 'true');
			clearError();

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

		const proceed = () => {
			if (!pendingHref) {
				closeModal();
				return;
			}
			window.location.href = pendingHref;
		};

		const sendFeedback = (payload) => {
			const data = new FormData();
			data.append('action', 'foodord_send_deactivation_feedback');
			data.append('nonce', config.nonce || '');
			data.append('plugin_file', config.pluginFile);
			data.append('event', payload.event);
			data.append('reason', payload.reason);
			if (payload.otherReason) {
				data.append('other_reason', payload.otherReason);
			}
			if (payload.details) {
				data.append('details', payload.details);
			}

			const ajaxUrl = config.ajaxUrl || window.ajaxurl;
			if (!ajaxUrl) {
				return;
			}

			if (navigator.sendBeacon) {
				const ok = navigator.sendBeacon(ajaxUrl, data);
				if (ok) {
					return;
				}
			}

			try {
				fetch(ajaxUrl, {
					method: 'POST',
					credentials: 'same-origin',
					body: data,
					keepalive: true,
				});
			} catch {
				// Intentionally ignore.
			}
		};

		const collectFeedback = () => {
			const reasonEl = form
				? form.querySelector('input[name="foodord_deactivation_feedback_reason"]:checked')
				: null;
			const reason = reasonEl ? reasonEl.value : '';

			let otherReason = '';
			if ('other' === reason) {
				const otherEl = form
					? form.querySelector('input[name="foodord_deactivation_feedback_other_reason"]:checked')
					: null;
				otherReason = otherEl ? otherEl.value : '';
			}

			let details = '';
			if ('missing_feature' === reason && missingFeatureTextarea) {
				details = (missingFeatureTextarea.value || '').trim();
			}
			if ('other' === reason && otherTextarea) {
				details = (otherTextarea.value || '').trim();
			}

			return {
				reason,
				otherReason,
				details,
			};
		};

		const onSubmit = (e) => {
			e.preventDefault();
			clearError();

			const { reason, otherReason, details } = collectFeedback();
			if (!reason) {
				showError('Please select a reason or use “Skip and deactivate”.');
				return;
			}

			if ('other' === reason && !otherReason) {
				showError('Please select one of the “Other” options.');
				return;
			}

			btnSubmit?.setAttribute('aria-busy', 'true');
			btnSubmit?.classList.add('is-busy');

			sendFeedback({
				event: pendingEvent,
				reason,
				otherReason,
				details,
			});

			proceed();
		};

		const onSkip = (e) => {
			e.preventDefault();
			proceed();
		};

		const onBackdropClick = (e) => {
			e.preventDefault();
			closeModal();
		};

		const onCancel = (e) => {
			e.preventDefault();
			closeModal();
		};

		const onKeyDown = (e) => {
			if ('Escape' === e.key && !modal.hidden) {
				e.preventDefault();
				closeModal();
			}
		};

		const getRowPlugin = (link) => {
			const row = link.closest('tr');
			return row ? row.getAttribute('data-plugin') || '' : '';
		};

		const onPluginActionClick = (e) => {
			const link = e.target.closest ? e.target.closest('a') : null;
			if (!link || !link.href) {
				return;
			}

			const rowPlugin = getRowPlugin(link);
			if (rowPlugin !== config.pluginFile) {
				return;
			}

			const actionWrap = link.closest('.deactivate, .delete');
			if (!actionWrap) {
				return;
			}

			const eventType = actionWrap.classList.contains('delete') ? 'delete' : 'deactivate';

			e.preventDefault();
			e.stopPropagation();
			if (typeof e.stopImmediatePropagation === 'function') {
				e.stopImmediatePropagation();
			}

			openModal(link.href, eventType);
		};

		form?.addEventListener('submit', onSubmit);
		form?.addEventListener('change', (e) => {
			if (!e.target) {
				return;
			}
			if (
				e.target.matches('input[name="foodord_deactivation_feedback_reason"]') ||
				e.target.matches('input[name="foodord_deactivation_feedback_other_reason"]')
			) {
				updateFieldsVisibility();
			}
		});

		backdrop?.addEventListener('click', onBackdropClick);
		btnsCancel.forEach(btn => btn.addEventListener('click', onCancel));
		btnSkip?.addEventListener('click', onSkip);
		document.addEventListener('keydown', onKeyDown);
		document.addEventListener('click', onPluginActionClick, true);

		window.foodordDeactivationFeedbackBooted = true;
		return true;
	};
	if (!boot()) {
		document.addEventListener(
			'DOMContentLoaded',
			() => {
				boot();
			},
			{ once: true }
		);
	}
})();
