extends Node2D

# =====================================================================================
#  SLIME  --  a patrolling enemy you can now STOMP.
#
#  It walks back and forth, turning around at walls/ledges (via raycasts). Touch it
#  from the side and you die; drop on its head and you squash it and bounce off.
#
#  Because the slime is an Area2D-based hazard (not a solid body), the stomp-vs-hurt
#  decision is made here, in the Hitbox's body_entered handler, by looking at where
#  the player is and which way they're moving.
# =====================================================================================

const SPEED = 60.0
const SPLAT_COLOR = Color(0.4, 0.85, 0.35)  # green goo

var direction := 1
var dead := false

@onready var ray_cast_right = $RayCastRight
@onready var ray_cast_left  = $RayCastLeft
@onready var animated_sprite = $AnimatedSprite2D
@onready var hitbox = $Hitbox


func _process(delta):
	if dead:
		return

	# Turn around at a wall or the edge of a platform.
	if ray_cast_right.is_colliding():
		direction = -1
		animated_sprite.flip_h = true
	if ray_cast_left.is_colliding():
		direction = 1
		animated_sprite.flip_h = false

	position.x += direction * SPEED * delta


func _on_hitbox_body_entered(body):
	if dead:
		return
	if not body.is_in_group("player"):
		return

	# Stomp = the player is moving downward AND is above the slime's middle.
	# Otherwise it's a side/below hit and the player takes the damage.
	var player_is_above = body.global_position.y < global_position.y - 2.0
	if body.velocity.y > 0.0 and player_is_above:
		_squash_to_death()
		if body.has_method("bounce"):
			body.bounce()
	else:
		if body.has_method("die"):
			body.die()


# Juicy enemy death: stop, spray goo, flatten, then disappear.
func _squash_to_death():
	dead = true
	set_process(false)
	hitbox.set_deferred("monitoring", false)

	Juice.spawn_burst(global_position + Vector2(0, -8), SPLAT_COLOR, 16, 130.0)

	# Blow the sprite out to white for a single frame of "hit flash", then let the
	# tween fade that flash away as the body squashes flat.
	animated_sprite.modulate = Color(6.0, 6.0, 6.0, 1.0)

	var tween := create_tween()
	animated_sprite.scale = Vector2(1.4, 0.5)               # splat flat
	tween.tween_property(animated_sprite, "scale", Vector2(1.7, 0.0), 0.12)
	tween.parallel().tween_property(animated_sprite, "modulate", Color(1, 1, 1, 0), 0.12)
	tween.tween_callback(queue_free)
