extends Control

var up_left
var down_right
var up_right
var down_left
var viewport_rect
var elapsed_time = 0.0
@export var spawn_entries: Array[SpawnEntry]

func _ready() -> void:
	var camera: Camera2D = get_parent().get_node("Camera2D")
	var viewport_size = get_viewport_rect().size
	var world_size = viewport_size / camera.zoom
	var world_origin = camera.global_position  # anchor_mode = 0 → top-left corner

	up_left = world_origin
	down_right = world_origin + world_size
	up_right = Vector2(down_right.x, up_left.y)
	down_left = Vector2(up_left.x, down_right.y)
	

func get_spawn_position() -> Vector2:
	var side = randi() % 4
	var spawn_x
	var spawn_y
	if side == 0:
		# oben
		spawn_x = randf_range(up_left.x, up_right.x)
		spawn_y = up_left.y
	elif side == 1:
		# rechts
		spawn_x = up_right.x
		spawn_y = randf_range(up_right.y, down_right.y)
	elif side == 2:
		#unten
		spawn_x = randf_range(up_left.x, up_right.x)
		spawn_y = down_left.y
	elif side == 3:
		#links
		spawn_x = up_left.x
		spawn_y = randf_range(up_right.y, down_right.y)
	return Vector2(spawn_x, spawn_y)
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	elapsed_time += delta
	pass

func spawn_enemy() -> void:
	var sum_weight = 0.0
	var available = []
	for entry in spawn_entries:
		if entry.min_time <= elapsed_time:
			available.append(entry)
			sum_weight += entry.weight
	var roll = randf() * sum_weight
	var winner = null
	for entry in available:
		roll -= entry.weight
		if roll <= 0:
			winner = entry
			break
	if winner == null:
		return
	var enemy = winner.enemy.instantiate()
	enemy.global_position = get_spawn_position()
	add_child(enemy)


func _on_spawn_timer_timeout() -> void:
	spawn_enemy()
	pass # Replace with function body.
