/**
 * Pro — Lead-capture form (single vehicle page).
 *
 * Client-side validation + AJAX submit with an inline success state.
 *
 * @package AutomotiveFeedImport
 */
(function () {
	'use strict';

	if (typeof window.aiiLead === 'undefined') { return; }
	var form = document.getElementById('afi-leadform');
	if (!form) { return; }

	var cfg = window.aiiLead;
	var submitBtn = form.querySelector('button[type="submit"]');

	function field(name) { return form.querySelector('.aii-field[data-validate="' + name + '"]'); }
	function setError(name, on) { var f = field(name); if (f) { f.classList.toggle('is-error', !!on); } }

	function validate() {
		var ok = true;
		var name = (form.elements.name.value || '').trim();
		var email = (form.elements.email.value || '').trim();
		setError('name', !name);
		if (!name) { ok = false; }
		var emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
		setError('email', !emailOk);
		if (!emailOk) { ok = false; }
		return ok;
	}

	form.addEventListener('input', function (e) {
		var f = e.target.closest('.aii-field[data-validate]');
		if (f) { f.classList.remove('is-error'); }
	});

	form.addEventListener('submit', function (e) {
		e.preventDefault();
		if (!validate()) {
			var firstErr = form.querySelector('.aii-field.is-error .aii-input');
			if (firstErr) { firstErr.focus(); }
			return;
		}

		var fd = new FormData(form);
		fd.append('action', 'afi_lead_submit');
		fd.append('nonce', cfg.nonce);
		fd.append('vehicle_id', form.dataset.vehicle);

		submitBtn.disabled = true;
		submitBtn.textContent = cfg.i18n.sending;

		fetch(cfg.ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
			.then(function (r) { return r.json(); })
			.then(function (res) {
				submitBtn.disabled = false;
				submitBtn.textContent = cfg.i18n.send;
				if (res && res.success) {
					form.classList.add('is-success');
					var sa = form.querySelector('[data-leadreset]');
					if (sa) { sa.focus(); }
				} else if (res && res.data && res.data.errors) {
					Object.keys(res.data.errors).forEach(function (k) { setError(k, true); });
					var fe = form.querySelector('.aii-field.is-error .aii-input');
					if (fe) { fe.focus(); }
				} else {
					window.alert(cfg.i18n.error);
				}
			})
			.catch(function () {
				submitBtn.disabled = false;
				submitBtn.textContent = cfg.i18n.send;
				window.alert(cfg.i18n.error);
			});
	});

	form.addEventListener('click', function (e) {
		if (e.target.closest('[data-leadreset]')) {
			form.classList.remove('is-success');
			form.reset();
		}
	});
})();
