#include "ZMMOHudPlayerVitalsWidget.h"

#include "Components/RichTextBlock.h"
#include "Components/TextBlock.h"
#include "UI/Widgets/UIProgressBar_Base.h"
#include "Internationalization/Text.h"

namespace
{
	/** Formata int com separador de milhar do locale (ex.: 9840 -> "9,840"). */
	FText FormatNumber(int64 Value)
	{
		return FText::AsNumber(Value);
	}

	float SafeRatio(int32 Current, int32 Max)
	{
		return Max > 0 ? FMath::Clamp(static_cast<float>(Current) / static_cast<float>(Max), 0.f, 1.f) : 0.f;
	}
}

void UZMMOHudPlayerVitalsWidget::ApplySnapshot(const FZMMOAttributesSnapshot& Snapshot)
{
	LastSnapshot = Snapshot;

	// HP / SP (pool efetivo — % real)
	ApplyHpSp(Snapshot.Hp, Snapshot.MaxHp, Snapshot.Sp, Snapshot.MaxSp);

	// Level — markup: "LVL " (pct/cinza) + número (num/gold-bright maior)
	if (LvlText)
	{
		LvlText->SetText(FText::FromString(
			FString::Printf(TEXT("<pct>LVL </><num>%d</>"), Snapshot.BaseLevel)));
	}

	// BASE / JOB EXP — sem "exp-to-next" no snapshot. Readout mostra valor
	// absoluto acumulado (estilo Default, sem markup de %); as barras + o "%"
	// ficam pra quando a curva de exp existir no snapshot do servidor.
	if (ExpReadout)
	{
		ExpReadout->SetText(FormatNumber(Snapshot.BaseExp));
	}
	if (JobReadout)
	{
		JobReadout->SetText(FormatNumber(Snapshot.JobExp));
	}

	OnSnapshotApplied(Snapshot);
}

void UZMMOHudPlayerVitalsWidget::ApplyHpSp(int32 Hp, int32 MaxHp, int32 Sp, int32 MaxSp)
{
	LastSnapshot.Hp = Hp;
	LastSnapshot.MaxHp = MaxHp;
	LastSnapshot.Sp = Sp;
	LastSnapshot.MaxSp = MaxSp;

	if (HpBar)
	{
		HpBar->SetTargetPrimaryLevel(SafeRatio(Hp, MaxHp));
	}
	if (SpBar)
	{
		SpBar->SetTargetPrimaryLevel(SafeRatio(Sp, MaxSp));
	}
	// Markup RichText: atual (Default/branco) + "/" (sep/escuro) + max (max/cinza).
	// Tags resolvem no DT_UI_VitalsReadout (TextStyleSet do RichTextBlock).
	auto MakeReadout = [](int32 Cur, int32 Max) -> FText
	{
		return FText::FromString(FString::Printf(TEXT("%s<sep>/</><max>%s</>"),
			*FText::AsNumber(Cur).ToString(), *FText::AsNumber(Max).ToString()));
	};
	if (HpReadout)
	{
		HpReadout->SetText(MakeReadout(Hp, MaxHp));
	}
	if (SpReadout)
	{
		SpReadout->SetText(MakeReadout(Sp, MaxSp));
	}
}

void UZMMOHudPlayerVitalsWidget::SetCharName(const FString& InName)
{
	if (NameText)
	{
		NameText->SetText(FText::FromString(InName));
	}
}

void UZMMOHudPlayerVitalsWidget::SetClassName(const FString& InClassName)
{
	if (ClassText)
	{
		ClassText->SetText(FText::FromString(InClassName));
	}
}

void UZMMOHudPlayerVitalsWidget::OnSnapshotApplied_Implementation(const FZMMOAttributesSnapshot& /*Snapshot*/)
{
	// Default vazio — skin do WBP estende se quiser (low-HP flash, etc.).
}
