const form = document.querySelector("#signup-form");
const message = document.querySelector("#message");
const title = document.querySelector("#signup-title");

function showError(text) {
	message.textContent = text;
	message.className = "auth-message error";
}
function showInfo(text) {
	message.textContent = text;
	message.className = "auth-message info";
}

(async function checkSignupEnabled() {
	try {
		const response = await fetch("/api/auth/signup-enabled");
		const body = await response.json();
		if (body.enabled) {
			form.classList.remove("hidden");
		} else {
			title.textContent = "Invite only";
			showInfo(
				"New signups are currently disabled. Ask an administrator for an invitation.",
			);
		}
	} catch {
		// Don't strand a new customer on a dead page over one failed probe — show the form and
		// let the real submit enforce the signup-enabled rule if it turns out to matter.
		form.classList.remove("hidden");
		showError(
			"Could not confirm signups are open. You can still try creating an account below.",
		);
	}
})();

form.addEventListener("submit", async (event) => {
	event.preventDefault();
	const data = Object.fromEntries(new FormData(form));
	if (data.password !== data.confirmPassword) {
		showError("Passwords do not match.");
		return;
	}
	const submitButton = form.querySelector("button[type=submit]");
	submitButton.disabled = true;
	message.textContent = "";
	try {
		const response = await fetch("/api/auth/signup", {
			method: "POST",
			headers: { "content-type": "application/json" },
			body: JSON.stringify({ email: data.email, password: data.password }),
		});
		const body = await response.json();
		if (!response.ok) {
			showError(
				{
					email_exists: "An account with that email already exists.",
					signup_disabled:
						"New signups are currently disabled. Ask an administrator for an invitation.",
				}[body.code] || body.error || "Could not create the account.",
			);
			return;
		}
		location.assign("/app");
	} catch {
		showError("Could not reach the server. Check your connection and try again.");
	} finally {
		submitButton.disabled = false;
	}
});
