@using System.Globalization
@inject NavigationManager Navigation
@inject IJSRuntime JS

<MudMenu Dense="true" AnchorOrigin="Origin.BottomRight" TransformOrigin="Origin.TopRight" LockScroll="true">
    <ActivatorContent>
        <MudStack Row="true" AlignItems="AlignItems.Center" Spacing="1" Class="mr-2 cursor-pointer">
             <MudText Typo="Typo.button" Style="font-family: var(--font-heading);">
                @GetCurrentLabel()
             </MudText>
             <MudIcon Icon="@Icons.Material.Rounded.Language" Size="Size.Small" />
        </MudStack>
    </ActivatorContent>
    <ChildContent>
        <MudMenuItem OnClick="@(() => SwitchLanguage("vi-VN"))">
            <MudStack Row="true" Spacing="2">
                <MudText>🇻🇳</MudText>
                <MudText>Tiếng Việt</MudText>
            </MudStack>
        </MudMenuItem>
        <MudMenuItem OnClick="@(() => SwitchLanguage("en-US"))">
            <MudStack Row="true" Spacing="2">
                <MudText>🇺🇸</MudText>
                <MudText>English</MudText>
            </MudStack>
        </MudMenuItem>
    </ChildContent>
</MudMenu>

@code {
    private string GetCurrentLabel()
    {
        var culture = CultureInfo.CurrentUICulture.Name;
        return culture.StartsWith("vi", StringComparison.OrdinalIgnoreCase) ? "VI" : "EN";
    }

    private async Task SwitchLanguage(string targetCulture)
    {
        // Save to localStorage for persistence across page reloads
        await JS.InvokeVoidAsync("localStorage.setItem", "aPOS_culture", targetCulture);
        
        // Force full page reload to reinitialize the WASM app with new culture
        var currentUri = Navigation.Uri;
        var uri = new Uri(currentUri);
        
        // Build clean URL (strip any culture segments from path)
        var path = uri.AbsolutePath;
        var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
        
        // Remove existing culture segment if present
        if (segments.Length > 0 && (
            segments[0].Equals("vi-VN", StringComparison.OrdinalIgnoreCase) || 
            segments[0].Equals("en-US", StringComparison.OrdinalIgnoreCase) ||
            segments[0].Equals("vi", StringComparison.OrdinalIgnoreCase) || 
            segments[0].Equals("en", StringComparison.OrdinalIgnoreCase)))
        {
            segments = segments.Skip(1).ToArray();
        }
        
        var cleanPath = "/" + string.Join('/', segments);
        if (cleanPath == "/") cleanPath = "";
        
        // Navigate to root with forceLoad to reinitialize WASM
        Navigation.NavigateTo($"{cleanPath}", forceLoad: true);
    }
}
