#include "UIButton_Base.h"

#include "ZMMOThemeSubsystem.h"
#include "Engine/GameInstance.h"

namespace
{
	/** Resolve o FUIStyle ativo; fallback p/ defaults (preview de designer). */
	const FUIStyle& ResolveActiveStyle(const UUserWidget* Widget, const FUIStyle& Fallback)
	{
		if (Widget)
		{
			if (const UGameInstance* GI = Widget->GetGameInstance())
			{
				if (const UZMMOThemeSubsystem* Theme = GI->GetSubsystem<UZMMOThemeSubsystem>())
				{
					return Theme->GetActiveUIStyle();
				}
			}
		}
		return Fallback; // sem GameInstance (design-time): Aurora Arcana default
	}
}

const FUIStyleButtonVariant& UUIButton_Base::ResolveVariant(const FUIStyleButton& Button) const
{
	switch (Variant)
	{
	case EUIButtonVariant::Secondary: return Button.Secondary;
	case EUIButtonVariant::Danger:    return Button.Danger;
	case EUIButtonVariant::Ghost:     return Button.Ghost;
	case EUIButtonVariant::Primary:
	default:                          return Button.Primary;
	}
}

void UUIButton_Base::RefreshUIStyle()
{
	const FUIStyle Fallback; // defaults do struct = paleta Aurora Arcana
	const FUIStyle& ActiveStyle = ResolveActiveStyle(this, Fallback);
	BP_ApplyUIStyle(ActiveStyle.Button, ResolveVariant(ActiveStyle.Button));
}

void UUIButton_Base::NativePreConstruct()
{
	Super::NativePreConstruct();
	RefreshUIStyle(); // preview no designer (usa defaults se não há GameInstance)
}

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

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

	RefreshUIStyle();
}

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

	Super::NativeDestruct();
}

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