@using Microsoft.Extensions.Localization
@using AliasVault.Client.Services
@using Microsoft.JSInterop
@using System.Globalization
@implements IDisposable
@inject LanguageService LanguageService
@inject IJSRuntime JSRuntime

<div class="relative inline-block">
    <select value="@_currentLanguage" @onchange="OnLanguageChangedFromSelect" aria-label="Select language"
            class="appearance-none cursor-pointer pl-3 pr-9 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-800">
        @foreach (var language in LanguageService.GetSupportedLanguages())
        {
            <option value="@language.Key">@LanguageService.GetLanguageFlag(language.Key) @language.Value</option>
        }
    </select>
    <svg class="w-4 h-4 absolute right-2.5 top-1/2 -translate-y-1/2 pointer-events-none text-gray-500 dark:text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m19 9-7 7-7-7"></path>
    </svg>
</div>

@code {
    private string _currentLanguage = "en";

    public void Dispose()
    {
        LanguageService.LanguageChanged -= OnLanguageChanged;
    }

    protected override async Task OnInitializedAsync()
    {
        // Get the current culture that Blazor is actually using
        var currentCulture = System.Globalization.CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
        var supportedLanguages = LanguageService.GetSupportedLanguages();
        
        if (supportedLanguages.ContainsKey(currentCulture))
        {
            _currentLanguage = currentCulture;
        }
        else
        {
            // Fallback to getting language from service
            _currentLanguage = await LanguageService.GetCurrentLanguageAsync();
        }
        
        LanguageService.LanguageChanged += OnLanguageChanged;
        StateHasChanged();
    }

    private void OnLanguageChanged(string languageCode)
    {
        _currentLanguage = languageCode;
        InvokeAsync(StateHasChanged);
    }

    private async Task OnLanguageChangedFromSelect(ChangeEventArgs e)
    {
        var languageCode = e.Value?.ToString();
        if (!string.IsNullOrEmpty(languageCode))
        {
            await LanguageService.SetLanguageAsync(languageCode);
        }
    }
}
