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


#include "ForumCommissionsWidget.h"

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

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

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

	Rebuild();
}

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

	Super::NativeDestruct();
}

void UForumCommissionsWidget::Rebuild()
{
	UMissionSubsystem* Missions = GetMissionSubsystem();
	if (!Missions || !CommissionEntryClass)
		return;

	PopulateOffered(DailyContainer, ECommissionTier::Daily);
	PopulateOffered(WeeklyContainer, ECommissionTier::Weekly);
	PopulateContainer(AcceptedContainer, Missions->GetAcceptedCommissions());
	PopulateContainer(CompletedContainer, Missions->GetCompletedCommissions());
}

void UForumCommissionsWidget::PopulateOffered(UPanelWidget* Container, ECommissionTier Tier)
{
	if (!Container)
		return;

	Container->ClearChildren();

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

	for (UCommission* Commission : Missions->GetOfferedCommissions())
	{
		if (Commission && Commission->GetTier() == Tier)
			AddEntry(Container, Commission);
	}
}

void UForumCommissionsWidget::PopulateContainer(UPanelWidget* Container, const TArray<UCommission*>& Commissions)
{
	if (!Container)
		return;

	Container->ClearChildren();

	for (UCommission* Commission : Commissions)
	{
		if (Commission)
			AddEntry(Container, Commission);
	}
}

UForumCommissionWidget* UForumCommissionsWidget::AddEntry(UPanelWidget* Container, UCommission* Commission)
{
	UForumCommissionWidget* Entry = CreateWidget<UForumCommissionWidget>(this, CommissionEntryClass);
	if (!Entry)
		return nullptr;

	Entry->SetCommission(Commission);
	Entry->OnAcceptClicked.BindUObject(this, &UForumCommissionsWidget::HandleAcceptClicked);
	Entry->OnAbandonClicked.BindUObject(this, &UForumCommissionsWidget::HandleAbandonClicked);
	Container->AddChild(Entry);
	return Entry;
}

void UForumCommissionsWidget::HandleAcceptClicked(UCommission* Commission)
{
	// AcceptCommission broadcasts OnBoardChanged, which drives Rebuild — no manual refresh here.
	if (UMissionSubsystem* Missions = GetMissionSubsystem())
		Missions->AcceptCommission(Commission);
}

void UForumCommissionsWidget::HandleAbandonClicked(UCommission* Commission)
{
	if (UMissionSubsystem* Missions = GetMissionSubsystem())
		Missions->AbandonCommission(Commission);
}

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