<!DOCTYPE html>
<html lang="en">
<head>
	<title>GoCMS | Login</title>
	{{.Head}}

	<style>
        .form-container {
            max-width: 24rem;
        }
	</style>
</head>
<body class="d-flex min-vh-100 vw-100 justify-content-center align-items-center text-dark">
<div class="container">
	<div class="d-flex flex-column m-auto form-container">
		<div>
			<h1>GoCMS</h1>
			<h2>Login</h2>
		</div>
		<form action="login" method="POST" class="mt-5" id="loginForm">
			<div class="d-flex flex-column gap-4">
				<div class="form-floating">
					<input class="form-control {{ if .PageError.IsError }} is-invalid {{ end }}"
						   id="username"
						   name="username"
						   placeholder="Username"
						   required
						   type="text"
						   value="{{.Username}}">
					<label for="username">Username</label>
				</div>
				<div class="form-floating">
					<input class="form-control {{ if .PageError.IsError }} is-invalid {{ end }}"
						   id="password"
						   name="password"
						   placeholder="Password"
						   required
						   type="password">
					<label for="password">Password</label>
					<div class="invalid-feedback">{{.PageError.Message}}</div>
				</div>
				<button id="loginFormButton" class="btn btn-primary" disabled type="submit">
						<span class="loginFormButtonLoading visually-hidden spinner-border spinner-border-sm"
							  role="status"></span>
					<span class="loginFormButtonDefault">Log in</span>
				</button>
			</div>
		</form>
        <form action="register" method="get" class="mt-2 w-100">
            <button class="btn btn-link w-100" type="submit">
				Don't have any verified account? Register here.
			</button>
		</form>
	</div>
</div>

<script>
    const button = document.querySelector("#loginFormButton")
    const inputs = document.querySelectorAll('input')
	const form = document.querySelector("#loginForm")

    function formFieldsEmpty() {
        return Array.from(inputs).some((input) => input.value === "")
    }

    function setButtonDisabled() {
        button.disabled = formFieldsEmpty() ? "disabled" : ""
    }

    function setButtonLoading() {
        button.classList.add("disabled")
        button.querySelector(".loginFormButtonDefault").classList.add("visually-hidden")
        button.querySelector(".loginFormButtonLoading").classList.remove("visually-hidden")
    }

    function onLoginFormSubmit(event) {
        event.preventDefault()
        setButtonLoading()
        event.target.submit()
    }

    function onInput(event) {
        if (event.target.tagName === "INPUT") setButtonDisabled()
    }

    form.addEventListener('submit', onLoginFormSubmit)
    window.addEventListener('input', onInput)
    setButtonDisabled()
</script>

</body>
</html>
