@page "/login"
@using Microsoft.AspNetCore.Components.Authorization
@inject NavigationManager Navigation
@inject IConfiguration Configuration
@inject IJSRuntime JS

<PageTitle>Вход — GM-Relay</PageTitle>

<div class="login-page">
    <div class="login-card">
        <div class="login-logo">🎲</div>
        <h1 class="login-title">GM-Relay</h1>
        <p class="login-subtitle">Войдите через Telegram для управления игровыми сессиями</p>

        @if (Navigation.Uri.Contains("error=auth_failed"))
        {
            <div class="gm-alert gm-alert-danger" style="margin-bottom: 1.5rem; justify-content: center;">
                ⚠️ Ошибка аутентификации. Пожалуйста, попробуйте снова.
            </div>
        }

        <div id="telegram-login-container"></div>
    </div>
</div>

@code {
    private string BotUsername => Configuration["Telegram:BotUsername"] ?? "GmRelayBot";

    [CascadingParameter]
    private Task<AuthenticationState>? AuthStateTask { get; set; }

    protected override async Task OnInitializedAsync()
    {
        if (AuthStateTask is not null)
        {
            var user = (await AuthStateTask).User;
            if (user.Identity?.IsAuthenticated == true)
            {
                Navigation.NavigateTo("/");
            }
        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await JS.InvokeVoidAsync("loadTelegramWidget", BotUsername, "/auth/telegram-login");
            await JS.InvokeVoidAsync("watchTelegramMiniAppLogin", "/auth/status", "/", false);
        }
    }
}
