using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using MudBlazor.Services;
using WebClientTpos.Client;
using WebClientTpos.Client.Localization;
using Microsoft.Extensions.Localization;
using System.Globalization;
using Microsoft.JSInterop;


var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

// EN: Add HttpClient for API calls
// VI: Thêm HttpClient cho các cuộc gọi API
builder.Services.AddSingleton(sp => new HttpClient { BaseAddress = new Uri(new Uri(builder.HostEnvironment.BaseAddress).GetLeftPart(UriPartial.Authority)) });

// EN: Add MudBlazor services
// VI: Thêm các services của MudBlazor
builder.Services.AddMudServices();

// Localization
builder.Services.AddLocalization();
builder.Services.AddSingleton<LocalizationCache>();
builder.Services.AddSingleton<IStringLocalizerFactory, JsonStringLocalizerFactory>();

// Build the host
var host = builder.Build();

// Initialize Localization Cache
var cache = host.Services.GetRequiredService<LocalizationCache>();

// Default culture is Vietnamese
var culture = new CultureInfo("vi-VN");

// Try reading saved culture preference from localStorage
try
{
    var jsRuntime = host.Services.GetRequiredService<IJSRuntime>();
    var savedCulture = await jsRuntime.InvokeAsync<string?>("localStorage.getItem", "aPOS_culture");
    if (!string.IsNullOrEmpty(savedCulture))
    {
        try { culture = new CultureInfo(savedCulture); } catch { }
    }
}
catch { /* JS not available yet during startup, use default */ }

CultureInfo.DefaultThreadCurrentCulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;

await cache.LoadAsync(culture);

await host.RunAsync();
