@page
@model CSR.WebUI.Pages.AuthModel
@{
    ViewData["Title"] = "Authenticate";
}

<div class="row">
    <div class="col-md-6 offset-md-3">
        <form method="post">
            <h4>Login or Register</h4>
            <hr />
            @if (Model.ErrorMessages != null && Model.ErrorMessages.Any())
            {
                <div class="text-danger" role="alert">
                    <ul>
                        @foreach (var error in Model.ErrorMessages)
                        {
                            <li>@error</li>
                        }
                    </ul>
                </div>
            }
            <div class="form-floating mb-3">
                <input asp-for="Input.Username" class="form-control" autocomplete="username" aria-required="true" placeholder="username" />
                <label asp-for="Input.Username">Username</label>
                <span asp-validation-for="Input.Username" class="text-danger"></span>
            </div>
            <div class="form-floating mb-3">
                <input asp-for="Input.Password" class="form-control" type="password" autocomplete="current-password" aria-required="true" placeholder="password" />
                <label asp-for="Input.Password">Password</label>
                <span asp-validation-for="Input.Password" class="text-danger"></span>
            </div>
            <div class="form-floating mb-3">
                <input asp-for="Input.Email" class="form-control" autocomplete="email" placeholder="name@example.com" id="Input_Email" />
                <label asp-for="Input.Email">Email (Optional for Login)</label>
                <span asp-validation-for="Input.Email" class="text-danger"></span>
            </div>
            <div class="d-grid gap-2 d-md-flex justify-content-md-between">
                <button type="submit" asp-page-handler="Login" class="btn btn-lg btn-secondary flex-grow-1 me-2" id="loginButton">Login</button>
                <button type="submit" asp-page-handler="Register" class="btn btn-lg btn-primary flex-grow-1 ms-2">Register</button>
            </div>
        </form>
    </div>
</div>

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
    <script>
        $(document).ready(function() {
            // When the login button is clicked
            $("#loginButton").click(function() {
                var emailInput = $("#Input_Email");
                var form = $("#authForm");

                // Remove the data-val-required attribute for client-side validation
                emailInput.removeAttr("data-val-required");

                // If jQuery Validate has already initialized the form,
                // re-parse the validation for the email field to reflect the change.
                if (form.data('validator')) {
                    form.validate().element(emailInput);
                }
            });
        });
    </script>
}
