#include "UIActivatableScreen_Base.h"

#include "ZMMOThemeSubsystem.h"
#include "UIFrontEndFlowSubsystem.h"
#include "Engine/GameInstance.h"
#include "Input/UIActionBindingHandle.h"
#include "CommonInputModeTypes.h"

TOptional<FUIInputConfig> UUIActivatableScreen_Base::GetDesiredInputConfig() const
{
	switch (InputConfig)
	{
	case EZMMOScreenInputMode::GameAndMenu:
		return FUIInputConfig(ECommonInputMode::All, GameMouseCaptureMode);
	case EZMMOScreenInputMode::Game:
		return FUIInputConfig(ECommonInputMode::Game, GameMouseCaptureMode);
	case EZMMOScreenInputMode::Menu:
		return FUIInputConfig(ECommonInputMode::Menu, EMouseCaptureMode::NoCapture);
	case EZMMOScreenInputMode::Default:
	default:
		return TOptional<FUIInputConfig>();
	}
}

void UUIActivatableScreen_Base::RefreshUIStyle_Implementation()
{
	// Base no-op: cada WBP/filho sobrescreve para reaplicar tokens do tema
	// ativo (via UZMMOThemeSubsystem). Mantém o contrato igual a
	// UUIButton_Base::RefreshUIStyle / UUIPanel_Base::RefreshUIStyle.
}

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

	if (!bThemeBound)
	{
		if (const UGameInstance* GI = GetGameInstance())
		{
			if (UZMMOThemeSubsystem* Theme = GI->GetSubsystem<UZMMOThemeSubsystem>())
			{
				Theme->OnThemeChanged.AddDynamic(this, &UUIActivatableScreen_Base::HandleThemeChanged);
				bThemeBound = true;
			}
		}
	}

	RefreshUIStyle();
}

void UUIActivatableScreen_Base::NativeDestruct()
{
	if (bThemeBound)
	{
		if (const UGameInstance* GI = GetGameInstance())
		{
			if (UZMMOThemeSubsystem* Theme = GI->GetSubsystem<UZMMOThemeSubsystem>())
			{
				Theme->OnThemeChanged.RemoveDynamic(this, &UUIActivatableScreen_Base::HandleThemeChanged);
			}
		}
		bThemeBound = false;
	}

	Super::NativeDestruct();
}

void UUIActivatableScreen_Base::NativeOnActivated()
{
	Super::NativeOnActivated();
	RefreshUIStyle();
	BP_OnScreenActivated();
}

void UUIActivatableScreen_Base::NativeOnDeactivated()
{
	Super::NativeOnDeactivated();
	BP_OnScreenDeactivated();
}

bool UUIActivatableScreen_Base::NativeOnHandleBackAction()
{
	if (const UGameInstance* GI = GetGameInstance())
	{
		if (UUIFrontEndFlowSubsystem* Flow = GI->GetSubsystem<UUIFrontEndFlowSubsystem>())
		{
			if (Flow->RequestBack())
			{
				return true; // consumido pelo fluxo
			}
		}
	}
	return Super::NativeOnHandleBackAction();
}

void UUIActivatableScreen_Base::HandleThemeChanged(FName /*NewThemeId*/)
{
	RefreshUIStyle();
}
