extends Control
# ModifierTray.gd  (catalog-driven)
# Each round, asks ModifierCatalog for 3 random modifiers and spawns a draggable
# trapezoid for each at the bottom-center. Dropping one onto the board applies it
# and consumes the round's pieces.

@export var drop_catcher: Control
@export var pieces_per_round := 3

@export var piece_size := Vector2(90, 110)
@export var spacing := 24.0
@export var bottom_margin := 30.0

const TrapezoidSwatch := preload("res://Scripts/TrapezoidSwatch.gd")

var _pieces: Array[Control] = []

func _ready() -> void:
	mouse_filter = Control.MOUSE_FILTER_IGNORE
	spawn_round()

# Offer a fresh set of random modifier pieces for a new round.
func spawn_round() -> void:
	_clear_pieces()
	# ModifierCatalog is an autoload singleton (set it up in Project Settings).
	var choices: Array = ModifierCatalog.pick_random(pieces_per_round)
	if choices.is_empty():
		push_warning("ModifierTray: catalog returned no modifiers.")
		return

	for mod in choices:
		var piece := Control.new()
		piece.set_script(TrapezoidSwatch)
		piece.custom_minimum_size = piece_size
		piece.size = piece_size
		piece.modifier = mod                 # carries the WHOLE modifier
		piece.paint_texture = mod.texture    # convenience for drawing
		piece.drop_catcher = drop_catcher
		piece.tray = self
		add_child(piece)
		_pieces.append(piece)

	_layout_pieces()

func _layout_pieces() -> void:
	var count := _pieces.size()
	if count == 0:
		return
	var total_w := count * piece_size.x + (count - 1) * spacing
	var screen := get_viewport_rect().size
	var start_x := (screen.x - total_w) * 0.5
	var y := screen.y - piece_size.y - bottom_margin
	for i in count:
		_pieces[i].position = Vector2(start_x + i * (piece_size.x + spacing), y)

# Called by a piece when successfully used: remove the whole set.
func consume() -> void:
	_clear_pieces()

func _clear_pieces() -> void:
	for p in _pieces:
		if is_instance_valid(p):
			p.queue_free()
	_pieces.clear()

# TESTING ONLY: press SPACE to roll a new round of pieces.
func _unhandled_input(event: InputEvent) -> void:
	if event is InputEventKey and event.pressed and event.keycode == KEY_SPACE:
		spawn_round()
