/**
 * Answyr — portal sign-in.
 * Posts the login form via REST so a failed attempt shows an inline error
 * instead of bouncing to wp-login.php. With JS off, the form posts natively.
 */
(() => {
	var cfg = window.AnswyrPortalLogin || {};
	var form = document.getElementById('loginform');
	if (!form || !cfg.restBase) {
		return;
	}

	var errorEl = document.querySelector('.ssp-login-error');
	var submitBtn = form.querySelector('#wp-submit') || form.querySelector('input[type="submit"]');

	function showError(msg) {
		if (errorEl) {
			errorEl.textContent = msg;
			errorEl.hidden = false;
		}
	}

	form.addEventListener('submit', (e) => {
		e.preventDefault();
		if (errorEl) {
			errorEl.textContent = '';
			errorEl.hidden = true;
		}

		var data = new FormData(form);
		var original = submitBtn ? submitBtn.value : '';
		if (submitBtn) {
			submitBtn.disabled = true;
			submitBtn.value = cfg.signingIn || 'Signing in…';
		}

		fetch(`${cfg.restBase}/login`, {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify({
				nonce: cfg.nonce,
				log: data.get('log') || '',
				pwd: data.get('pwd') || '',
				remember: !!data.get('rememberme'),
			}),
		})
			.then((r) => r.json().then((body) => ({ ok: r.ok, body })))
			.then(({ ok, body }) => {
				if (ok && body && body.ok) {
					window.location.assign(cfg.redirect || window.location.href);
					return;
				}
				showError(body?.error || cfg.genericError || 'Sign-in failed.');
			})
			.catch(() => showError(cfg.genericError || 'Sign-in failed.'))
			.finally(() => {
				if (submitBtn) {
					submitBtn.disabled = false;
					submitBtn.value = original;
				}
			});
	});
})();
