@page "/"
@using Microsoft.AspNetCore.Components.Authorization
@inject AuthenticationStateProvider AuthStateProvider

<MudText Typo="Typo.h3" Class="mb-4">Zahlen-Analyse</MudText>

<AuthorizeView>
    <Authorized>
        <MudText Typo="Typo.body1">Willkommen zurück, @context.User.Identity?.Name!</MudText>
        <MudText Typo="Typo.body2" Color="Color.Secondary">Deine Pocket-ID (Sub): @_userId</MudText>
        
        <MudButton Link="/logout" Variant="Variant.Filled" Color="Color.Error" Class="mt-2">
            Abmelden
        </MudButton>
    </Authorized>
    <NotAuthorized>
        <MudText Typo="Typo.body1" Class="mb-2">Bitte melde dich an, um deine Workspaces zu verwalten.</MudText>
        <MudButton Link="/login" Variant="Variant.Filled" Color="Color.Primary">
            Mit Pocket-ID anmelden
        </MudButton>
    </NotAuthorized>
</AuthorizeView>

@code {
    private string _userId = string.Empty;

    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;

        if (user.Identity?.IsAuthenticated == true)
        {
            // Das ist der "sub"-Claim (Subject), den wir als OwnerId in RavenDB nutzen
            _userId = user.FindFirst(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")?.Value 
                      ?? user.FindFirst("sub")?.Value 
                      ?? string.Empty;
        }
    }
}