@inject IJSRuntime JS

<MudContainer MaxWidth="MaxWidth.Small" Class="admin-login-page admin-login-page-shell d-flex align-center justify-center">
    <MudPaper Class="pa-8 admin-login-card" Elevation="3">
        <MudStack Spacing="1" Class="mb-6 text-center">
            <MudText Typo="Typo.h4">관리자 로그인</MudText>
            <MudText Typo="Typo.body2" Color="Color.Secondary">관리자 계정으로 운영 화면에 प्रवेश합니다.</MudText>
        </MudStack>

        <form id="admin-login-form" @onsubmit="HandleLogin" @onsubmit:preventDefault>
            <MudTextField
                @bind-Value="username"
                Label="사용자명"
                Variant="Variant.Outlined"
                FullWidth="true"
                Class="mb-4"
                AutoFocus="true"
                Clearable="true" />

            <MudTextField
                @bind-Value="password"
                Label="비밀번호"
                Variant="Variant.Outlined"
                FullWidth="true"
                Class="mb-4"
                InputType="InputType.Password"
                Clearable="true" />

            <MudCheckBox T="bool"
                         @bind-Value="rememberMe"
                         Label="아이디 기억하기"
                         Color="Color.Primary"
                         Class="mb-4" />

            @if (!string.IsNullOrEmpty(errorMessage))
            {
                <MudAlert Severity="Severity.Error" Class="mb-4">@errorMessage</MudAlert>
            }

            <MudButton ButtonType="ButtonType.Submit"
                       Variant="Variant.Filled"
                       Color="Color.Primary"
                       FullWidth="true"
                       Size="Size.Large"
                       Class="mb-4">
                로그인
            </MudButton>

            @if (!string.Equals(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"), "Production", StringComparison.OrdinalIgnoreCase))
            {
                <MudText Typo="Typo.caption" Class="text-center">
                    <em>개발/테스트 환경에서만 표시되는 안내입니다.</em>
                </MudText>
            }
        </form>
    </MudPaper>
</MudContainer>

@code {
    private string username = "";
    private string password = "";
    private bool rememberMe = false;
    private string errorMessage = "";

    protected override async Task OnInitializedAsync()
    {
        // 저장된 아이디 복원
        try
        {
            var savedUsername = await JS.InvokeAsync<string>("localStorage.getItem", "admin_username_remembered");
            if (!string.IsNullOrEmpty(savedUsername))
            {
                username = savedUsername;
                rememberMe = true;
            }
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine($"localStorage 읽기 실패: {ex.Message}");
        }
    }

    private async Task HandleLogin()
    {
        errorMessage = "";

        if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
        {
            errorMessage = "사용자명과 비밀번호를 입력하세요.";
            return;
        }

        try
        {
            // 아이디 기억하기 처리
            if (rememberMe)
            {
                await JS.InvokeVoidAsync("localStorage.setItem", "admin_username_remembered", username);
            }
            else
            {
                await JS.InvokeVoidAsync("localStorage.removeItem", "admin_username_remembered");
            }

            // 로그인 폼 제출 (Razor Pages로 리다이렉트)
            // eval() 제거하고 NavigationManager 사용
            var loginUrl = $"./login?username={Uri.EscapeDataString(username)}&remember={rememberMe}";

            // window.location으로 직접 이동 (폼 제출 대체)
            await JS.InvokeVoidAsync("window.location.assign", loginUrl);
        }
        catch (Exception ex)
        {
            errorMessage = $"로그인 처리 중 오류: {ex.Message}";
            System.Diagnostics.Debug.WriteLine($"로그인 오류: {ex}");
        }
    }
}
