extends Label

@export var label: String = "1"

@export var color := Color.RED  # Red color for damage numbers
@export var direction := Vector2.ZERO # Default direction (will be random if not set)
var fade_delay := 0.6 # When to start fading (display duration)
var move_duration := 1.0 # Total animation duration (includes fade)
var fade_duration := 0.4 # Time to fade out (after fade_delay)
var rise_distance: float = 20.0  # Distance to move upward
var stretch_amount := Vector2(1, 1.4) # How much to stretch the sprite

# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	call_deferred("_initialize_damage_number")
	pass # Replace with function body.

func _initialize_damage_number() -> void:
	# Reparent to FloatingTextLayer (not affected by CanvasModulate).
	# Layer has follow_viewport_enabled = true so it scrolls with world → use world position, not screen.
	var gw = get_tree().get_first_node_in_group("game_world")
	var layer = gw.get_node_or_null("FloatingTextLayer") if gw else null
	if layer and gw:
		var world_pos = global_position
		get_parent().remove_child(self)
		layer.add_child(self)
		global_position = world_pos
	# Ensure visible: use default layer so camera/viewport always draws us (fixes layer 262144 not being shown)
	visibility_layer = 1
	light_mask = 1
	# Set color (red by default) and text
	self.modulate = color
	self.text = label
	
	# If direction is not set, use a random upward direction with slight variation
	if direction == Vector2.ZERO:
		var random_angle = randf_range(-PI/6, PI/6)  # ±30 degrees from straight up
		direction = Vector2(sin(random_angle), -cos(random_angle))  # Mostly upward with slight variation
	
	# Calculate target position (move upward with slight horizontal variation; in screen space if on layer)
	var move_target = global_position + (direction.normalized() * rise_distance)
	
	# Total animation duration = display (0.6s) + fade (0.4s) = 1.0s
	var total_duration = fade_delay + fade_duration  # 0.6 + 0.4 = 1.0s
	
	# Create tween for movement (entire duration, continues during fade)
	var move_tween = create_tween()
	move_tween.set_trans(Tween.TRANS_CUBIC)
	move_tween.set_ease(Tween.EASE_OUT)
	move_tween.tween_property(self, "global_position", move_target, total_duration)
	
	# Wait for display duration (0.6s), then start fading
	await get_tree().create_timer(fade_delay).timeout
	
	# Fade out over fade_duration (0.4s) while still moving
	var fade_tween = create_tween()
	fade_tween.tween_property(self, "modulate:a", 0.0, fade_duration)
	
	# Wait for fade to complete, then remove
	await fade_tween.finished
	queue_free()
	pass
