/**
 * Listing Form — AJAX submission, validation, success/error display.
 *
 * @package ThemeREX\AutoDealer
 */
(function () {
	'use strict';

	function initForm(wrapper) {
		var form = wrapper.querySelector('.trx-ad-form__form');
		if (!form || wrapper.dataset.trxAdInit) return;
		wrapper.dataset.trxAdInit = '1';

		form.addEventListener('submit', function (e) {
			e.preventDefault();
			submitForm(wrapper, form);
		});
	}

	function submitForm(wrapper, form) {
		// Clear previous errors.
		form.querySelectorAll('.trx-ad-form__input--error').forEach(function (el) {
			el.classList.remove('trx-ad-form__input--error');
		});
		var msgEl = wrapper.querySelector('.trx-ad-form__message');
		msgEl.style.display = 'none';
		msgEl.className = 'trx-ad-form__message';

		// Client-side validation.
		var requiredFields = form.querySelectorAll('[required]');
		var hasError = false;
		requiredFields.forEach(function (input) {
			if (!input.value.trim()) {
				input.classList.add('trx-ad-form__input--error');
				hasError = true;
			}
			if (input.type === 'email' && input.value.trim() && !isValidEmail(input.value)) {
				input.classList.add('trx-ad-form__input--error');
				hasError = true;
			}
		});

		if (hasError) return;

		// Disable submit.
		var btn = form.querySelector('.trx-ad-form__submit');
		btn.disabled = true;
		btn.classList.add('trx-ad-form__submit--loading');

		// Collect data.
		var formData = new FormData(form);
		var data = {};
		formData.forEach(function (value, key) {
			// Handle fields[name] format.
			var match = key.match(/^fields\[(.+)\]$/);
			if (match) {
				if (!data.fields) data.fields = {};
				data.fields[match[1]] = value;
			} else {
				data[key] = value;
			}
		});

		// Submit via REST.
		fetch(trxAdFormData.restUrl + 'forms/submit', {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				'X-WP-Nonce': trxAdFormData.restNonce
			},
			body: JSON.stringify(data)
		})
		.then(function (response) {
			return response.json().then(function (json) {
				return { ok: response.ok, data: json };
			});
		})
		.then(function (result) {
			btn.disabled = false;
			btn.classList.remove('trx-ad-form__submit--loading');

			if (result.ok && result.data.success) {
				// Success.
				var successMsg = result.data.message || wrapper.dataset.success || 'Thank you!';
				msgEl.textContent = successMsg;
				msgEl.className = 'trx-ad-form__message trx-ad-form__message--success';
				msgEl.style.display = '';
				form.reset();
			} else {
				// Error.
				var errorMsg = result.data.message || result.data.data?.message || 'An error occurred.';
				msgEl.textContent = errorMsg;
				msgEl.className = 'trx-ad-form__message trx-ad-form__message--error';
				msgEl.style.display = '';
			}
		})
		.catch(function () {
			btn.disabled = false;
			btn.classList.remove('trx-ad-form__submit--loading');
			msgEl.textContent = 'A network error occurred. Please try again.';
			msgEl.className = 'trx-ad-form__message trx-ad-form__message--error';
			msgEl.style.display = '';
		});
	}

	function isValidEmail(email) {
		return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
	}

	function initAll() {
		document.querySelectorAll('.trx-ad-form:not([data-trx-ad-init])').forEach(initForm);
	}

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

	// Elementor editor support.
	if (typeof jQuery !== 'undefined') {
		jQuery(window).on('elementor/frontend/init', function () {
			if (typeof elementorFrontend !== 'undefined') {
				elementorFrontend.hooks.addAction(
					'frontend/element_ready/trx_ad_listing_form.default',
					function ($scope) {
						var el = $scope[0].querySelector('.trx-ad-form');
						if (el) {
							delete el.dataset.trxAdInit;
							initForm(el);
						}
					}
				);
			}
		});
	}
})();
