extends CharacterBody2D
# Tile debris from bomb explosion - flies out, bounces off walls, fades

var angular_velocity: float = 0.0
var fade_timer: float = 0.0
var fading: bool = false
const FADE_DELAY: float = 0.8
const BOUNCE_DAMP: float = 0.82  # Keep more speed after bounce - fly around more

# Z-axis physics (fly up, then fall back down with gravity)
var position_z: float = 0.0
var velocity_z: float = 0.0
var acceleration_z: float = -500.0  # Downward gravity

func _physics_process(delta: float) -> void:
	if fading:
		return
	
	# Slow down over time (slower decay so they keep flying longer)
	velocity = velocity.lerp(Vector2.ZERO, delta * 1.8)
	if abs(angular_velocity) > 0.1:
		rotation += angular_velocity * delta
		angular_velocity = lerp(angular_velocity, 0.0, delta * 1.5)
	
	# Z physics: gravity, then integrate
	velocity_z += acceleration_z * delta
	position_z += velocity_z * delta
	if position_z <= 0.0:
		position_z = 0.0
		velocity_z = 0.0
	
	move_and_slide()
	
	# Bounce off walls (tilemap uses layer 7 = bit 64)
	for i in get_slide_collision_count():
		var col = get_slide_collision(i)
		if col and col.get_collider() is CollisionObject2D:
			var wall = col.get_collider() as CollisionObject2D
			if wall.get_collision_layer_value(7):  # Layer 7 = walls
				velocity = velocity.bounce(col.get_normal()) * BOUNCE_DAMP
				angular_velocity *= -0.6
				break
	
	# Visual: raise sprite when airborne, scale up a little when flying upward
	var spr = get_node_or_null("Sprite2D")
	if spr:
		spr.position.y = -position_z * 0.5
		var scale_up = 1.0 + (position_z / 60.0) * 0.25  # Slightly bigger when higher
		spr.scale = Vector2.ONE * clampf(scale_up, 1.0, 1.35)
	
	# Fade after delay
	fade_timer += delta
	if fade_timer >= FADE_DELAY:
		fading = true
		if spr:
			var t = create_tween()
			t.tween_property(spr, "modulate:a", 0.0, 0.4)
			t.tween_callback(queue_free)
		else:
			queue_free()
