<!DOCTYPE html>
<html lang="en">
<head>
	<title>GohCMS | 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 gap-5 m-auto form-container">
		<div>
			<h1>GohCMS</h1>
			<h2>Login</h2>
		</div>
		<form action="login" class="" method="POST">
			<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>
	</div>
</div>

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

    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()
    }

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

</body>
</html>
