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


#include "WardrobeScreenWidget.h"

#include "Components/Button.h"
#include "Components/CanvasPanel.h"
#include "Components/CanvasPanelSlot.h"
#include "NakedDesire/UI/Inventory/Equipment/EquipmentPanelWidget.h"
#include "NakedDesire/UI/Inventory/Equipment/EquipmentSlotMenuWidget.h"
#include "NakedDesire/UI/Inventory/Equipment/EquipmentSlotWidget.h"
#include "WardrobeInventoryWidget.h"

void UWardrobeScreenWidget::NativeOnActivated()
{
	Super::NativeOnActivated();

	if (WardrobeInventory)
		WardrobeInventory->Init();

	if (!EquipmentSlotMenuWidget && EquipmentSlotMenuWidgetClass)
	{
		// Host the slot menu in the same canvas as the blocker, matching UInventoryScreenWidget.
		if (UCanvasPanel* MenuCanvas = Cast<UCanvasPanel>(MenuBlocker->GetParent()))
		{
			EquipmentSlotMenuWidget = CreateWidget<UEquipmentSlotMenuWidget>(this, EquipmentSlotMenuWidgetClass);
			if (UCanvasPanelSlot* CanvasSlot = Cast<UCanvasPanelSlot>(MenuCanvas->AddChild(EquipmentSlotMenuWidget)))
			{
				CanvasSlot->SetAutoSize(true);
				CanvasSlot->SetAnchors(FAnchors(0.f, 0.f));
				CanvasSlot->SetZOrder(1);
			}

			EquipmentSlotMenuWidget->OnActionPerformed.AddUObject(this, &UWardrobeScreenWidget::CloseMenu);
		}

		if (EquipmentPanel)
			EquipmentPanel->OnSlotClicked.BindUObject(this, &UWardrobeScreenWidget::HandleSlotClicked);

		if (MenuBlocker)
			MenuBlocker->OnClicked.AddUniqueDynamic(this, &UWardrobeScreenWidget::CloseMenu);
	}

	CloseMenu();
}

void UWardrobeScreenWidget::HandleSlotClicked(UEquipmentSlotWidget* SlotWidget)
{
	if (!EquipmentSlotMenuWidget || !SlotWidget)
		return;

	const bool bMenuOpen = EquipmentSlotMenuWidget->GetVisibility() != ESlateVisibility::Collapsed;
	if (bMenuOpen && EquipmentSlotMenuWidget->GetSlotType() == SlotWidget->GetSlotType())
	{
		CloseMenu();
		return;
	}

	// At the wardrobe the "remove" action stores the garment instead of dropping it on the ground.
	EquipmentSlotMenuWidget->Init(SlotWidget->GetSlotType(), /*bAtWardrobe=*/true);

	if (UCanvasPanelSlot* MenuSlot = Cast<UCanvasPanelSlot>(EquipmentSlotMenuWidget->Slot))
	{
		if (UCanvasPanel* MenuCanvas = Cast<UCanvasPanel>(MenuBlocker->GetParent()))
		{
			const FGeometry& SlotGeom = SlotWidget->GetCachedGeometry();
			const FVector2D AbsPos = SlotGeom.GetAbsolutePosition() + FVector2D(SlotGeom.GetAbsoluteSize().X, 0.f);
			MenuSlot->SetPosition(MenuCanvas->GetCachedGeometry().AbsoluteToLocal(AbsPos));
		}
	}

	MenuBlocker->SetVisibility(ESlateVisibility::Visible);
	EquipmentSlotMenuWidget->SetVisibility(ESlateVisibility::Visible);
}

void UWardrobeScreenWidget::CloseMenu()
{
	if (EquipmentSlotMenuWidget)
		EquipmentSlotMenuWidget->SetVisibility(ESlateVisibility::Collapsed);

	if (MenuBlocker)
		MenuBlocker->SetVisibility(ESlateVisibility::Collapsed);
}