/**
 * Answyr — public intake form.
 * Submits the support form to the REST intake route with inline status.
 */
(() => {
	document.querySelectorAll('.answyr-form').forEach((form) => {
		var endpoint = form.getAttribute('data-endpoint');
		var nonce = form.getAttribute('data-nonce') || '';
		var status = form.querySelector('.answyr-form-status');
		var button = form.querySelector('button[type="submit"]');

		form.addEventListener('submit', (e) => {
			e.preventDefault();

			var payload = {
				name: form.querySelector('[name="name"]')?.value || '',
				email: form.querySelector('[name="email"]')?.value || '',
				message: form.querySelector('[name="message"]')?.value || '',
				fields: {},
			};

			if (!payload.email || !payload.message) {
				setStatus('Please add your email and a message.', 'is-error');
				return;
			}

			// Collect any admin-configured intake fields (name="field_<key>").
			form.querySelectorAll('[name^="field_"]').forEach((input) => {
				payload.fields[input.getAttribute('name').slice('field_'.length)] = input.value;
			});

			button.disabled = true;
			setStatus('Sending…', '');

			fetch(endpoint, {
				method: 'POST',
				headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
				body: JSON.stringify(payload),
			})
				.then((r) => r.json().then((data) => ({ ok: r.ok, status: r.status, data: data })))
				.then((res) => {
					if (res.ok && res.data.ok) {
						form.reset();
						setStatus('Thanks — we got your message and will reply by email.', 'is-success');
					} else if (res.status === 429) {
						setStatus('Too many submissions. Please try again later.', 'is-error');
					} else {
						setStatus(res.data.error || 'Something went wrong. Please try again.', 'is-error');
					}
				})
				.catch((err) => {
					setStatus(err.message, 'is-error');
				})
				.finally(() => {
					button.disabled = false;
				});
		});

		function setStatus(text, cls) {
			if (!status) {
				return;
			}
			status.textContent = text;
			status.className = `answyr-form-status${cls ? ` ${cls}` : ''}`;
		}
	});
})();
