#include "InventoryEditor.hpp"
#include "../systems/ItemRegistry.hpp"
#include <imgui.h>

bool InventoryEditor::renderComponent(flecs::entity entity,
				      InventoryComponent &inventory)
{
	(void)entity;
	bool modified = false;
	ImGui::PushID("Inventory");

	ImGui::Text("Inventory Settings");
	ImGui::Separator();

	// Max slots
	int maxSlots = inventory.maxSlots;
	if (ImGui::DragInt("Max Slots", &maxSlots, 1, 1, 999)) {
		if (maxSlots < 1)
			maxSlots = 1;
		inventory.maxSlots = maxSlots;
		modified = true;
	}

	// Max weight
	if (ImGui::DragFloat("Max Weight", &inventory.maxWeight, 0.1f, 0.0f,
			     10000.0f, "%.1f")) {
		if (inventory.maxWeight < 0.0f)
			inventory.maxWeight = 0.0f;
		modified = true;
	}

	// Is container
	bool isContainer = inventory.isContainer;
	if (ImGui::Checkbox("Is Container", &isContainer)) {
		inventory.isContainer = isContainer;
		modified = true;
	}

	// Container ID (only for containers)
	if (inventory.isContainer) {
		char idBuf[256];
		strncpy(idBuf, inventory.containerId.c_str(), sizeof(idBuf));
		idBuf[sizeof(idBuf) - 1] = '\0';
		if (ImGui::InputText("Container ID", idBuf, sizeof(idBuf))) {
			inventory.containerId = idBuf;
			modified = true;
		}
	}

	ImGui::Separator();
	ImGui::Text("Contents (%d items, %.1f weight)", inventory.countItems(),
		    inventory.totalWeight);

	ItemRegistry *registry = ItemRegistry::getSingletonPtr();

	// List slots
	for (int i = 0; i < (int)inventory.slots.size(); i++) {
		auto &slot = inventory.slots[i];
		if (slot.isEmpty())
			continue;

		ImGui::PushID(i);
		std::string displayName = slot.itemId;
		if (registry) {
			auto *def = registry->findDefinition(slot.itemId);
			if (def)
				displayName = def->itemName;
		}
		ImGui::Text("[%d] %s x%d", i, displayName.c_str(),
			    slot.stackSize);
		ImGui::SameLine();
		if (ImGui::SmallButton("X")) {
			slot.clear();
			modified = true;
			ImGui::PopID();
			break;
		}
		ImGui::PopID();
	}

	ImGui::PopID();
	return modified;
}
