#include "UIManagerSubsystem.h"

#include "ZMMO.h"
#include "UIPrimaryGameLayout_Base.h"
#include "CommonActivatableWidget.h"
#include "Engine/LocalPlayer.h"
#include "GameFramework/PlayerController.h"
#include "Blueprint/UserWidget.h"

namespace
{
	constexpr int32 GRootLayoutZOrder = 1000;
}

void UUIManagerSubsystem::CreateAndAddRootLayout(TSubclassOf<UUIPrimaryGameLayout_Base> LayoutClass)
{
	// Idempotente: sobrevive ao travel boot→mundo sem recriar.
	if (RootLayout && RootLayout->IsInViewport())
	{
		return;
	}

	if (!LayoutClass)
	{
		UE_LOG(LogZMMO, Warning,
			TEXT("UIManagerSubsystem: RootLayoutClass não configurado (DA_FrontEndScreenSet vazio?). Sem root layout."));
		return;
	}

	ULocalPlayer* LP = GetLocalPlayer();
	if (!LP)
	{
		return;
	}

	APlayerController* PC = LP->GetPlayerController(LP->GetWorld());
	if (!PC)
	{
		UE_LOG(LogZMMO, Warning, TEXT("UIManagerSubsystem: PlayerController ausente; root layout adiado."));
		return;
	}

	RootLayout = CreateWidget<UUIPrimaryGameLayout_Base>(PC, LayoutClass);
	if (!RootLayout)
	{
		UE_LOG(LogZMMO, Warning, TEXT("UIManagerSubsystem: falha ao criar o root layout."));
		return;
	}

	RootLayout->AddToViewport(GRootLayoutZOrder);
	UE_LOG(LogZMMO, Log, TEXT("UIManagerSubsystem: root layout criado e adicionado ao viewport."));
}

bool UUIManagerSubsystem::IsRootLayoutReady() const
{
	return RootLayout != nullptr && RootLayout->IsInViewport();
}

UCommonActivatableWidget* UUIManagerSubsystem::PushScreenToLayer(
	FGameplayTag LayerTag,
	TSubclassOf<UCommonActivatableWidget> WidgetClass)
{
	if (!RootLayout)
	{
		UE_LOG(LogZMMO, Warning, TEXT("UIManagerSubsystem: PushScreenToLayer sem root layout."));
		return nullptr;
	}
	return RootLayout->PushWidgetToLayer(LayerTag, WidgetClass);
}

void UUIManagerSubsystem::PopScreenFromLayer(FGameplayTag LayerTag, UCommonActivatableWidget* Widget)
{
	if (RootLayout)
	{
		RootLayout->PopWidgetFromLayer(LayerTag, Widget);
	}
}

void UUIManagerSubsystem::ClearLayer(FGameplayTag LayerTag)
{
	if (RootLayout)
	{
		RootLayout->ClearLayer(LayerTag);
	}
}

void UUIManagerSubsystem::Deinitialize()
{
	if (RootLayout)
	{
		RootLayout->RemoveFromParent();
		RootLayout = nullptr;
	}
	Super::Deinitialize();
}
