@inherits AliasVault.Client.Auth.Pages.Base.LoginBase
@layout Auth.Layout.EmptyLayout
@attribute [AllowAnonymous]
@using System.Text.Json
@using AliasVault.Client.Utilities
@using AliasVault.Cryptography.Client
@using AliasVault.Shared.Models.WebApi.Auth
@using SecureRemotePassword

<div class="w-full mx-auto">
    <div class="relative inset-0 mt-10 z-10">
        <GlobalNotificationDisplay />
        @if (IsLoading)
        {
            <div class="flex justify-center items-center">
                <div class="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-primary-500"></div>
            </div>
        }
    </div>
</div>

@code {
    /// <summary>
    /// The username to use for the new account.
    /// </summary>
    [Parameter]
    public string Username { get; set; } = string.Empty;

    /// <summary>
    /// The password to use for the new account.
    /// </summary>
    [Parameter]
    public string Password { get; set; } = string.Empty;

    private bool IsLoading { get; set; } = true;

    /// <inheritdoc />
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
            await CompleteSetup();
        }
    }

    private async Task CompleteSetup()
    {
        StateHasChanged();

        var (success, errorMessage) = await UserRegistrationService.RegisterUserAsync(Username, Password);

        if (success)
        {
            NavigationManager.NavigateTo("/");
        }
        else
        {
            IsLoading = false;
            GlobalNotificationService.AddErrorMessage(errorMessage ?? "An error occurred during registration.", true);
            StateHasChanged();
        }
    }
}
