extends CenterContainer

@export var inventory: Inventory

var current_container: LootContainer

@onready var grid_container: GridContainer = $PanelContainer/VBoxContainer/GridContainer
@onready var title_label: Label = %TitleLabel

func _ready() -> void:
	visible = false

func close() -> void:
	visible = false
	Input.mouse_mode = Input.MOUSE_MODE_CAPTURED

	if is_instance_valid(current_container):
		for item in grid_container.get_children():
			item.interact.disconnect(pickup_item)
			grid_container.remove_child(item)
			current_container.add_child(item)
			item.visible = false

func toggle_open(container: LootContainer) -> void:
	if visible:
		close()
	else:
		current_container = container
		title_label.text = container.name.capitalize()
		for item: ItemIcon in container.get_items():
			current_container.remove_child(item)
			grid_container.add_child(item)
			item.visible = true
			item.interact.connect(pickup_item)
		visible = true
		Input.mouse_mode = Input.MOUSE_MODE_VISIBLE

func pickup_item(item: ItemIcon) -> void:
	item.interact.disconnect(pickup_item)
	item.get_parent().remove_child(item)
	inventory.add_item(item)
