extends Node

@onready var layer = $GonerLayer

var layers: Array = []
var timer: float = 0.0
const INTERVAL: float = 2
const START_SCALE: float = 4.5
const END_SCALE: float = 8.0
const DURATION: float = 10.0

func _ready() -> void:
	layer.visible = false

func _process(delta: float) -> void:
	timer += delta
	if timer >= INTERVAL:
		timer -= INTERVAL
		_spawn_layer()

	var i: int = layers.size() - 1
	while i >= 0:
		var entry = layers[i]
		entry["elapsed"] += delta
		var t: float = clampf(entry["elapsed"] / DURATION, 0.0, 1)
		var node: Node2D = entry["node"]
		node.scale = Vector2(lerpf(START_SCALE, END_SCALE, t), lerpf(START_SCALE, END_SCALE, t))
		node.modulate.a = sin(t * PI) * 0.5
		if t >= 1.0:
			node.queue_free()
			layers.remove_at(i)
		i -= 1

func _spawn_layer() -> void:
	var clone: Node2D = layer.duplicate()
	clone.visible = true
	clone.scale = Vector2(START_SCALE, START_SCALE)
	clone.modulate = Color(1, 1, 1, 0)
	layer.get_parent().add_child(clone)
	layer.get_parent().move_child(clone, layer.get_index())
	layers.push_back({"node": clone, "elapsed": 0.0})
