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


#include "SettingsScreenWidget.h"
#include "AudioSettingsTab.h"
#include "GameplaySettingsTab.h"
#include "GraphicsSettingsTab.h"
#include "Components/WidgetSwitcher.h"
#include "NakedDesire/Global/NakedDesireUserSettings.h"
#include "NakedDesire/UI/TextButton.h"

void USettingsScreenWidget::NativeOnActivated()
{
	Super::NativeOnActivated();

	GameplayTabButton->OnClicked().AddUObject(this, &USettingsScreenWidget::ShowGameplayTab);
	AudioTabButton->OnClicked().AddUObject(this, &USettingsScreenWidget::ShowAudioTab);
	GraphicsTabButton->OnClicked().AddUObject(this, &USettingsScreenWidget::ShowGraphicsTab);
	ApplyButton->OnClicked().AddUObject(this, &USettingsScreenWidget::OnApplyClicked);
	BackButton->OnClicked().AddUObject(this, &USettingsScreenWidget::OnBackClicked);

	// Pull live values into every tab so the controls reflect the current state.
	GameplayTab->RefreshFromSettings();
	AudioTab->RefreshFromSettings();
	GraphicsTab->RefreshFromSettings();

	ShowGameplayTab();
}

void USettingsScreenWidget::NativeOnDeactivated()
{
	Super::NativeOnDeactivated();

	// Persist whatever the player changed, even if they didn't hit Apply.
	PersistSettings();
}

void USettingsScreenWidget::ShowGameplayTab()
{
	TabSwitcher->SetActiveWidget(GameplayTab);
	GameplayTabButton->SetIsActive(true);
	AudioTabButton->SetIsActive(false);
	GraphicsTabButton->SetIsActive(false);
}

void USettingsScreenWidget::ShowAudioTab()
{
	TabSwitcher->SetActiveWidget(AudioTab);
	GameplayTabButton->SetIsActive(false);
	AudioTabButton->SetIsActive(true);
	GraphicsTabButton->SetIsActive(false);
}

void USettingsScreenWidget::ShowGraphicsTab()
{
	TabSwitcher->SetActiveWidget(GraphicsTab);
	GameplayTabButton->SetIsActive(false);
	AudioTabButton->SetIsActive(false);
	GraphicsTabButton->SetIsActive(true);
}

void USettingsScreenWidget::OnApplyClicked()
{
	// Commits resolution + scalability changes staged by the graphics tab.
	if (UNakedDesireUserSettings* Settings = UNakedDesireUserSettings::GetNakedDesireUserSettings())
		Settings->ApplySettings(false);

	PersistSettings();
}

void USettingsScreenWidget::OnBackClicked()
{
	DeactivateWidget();
}

void USettingsScreenWidget::PersistSettings()
{
	if (UNakedDesireUserSettings* Settings = UNakedDesireUserSettings::GetNakedDesireUserSettings())
		Settings->SaveSettings();
}