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

namespace EggymonLandingPage.Client.Localization;

/// <summary>
/// EN: Cache for localization strings loaded from JSON files.
/// VI: Cache cho các chuỗi bản địa hóa được tải từ file JSON.
/// </summary>
public class LocalizationCache
{
    private readonly HttpClient _httpClient;
    private Dictionary<string, string> _strings = new();
    private bool _isLoaded;

    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)
    {
        if (_isLoaded) return;

        try
        {
            var cultureName = culture.Name;
            // EN: Map generic culture codes to specific ones
            // VI: Map mã ngôn ngữ chung sang mã cụ thể
            if (cultureName == "vi") cultureName = "vi-VN";
            if (cultureName == "en") cultureName = "en-US";

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