extends AnimatedSprite2D
class_name Explosion

# Per-instance override; leave at 1.0 to use GameConfig.explosion_scale (the
# one shared knob for resizing every explosion in the game at once).
@export var scale_override: float = 0.0

# Ships no longer collide with each other (see ship.tscn's collision layers),
# but flying straight through an explosion's sprite still looked wrong, so
# GhostArea (a child Area2D, scaled along with this node) hides any ship's
# sprite while it overlaps and restores it on exit. Tracked here so a ship
# still inside when this explosion despawns gets un-ghosted rather than
# stuck invisible.
var _ghosted_ships: Array = []


func _ready() -> void:
	var s: float = scale_override if scale_override > 0.0 else GameConfig.explosion_scale
	scale = Vector2.ONE * s
	sprite_frames.set_animation_speed("explode", GameConfig.explosion_fps)
	play("explode")
	animation_finished.connect(queue_free)

	var ghost_area := get_node("GhostArea") as Area2D
	ghost_area.body_entered.connect(_on_body_entered)
	ghost_area.body_exited.connect(_on_body_exited)


func _on_body_entered(body: Node) -> void:
	if body.has_method("set_ghosted"):
		body.set_ghosted(true)
		_ghosted_ships.append(body)


func _on_body_exited(body: Node) -> void:
	if body.has_method("set_ghosted"):
		body.set_ghosted(false)
	_ghosted_ships.erase(body)


func _exit_tree() -> void:
	for ship in _ghosted_ships:
		if is_instance_valid(ship):
			ship.set_ghosted(false)
