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


#include "WardrobeInventoryWidget.h"
#include "Components/VerticalBox.h"
#include "Kismet/GameplayStatics.h"
#include "NakedDesire/Clothing/ClothingItemInstance.h"
#include "NakedDesire/Inventory/InventorySubsystem.h"
#include "WardrobeItemWidget.h"

void UWardrobeInventoryWidget::Init()
{
	if (UInventorySubsystem* Inventory = GetInventory())
		Inventory->OnWardrobeChanged.AddUniqueDynamic(this, &UWardrobeInventoryWidget::HandleWardrobeChanged);

	RenderItems();
}

void UWardrobeInventoryWidget::NativeDestruct()
{
	if (UInventorySubsystem* Inventory = GetInventory())
		Inventory->OnWardrobeChanged.RemoveDynamic(this, &UWardrobeInventoryWidget::HandleWardrobeChanged);

	Super::NativeDestruct();
}

UInventorySubsystem* UWardrobeInventoryWidget::GetInventory() const
{
	UGameInstance* GameInstance = UGameplayStatics::GetGameInstance(GetWorld());
	return GameInstance ? GameInstance->GetSubsystem<UInventorySubsystem>() : nullptr;
}

void UWardrobeInventoryWidget::HandleWardrobeChanged()
{
	RenderItems();
}

void UWardrobeInventoryWidget::HandleItemClicked(UWardrobeItemWidget* ItemWidget)
{
	if (!ItemWidget)
		return;

	if (UInventorySubsystem* Inventory = GetInventory())
		Inventory->EquipFromWardrobe(ItemWidget->GetClothingItemInstance());
}

void UWardrobeInventoryWidget::RenderItems()
{
	if (!ItemsList || !WardrobeItemWidgetClass)
		return;

	UInventorySubsystem* Inventory = GetInventory();
	if (!Inventory)
		return;

	ItemsList->ClearChildren();

	for (UItemInstance* Item : Inventory->GetWardrobeItems())
	{
		// Wardrobe holds any UItemInstance (phones / toys land here too, §6.5 / §9.9); the
		// clothing widget only renders clothing for now — other types get their own widgets later.
		UClothingItemInstance* Clothing = Cast<UClothingItemInstance>(Item);
		if (!Clothing)
			continue;

		UWardrobeItemWidget* NewItemWidget = CreateWidget<UWardrobeItemWidget>(this, WardrobeItemWidgetClass);
		NewItemWidget->SetClothingItemInstance(Clothing);
		NewItemWidget->OnItemClicked.BindUObject(this, &UWardrobeInventoryWidget::HandleItemClicked);
		ItemsList->AddChild(NewItemWidget);
	}
}