extends Area2D

# Stairs that trigger level completion when player enters

@onready var sfx_stairs = null

func _ready():
	# Connect body entered signal
	body_entered.connect(_on_body_entered)
	
	# Set collision layer/mask to detect players
	collision_layer = 0
	collision_mask = 1  # Detect players (layer 1)
	
	# Load stairs sound effect
	if not sfx_stairs:
		# Try to create AudioStreamPlayer2D if it doesn't exist
		sfx_stairs = AudioStreamPlayer2D.new()
		sfx_stairs.name = "SfxStairs"
		add_child(sfx_stairs)
	
	# Load go_down_stairs.mp3 sound
	var stairs_sound = load("res://assets/audio/sfx/walk/go_down_stairs.mp3")
	if stairs_sound:
		sfx_stairs.stream = stairs_sound
	else:
		print("Stairs: Warning - Could not load go_down_stairs.mp3")

func _on_body_entered(body: Node2D):
	print("Stairs: Body entered: ", body, " is_player: ", body.is_in_group("player") if body else false, " is_dead: ", body.is_dead if body and "is_dead" in body else false)
	if body and body.is_in_group("player") and not body.is_dead:
		print("Stairs: Player entered stairs! Player: ", body.name)
		
		# Play stairs sound effect
		if sfx_stairs and sfx_stairs.stream:
			sfx_stairs.play()
		
		var game_world = get_tree().get_first_node_in_group("game_world")
		if not game_world:
			print("Stairs: ERROR - Game world not found!")
			return
		if multiplayer.is_server() or not multiplayer.has_multiplayer_peer():
			print("Stairs: Server detected, calling _on_player_reached_stairs")
			game_world._on_player_reached_stairs(body)
		else:
			# Client: notify server so level complete triggers (host may not detect joiner via sync)
			var peer_id = body.get_multiplayer_authority() if body.has_method("get_multiplayer_authority") else 0
			if peer_id > 0 and game_world.has_method("_request_player_reached_stairs"):
				print("Stairs: Client notifying server that player ", body.name, " (peer ", peer_id, ") reached stairs")
				game_world._request_player_reached_stairs.rpc_id(1, peer_id)
