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

#include "PhoneScreenWidget.h"

#include "PhoneHomeScreenWidget.h"
#include "Components/Button.h"
#include "Widgets/CommonActivatableWidgetContainer.h"

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

	HomeButton->OnClicked.AddUniqueDynamic(this, &UPhoneScreenWidget::GoHome);

	// Open on the home screen every time the phone is brought up.
	if (AppStack)
	{
		AppStack->ClearWidgets();
		PushHomeScreen();
	}
}

UWidget* UPhoneScreenWidget::NativeGetDesiredFocusTarget() const
{
	return HomeButton;
}

void UPhoneScreenWidget::OpenApp(TSubclassOf<UPhoneAppWidget> AppClass)
{
	if (AppStack && AppClass)
	{
		AppStack->AddWidget<UPhoneAppWidget>(AppClass);
	}
}

UPhoneHomeScreenWidget* UPhoneScreenWidget::PushHomeScreen()
{
	if (!AppStack || !HomeScreenClass)
	{
		return nullptr;
	}

	HomeScreen = AppStack->AddWidget<UPhoneHomeScreenWidget>(HomeScreenClass);
	if (HomeScreen)
	{
		HomeScreen->OnAppSelected.BindUObject(this, &UPhoneScreenWidget::OpenApp);
	}
	return HomeScreen;
}

void UPhoneScreenWidget::GoHome()
{
	if (!AppStack)
	{
		return;
	}

	// Already on the home screen — nothing to do.
	if (HomeScreen && AppStack->GetActiveWidget() == HomeScreen)
	{
		DeactivateWidget();
	}

	// Drop every app and re-seat the home screen at the base of the stack.
	AppStack->ClearWidgets();
	PushHomeScreen();
}