extends CanvasLayer

# Level Text UI - Shows "LEVEL #" when starting a new level

var level_label: Label = null

func _ready():
	visible = false
	# Find level label (works for both scene-based and programmatically created UI)
	var vbox = get_child(0) if get_child_count() > 0 else null
	if vbox:
		for child in vbox.get_children():
			if child.name == "LevelLabel" or child is Label:
				level_label = child
				break

func show_level(level_number: int):
	print("LevelTextUI: show_level(", level_number, ") called")
	
	# Stop any existing tweens to prevent conflicts
	var existing_tweens = get_tree().get_processed_tweens()
	for tween in existing_tweens:
		if tween.is_valid():
			tween.kill()
	
	# Get vbox once at the start (reuse throughout function)
	var vbox = get_child(0) if get_child_count() > 0 else null
	
	# Update label text FIRST before showing
	if level_label:
		level_label.text = "LEVEL " + str(level_number)
		print("LevelTextUI: Set label text to: ", level_label.text)
	else:
		print("LevelTextUI: ERROR - level_label is null!")
		# Try to find it again
		if vbox:
			for child in vbox.get_children():
				if child.name == "LevelLabel" or child is Label:
					level_label = child
					level_label.text = "LEVEL " + str(level_number)
					print("LevelTextUI: Found label and set text to: ", level_label.text)
					break
	
	# Show UI
	visible = true
	
	# Fade in - fade the VBoxContainer and level label
	if vbox:
		vbox.modulate.a = 0.0
		var fade_in = create_tween()
		fade_in.set_parallel(true)
		fade_in.tween_property(vbox, "modulate:a", 1.0, 0.5)
		
		if level_label:
			level_label.modulate.a = 0.0
			fade_in.tween_property(level_label, "modulate:a", 1.0, 0.5)
	
	# Fade out after 3 seconds
	await get_tree().create_timer(3.0).timeout
	
	if vbox:
		var fade_out = create_tween()
		fade_out.set_parallel(true)
		fade_out.tween_property(vbox, "modulate:a", 0.0, 0.5)
		
		if level_label:
			fade_out.tween_property(level_label, "modulate:a", 0.0, 0.5)
		
		await fade_out.finished
	
	visible = false
