using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using MudBlazor.Services;
using EggymonLandingPage.Client;
using EggymonLandingPage.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();

// EN: Add Localization services
// VI: Thêm services đa ngôn ngữ
builder.Services.AddLocalization();
builder.Services.AddSingleton<LocalizationCache>();
builder.Services.AddSingleton<IStringLocalizerFactory, JsonStringLocalizerFactory>();

// EN: Build the host
// VI: Build host
var host = builder.Build();

// EN: Initialize Localization Cache
// VI: Khởi tạo Localization Cache
var cache = host.Services.GetRequiredService<LocalizationCache>();

// EN: Detect culture from BaseAddress (set by <base href> from Server)
// VI: Phát hiện ngôn ngữ từ BaseAddress (được set bởi <base href> từ 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();
