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


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
// Initialize Localization Cache
var cache = host.Services.GetRequiredService<LocalizationCache>();

// Detect culture from BaseAddress (which is set by <base href> from Server)
var baseAddress = builder.HostEnvironment.BaseAddress;
var culture = new CultureInfo("en-US"); // Default

if (baseAddress.Contains("/vi-VN/", StringComparison.OrdinalIgnoreCase))
{
    culture = new CultureInfo("vi-VN");
}
else if (baseAddress.Contains("/vi/", StringComparison.OrdinalIgnoreCase))
{
    culture = new CultureInfo("vi-VN");
}

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

await cache.LoadAsync(culture);

await host.RunAsync();
