@using System.Security.Claims
@inject NavigationManager NavManager

@*
 *                                dbMango
 *
 * Copyright 2025 Deutsche Bank AG
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *@

<style>
    .arrow-margin {
        margin-top: 2px;
    }
</style>

<AuthorizeView>
    <Authorized>
        <span class="nav-link">@GetEmail(context.User)</span>
        <div class="nav-link" @onclick="@(Logout)">Logout</div>
    </Authorized>
    <NotAuthorized>
        <div class="flex-stack-horizontal">
            <BouncingArrow Class="arrow-margin"/>
            <div class="nav-link" @onclick="@(Login)">Login</div>
        </div>
    </NotAuthorized>
</AuthorizeView>

@code {

    [Parameter]
    public bool ForceLogin { get; set; }

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender && ForceLogin)
        {
            Login();
        }
    }

    private void Login()
    {
        NavManager.NavigateTo($"/login/{Uri.EscapeDataString(Base64Encode(NavManager.ToBaseRelativePath(NavManager.Uri)))}", true, true);
    }

    private static string Base64Encode(string plainText)
    {
        var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
        return Convert.ToBase64String(plainTextBytes);
    }

    private void Logout()
    {
        NavManager.NavigateTo("/logout", true, true);
    }

    private string GetEmail( ClaimsPrincipal principal )
    {
        var email = principal.FindFirst(ClaimTypes.Email);
        return email?.Value ?? "";
    }

}
