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


#include "TravelObjectiveBase.h"

#include "TimerManager.h"
#include "NakedDesire/Player/NakedDesireCharacter.h"

namespace
{
	constexpr float SampleIntervalSeconds = 0.2f;
	constexpr float MaxStepCm = 1000.0f; // ignore single-sample jumps larger than this (teleports / streaming)
}

void UTravelObjectiveBase::OnActivate()
{
	Super::OnActivate();

	AccumulatedCm = 0.0f;

	if (Player)
	{
		LastLocation = Player->GetActorLocation();
		Player->GetWorldTimerManager().SetTimer(SampleTimer, this, &UTravelObjectiveBase::SampleDistance, SampleIntervalSeconds, true);
	}
}

void UTravelObjectiveBase::OnDeactivate()
{
	if (Player)
		Player->GetWorldTimerManager().ClearTimer(SampleTimer);
	SampleTimer.Invalidate();

	Super::OnDeactivate();
}

void UTravelObjectiveBase::SampleDistance()
{
	if (bSatisfied || !Player)
		return;

	const FVector Now = Player->GetActorLocation();
	const float Delta = FVector::Dist(Now, LastLocation);
	LastLocation = Now;

	if (DoesSampleCount() && AreConstraintsMet())
	{
		AccumulatedCm += FMath::Min(Delta, MaxStepCm);
		if (AccumulatedCm >= RequiredMeters * 100.0f)
			MarkSatisfied();
	}
}

float UTravelObjectiveBase::GetProgress() const
{
	if (bSatisfied)
		return 1.0f;

	const float TargetCm = RequiredMeters * 100.0f;
	return TargetCm > 0.0f ? FMath::Clamp(AccumulatedCm / TargetCm, 0.0f, 1.0f) : 0.0f;
}