@page "/verify-email"
@using WebClientTpos.Shared
@inject HttpClient Http
@inject NavigationManager Navigation
@inject IStringLocalizer<VerifyEmail> L

@* 
    EN: Email verification page.
    VI: Trang xác minh email.
*@

<PageTitle>@L["Auth_VerifyEmail_Title"]</PageTitle>

<div class="auth-container">
    <section class="auth-card text-center">
        <h1 class="auth-title">@L["Auth_VerifyEmail_Title"]</h1>
        
        @if (isVerifying)
        {
            <div class="loading-state">
                <span class="spinner"></span>
                <p class="mt-4">@L["Auth_VerifyEmail_Verifying"]</p>
            </div>
        }
        else if (success)
        {
            <div class="success-state">
                <svg class="checkmark" xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M20 6L9 17l-5-5"/>
                </svg>
                <p class="mt-4 text-lg">@L["Auth_VerifyEmail_Success"]</p>
                <button class="btn-primary mt-6" @onclick="@(() => Navigation.NavigateTo("/login"))">
                    @L["Auth_VerifyEmail_GoToLogin"]
                </button>
            </div>
        }
        else
        {
            <div class="alert alert-error">
                @message
            </div>
            <div class="mt-6">
                <a href="/login" class="link-primary">@L["Auth_VerifyEmail_GoToLogin"]</a>
            </div>
        }
    </section>
</div>

@code {
    private bool isVerifying = true;
    private bool success = false;
    private string message = "";

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await VerifyEmailAsync();
        }
    }

    /// <summary>
    /// EN: Verify email using token from query parameters.
    /// VI: Xác minh email sử dụng token từ query parameters.
    /// </summary>
    private async Task VerifyEmailAsync()
    {
        try
        {
            // EN: Parse query parameters
            // VI: Phân tích query parameters
            var uri = new Uri(Navigation.Uri);
            var query = uri.Query;
            
            string? token = null;
            string? userId = null;
            
            if (!string.IsNullOrEmpty(query))
            {
                var queryParams = System.Web.HttpUtility.ParseQueryString(query);
                token = queryParams["token"];
                userId = queryParams["userId"];
            }

            if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(userId))
            {
                success = false;
                message = L["Auth_VerifyEmail_InvalidToken"];
                isVerifying = false;
                StateHasChanged();
                return;
            }

            // EN: Call verification endpoint
            // VI: Gọi endpoint xác minh
            var response = await Http.PostAsJsonAsync("api/auth/verify-email", new { 
                Token = token.ToString(), 
                UserId = userId.ToString() 
            });

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadFromJsonAsync<ApiResponse<object>>();
                success = result?.Success == true;
                message = success ? L["Auth_VerifyEmail_Success"] : (result?.Error ?? L["Auth_VerifyEmail_Error"]);
            }
            else
            {
                success = false;
                message = L["Auth_VerifyEmail_Error"];
            }
        }
        catch (Exception ex)
        {
            success = false;
            message = $"{L["Common_Error"]}: {ex.Message}";
        }
        finally
        {
            isVerifying = false;
            StateHasChanged();
        }
    }
}
