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


#include "PauseMenuWidget.h"

#include "ConfirmModalWidget.h"
#include "Components/Button.h"
#include "Kismet/GameplayStatics.h"
#include "Widgets/CommonActivatableWidgetContainer.h"

#define LOCTEXT_NAMESPACE "PauseMenu"

UPauseMenuWidget::UPauseMenuWidget()
{
	// Default to the front-end map; override per-asset on WBP_PauseMenu.
	MainMenuMap = TSoftObjectPtr<UWorld>(FSoftObjectPath(TEXT("/Game/Maps/MainMenu.MainMenu")));
}

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

	GetWorld()->GetTimerManager().SetTimer(PauseTimerHandle, this, &UPauseMenuWidget::PauseGame, 0.1f);

	ResumeButton->OnClicked.AddUniqueDynamic(this, &UPauseMenuWidget::OnResumeClicked);
	SettingsButton->OnClicked.AddUniqueDynamic(this, &UPauseMenuWidget::OnSettingsClicked);
	MainMenuButton->OnClicked.AddUniqueDynamic(this, &UPauseMenuWidget::OnMainMenuClicked);
}

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

	// Unpause whenever the menu closes — Resume, back action, or being popped.
	if (UGameplayStatics::IsGamePaused(this))
		UGameplayStatics::SetGamePaused(this, false);
}

void UPauseMenuWidget::OnResumeClicked()
{
	DeactivateWidget();
}

void UPauseMenuWidget::OnSettingsClicked()
{
	if (SettingsWidgetClass && ModalStack)
		ModalStack->AddWidget(SettingsWidgetClass);
}

void UPauseMenuWidget::OnMainMenuClicked()
{
	if (!ConfirmModalClass || !ModalStack)
	{
		HandleMainMenuConfirmed();
		return;
	}

	UConfirmModalWidget* Modal = ModalStack->AddWidget<UConfirmModalWidget>(ConfirmModalClass);
	if (!Modal)
		return;

	Modal->Setup(
		LOCTEXT("MainMenuTitle", "Main Menu"),
		LOCTEXT("MainMenuBody", "Return to the main menu? Unsaved progress may be lost."));
	Modal->OnConfirmed.AddUObject(this, &UPauseMenuWidget::HandleMainMenuConfirmed);
}

void UPauseMenuWidget::HandleMainMenuConfirmed()
{
	// Unpause before travel — level transitions while paused are unreliable.
	UGameplayStatics::SetGamePaused(this, false);

	if (MainMenuMap.IsNull())
		return;

	UGameplayStatics::OpenLevelBySoftObjectPtr(this, MainMenuMap);
}

void UPauseMenuWidget::PauseGame()
{
	UGameplayStatics::SetGamePaused(this, true);
}

#undef LOCTEXT_NAMESPACE
