class_name CaveSpider
extends Area2D
## Araña pequeña de la cueva: patrulla en horizontal, 1 HP.
## Muere si el jugador le cae encima; daña al contacto lateral.

const SPEED := 90.0

var min_x := 0.0
var max_x := 0.0
var dir := 1.0
var dead := false

var _sprite: Sprite2D

func setup(p_min_x: float, p_max_x: float, tex: Texture2D) -> void:
	min_x = p_min_x
	max_x = p_max_x
	position.x = (min_x + max_x) * 0.5

func _ready() -> void:
	add_to_group("enemy")
	var cs := CollisionShape2D.new()
	var rect := RectangleShape2D.new()
	rect.size = Vector2(44, 36)
	cs.shape = rect
	add_child(cs)
	_sprite = Sprite2D.new()
	# Se asigna desde el builder (spider.png escalado o procedural)
	add_child(_sprite)
	body_entered.connect(_on_body_entered)
	# Las arañas cuelgan un poco: bobbing vertical leve
	var tw := create_tween().set_loops()
	tw.tween_property(_sprite, "position:y", -6.0, 0.9).set_trans(Tween.TRANS_SINE)
	tw.tween_property(_sprite, "position:y", 6.0, 0.9).set_trans(Tween.TRANS_SINE)

func _physics_process(delta: float) -> void:
	if dead:
		return
	position.x += dir * SPEED * delta
	if position.x < min_x:
		position.x = min_x
		dir = 1.0
	elif position.x > max_x:
		position.x = max_x
		dir = -1.0
	_sprite.flip_h = dir < 0.0

func _on_body_entered(body: Node2D) -> void:
	if dead:
		return
	var player := body as CavePlayer
	if player == null or not player.alive:
		return
	# ¿Stomp? Jugador cayendo y por encima
	if player.velocity.y > 120.0 and player.global_position.y < global_position.y - 10.0:
		_stomp(player)
	else:
		player.take_damage()

func _stomp(player: CavePlayer) -> void:
	dead = true
	player.velocity.y = -500.0
	player.jumps = 1  # permite encadenar saltos sobre enemigos
	var tw := create_tween()
	tw.tween_property(self, "scale", Vector2(1.4, 0.3), 0.12)
	tw.tween_callback(queue_free)

func set_texture(tex: Texture2D, target_h: float = 40.0) -> void:
	_sprite.texture = tex
	if tex != null:
		var s := target_h / float(tex.get_height())
		_sprite.scale = Vector2(s, s)
