using System.Globalization;
using System.Net.Http.Json;

namespace WebClientTpos.Client.Localization;

public class LocalizationCache
{
    private readonly HttpClient _httpClient;
    private Dictionary<string, string> _strings = new();
    private string _loadedCulture = "";

    public LocalizationCache(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public string? GetString(string key)
    {
        if (_strings.TryGetValue(key, out var value))
        {
            return value;
        }
        return null;
    }

    public async Task LoadAsync(CultureInfo culture)
    {
        var cultureName = culture.Name;
        
        // Fallback for simple culture codes
        if (cultureName == "vi") cultureName = "vi-VN";
        if (cultureName == "en") cultureName = "en-US";

        // Skip reload only if same culture is already loaded
        if (_loadedCulture == cultureName) return;

        try
        {
            var loaded = await _httpClient.GetFromJsonAsync<Dictionary<string, string>>($"/locales/{cultureName}.json?v={DateTime.Now.Ticks}");
            if (loaded != null)
            {
                _strings = loaded;
                _loadedCulture = cultureName;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error loading localization for {culture.Name}: {ex.Message}");
        }
    }
}
