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


#include "HUDCommissionTrackerWidget.h"

#include "Components/PanelWidget.h"
#include "NakedDesire/Commissions/Commission.h"
#include "NakedDesire/Commissions/MissionSubsystem.h"
#include "NakedDesire/UI/Phone/Apps/ForumCommissionWidget.h"

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

	if (UMissionSubsystem* Missions = GetMissionSubsystem())
		Missions->OnBoardChanged.AddUniqueDynamic(this, &UHUDCommissionTrackerWidget::Rebuild);

	Rebuild();
}

void UHUDCommissionTrackerWidget::NativeDestruct()
{
	if (UMissionSubsystem* Missions = GetMissionSubsystem())
		Missions->OnBoardChanged.RemoveDynamic(this, &UHUDCommissionTrackerWidget::Rebuild);

	Super::NativeDestruct();
}

void UHUDCommissionTrackerWidget::Rebuild()
{
	if (!CommissionContainer || !CommissionEntryClass)
		return;

	CommissionContainer->ClearChildren();

	UMissionSubsystem* Missions = GetMissionSubsystem();
	if (!Missions)
		return;

	// Only accepted commissions are "active" — offered / completed / expired stay on the forum.
	for (UCommission* Commission : Missions->GetAcceptedCommissions())
	{
		if (!Commission)
			continue;

		UForumCommissionWidget* Entry = CreateWidget<UForumCommissionWidget>(this, CommissionEntryClass);
		if (!Entry)
			continue;

		// SetCommission collapses the accept control and keeps the row's objective progress polling live;
		// the HUD row BP simply omits the accept / abandon buttons (both optional binds).
		Entry->SetCommission(Commission);
		CommissionContainer->AddChild(Entry);
	}
}

UMissionSubsystem* UHUDCommissionTrackerWidget::GetMissionSubsystem() const
{
	const UWorld* World = GetWorld();
	return World ? World->GetSubsystem<UMissionSubsystem>() : nullptr;
}