@using System.Globalization
@inject NavigationManager Navigation

<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 uri = new Uri(Navigation.Uri);
        var path = uri.PathAndQuery;
        
        // Simple heuristic: if path starts with /vi-VN or /vi, show VI. Default EN.
        if (path.StartsWith("/vi", StringComparison.OrdinalIgnoreCase))
        {
            return "VI";
        }
        return "EN";
    }

    private void SwitchLanguage(string targetCulture)
    {
        var uri = new Uri(Navigation.Uri);
        var path = uri.PathAndQuery;
        
        var segments = path.Split('/', StringSplitOptions.RemoveEmptyEntries);
        
        string newPath;
        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[0] = targetCulture;
            newPath = "/" + string.Join('/', segments);
        }
        else
        {
            if (path == "/") path = "";
            newPath = $"/{targetCulture}{path}";
        }

        Navigation.NavigateTo(newPath, forceLoad: true);
    }
}
