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


#include "EquipmentSlotWidget.h"
#include "Kismet/GameplayStatics.h"
#include "NakedDesire/Clothing/ClothingItemDefinition.h"
#include "NakedDesire/Clothing/ClothingItemInstance.h"
#include "NakedDesire/Clothing/ClothingManager.h"
#include "NakedDesire/Clothing/ClothingSlotsData.h"
#include "NakedDesire/Player/NakedDesireCharacter.h"

void UEquipmentSlotWidget::SetItem(UClothingItemInstance* InItem)
{
	ClothingItemInstance = InItem;
	
	IconImage->SetBrushFromTexture(InItem->GetClothingItemDefinition()->Icon);
	IconImage->SetVisibility(ESlateVisibility::SelfHitTestInvisible);
	PlaceholderImage->SetVisibility(ESlateVisibility::Hidden);
	SetIsEnabled(true);
}

void UEquipmentSlotWidget::ClearItem()
{
	ClothingItemInstance = nullptr;
	
	IconImage->SetBrushFromTexture(nullptr);
	IconImage->SetVisibility(ESlateVisibility::Hidden);
	PlaceholderImage->SetVisibility(ESlateVisibility::SelfHitTestInvisible);
	SetIsEnabled(false);
}

void UEquipmentSlotWidget::NativeOnClicked()
{
	Super::NativeOnClicked();
	
	OnEquipmentSlotClicked.ExecuteIfBound(this);
}

void UEquipmentSlotWidget::NativePreConstruct()
{
	Super::NativePreConstruct();
	
	InitSlotVisuals();
}

void UEquipmentSlotWidget::OnClothingEquip(UClothingItemInstance* InClothingItemInstance)
{
	if (InClothingItemInstance->GetClothingItemDefinition()->SlotType != SlotType)
		return;
	
	SetItem(InClothingItemInstance);
}

void UEquipmentSlotWidget::OnClothingUnequip(UClothingItemInstance* InClothingItemInstance)
{
	if (InClothingItemInstance->GetClothingItemDefinition()->SlotType != SlotType)
		return;
	
	ClearItem();
}

void UEquipmentSlotWidget::InitSlotVisuals()
{
	if (!ClothingSlotsData)
		return;
	
	const FClothingSlotData& SlotData = ClothingSlotsData->Slots[SlotType];
	PlaceholderImage->SetBrushFromTexture(SlotData.Icon);
}

void UEquipmentSlotWidget::SetSlotType(const EClothingSlotType InSlotType)
{
	SlotType = InSlotType;
	
	InitSlotVisuals();
}

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

	const ANakedDesireCharacter* Player = Cast<ANakedDesireCharacter>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0));
	
	Player->ClothingManager->OnClothingEquip.AddUniqueDynamic(this, &UEquipmentSlotWidget::OnClothingEquip);
	Player->ClothingManager->OnClothingUnequip.AddUniqueDynamic(this, &UEquipmentSlotWidget::OnClothingUnequip);
}
