extends Control

@export var collectible_ui_scene: PackedScene

@onready var grid_container: GridContainer = $%CollectibleGrid

func _ready() -> void:
	CollectionManager.on_collectible_unlocked.connect(_unlock_collectible)
	setup()

func setup() -> void:
	var unlocked_collectible_ids = CollectionManager.get_unlocked_collectible_ids()
	var collectibles = CollectionManager.get_all_collectibles()
	
	for child in grid_container.get_children():
		child.queue_free()
		
	for collectible in collectibles:
		_add_collectible(collectible)
		if unlocked_collectible_ids.has(collectible.id):
			_unlock_collectible(collectible.id)

func on_collectible_unlocked(collectible_id: StringName) -> void:
	_unlock_collectible(collectible_id)

func _add_collectible(collectible: CollectibleResource) -> void:
		var collectible_ui: CollectibleUI = collectible_ui_scene.instantiate()
		collectible_ui.setup(collectible)
		grid_container.add_child(collectible_ui)

func _unlock_collectible(collectible_id: StringName) -> void:
	for collectible_ui in grid_container.get_children():
		if collectible_ui.collectible_resource.id == collectible_id:
			collectible_ui.unlock()
