// © 2025 Naked People Team. All Rights Reserved.


#include "GameplaySettingsTab.h"

#include "Components/CheckBox.h"
#include "Components/ComboBoxString.h"
#include "Kismet/KismetInternationalizationLibrary.h"
#include "NakedDesire/Global/NakedDesireUserSettings.h"

namespace
{
	// Index-aligned: combo display name → UE culture code. Add a row here when a new
	// translation ships, and make sure the culture is in DefaultGame.ini CulturesToStage.
	struct FLanguageOption
	{
		const TCHAR* DisplayName;
		const TCHAR* CultureCode;
	};

	constexpr FLanguageOption LanguageOptions[] = {
		{ TEXT("English"),     TEXT("en") },
		{ TEXT("Українська"),  TEXT("uk") },
		{ TEXT("日本語"),       TEXT("ja") }
	};
}

void UGameplaySettingsTab::NativeConstruct()
{
	Super::NativeConstruct();

	CensorshipCheckBox->OnCheckStateChanged.AddUniqueDynamic(this, &UGameplaySettingsTab::OnCensorshipChanged);
	LanguageCombo->OnSelectionChanged.AddUniqueDynamic(this, &UGameplaySettingsTab::OnLanguageChanged);

	RefreshFromSettings();
}

void UGameplaySettingsTab::RefreshFromSettings()
{
	const UNakedDesireUserSettings* Settings = UNakedDesireUserSettings::GetNakedDesireUserSettings();
	if (!Settings)
		return;

	CensorshipCheckBox->SetIsChecked(Settings->GetIsCensorshipEnabled());

	// Language: match the active culture (e.g. "uk-UA") against our supported codes by prefix.
	LanguageCombo->ClearOptions();
	const FString CurrentCulture = UKismetInternationalizationLibrary::GetCurrentLanguage();
	int32 SelectedIndex = 0;
	for (int32 i = 0; i < static_cast<int32>(UE_ARRAY_COUNT(LanguageOptions)); ++i)
	{
		LanguageCombo->AddOption(LanguageOptions[i].DisplayName);
		if (CurrentCulture.StartsWith(LanguageOptions[i].CultureCode))
			SelectedIndex = i;
	}
	LanguageCombo->SetSelectedIndex(SelectedIndex);
}

void UGameplaySettingsTab::OnCensorshipChanged(bool bIsChecked)
{
	UNakedDesireUserSettings* Settings = UNakedDesireUserSettings::GetNakedDesireUserSettings();
	if (!Settings)
		return;

	Settings->SetIsCensorshipEnabled(bIsChecked);
	// Broadcasts OnSettingsChanged so the censorship meshes update immediately.
	Settings->ApplyNonResolutionSettings();
}

void UGameplaySettingsTab::OnLanguageChanged(FString SelectedItem, ESelectInfo::Type SelectionType)
{
	// Skip the programmatic SetSelectedIndex during RefreshFromSettings.
	if (SelectionType == ESelectInfo::Direct)
		return;

	const int32 Index = LanguageCombo->GetSelectedIndex();
	if (Index < 0 || Index >= static_cast<int32>(UE_ARRAY_COUNT(LanguageOptions)))
		return;

	// Applies immediately (all LOCTEXT re-evaluates) and persists to the game config.
	UKismetInternationalizationLibrary::SetCurrentLanguageAndLocale(LanguageOptions[Index].CultureCode, /*SaveToConfig*/ true);
}