@using Microsoft.AspNetCore.Identity

@inject SignInManager<UserModel> SignInManager
@inject UserManager<UserModel> UserManager

@if (SignInManager.IsSignedIn(User))
{
    <li class="nav-item d-inline">
        <a id="manage" class="nav-link" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">
            Hello @UserManager.GetUserName(User)!
        </a>
    </li>
    <li class="nav-item d-inline">
        <a id="logout" class="nav-link" href="javascript:void(0);" onclick="logout()">Logout</a>
    </li>
    @Html.AntiForgeryToken()
    <script>
        function logout() {
            const returnUrl = '@Url.Action("Index", "Home", new { area = "" })';
            fetch('@Url.Page("/Account/Logout", new { area = "Identity" })', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `__RequestVerificationToken=${document.querySelector('input[name="__RequestVerificationToken"]').value}&returnUrl=${encodeURIComponent(returnUrl)}`
            }).then(response => {
                if (response.ok) {
                    window.location.href = returnUrl;
                } else {
                    alert('Logout failed.');
                }
            }).catch(error => {
                console.error('Logout error:', error);
            });
        }
    </script>
}
else
{
    @* <li class="nav-item">
        <a class="nav-link " id="register" asp-area="Identity" asp-page="/Account/Register">Register</a>
    </li> *@
    <li class="nav-item">
        <a class="nav-link " id="login" asp-area="Identity" asp-page="/Account/Login">Login</a>
    </li>
}
