extends StaticBody3D

@export var target_scene: String = "res://scenes/dungeon/dungeon.tscn"
@export var is_exit: bool = false

var active := false
var dungeon_variant: int = 0

func _ready() -> void:
  if not is_exit:
    if PlayerData.dungeon_cleared:
      queue_free()
      return
    get_tree().create_timer(0.5).timeout.connect(_check_overlapping)
  else:
    get_tree().create_timer(1.0).timeout.connect(func() -> void: active = true)

func _check_overlapping() -> void:
  active = true
  for body in $GateArea.get_overlapping_bodies():
    _on_gate_area_body_entered(body)

func _on_gate_area_body_entered(body: Node3D) -> void:
  if not active:
    return
  if body is CharacterBody3D and body.name == "Player":
    PlayerData.save_cache()
    if is_exit:
      PlayerData.returning_from_dungeon = true
    else:
      PlayerData.portal_position = global_position
      GameState.last_dungeon_variant = dungeon_variant
    call_deferred("_change_scene")

func _change_scene() -> void:
  get_tree().change_scene_to_file(target_scene)
