extends StaticBody3D

@export var stats_resource: PortalStats
@export var is_red: bool = false

@onready var mesh: MeshInstance3D = $Mesh
@onready var name_label: Label3D = $NameLabel
@onready var enter_area: Area3D = $EnterArea

var triggered: bool = false

func _enter_tree() -> void:
  set_multiplayer_authority(1)

func _ready() -> void:
  add_to_group("portals")
  if is_red:
    add_to_group("red_portal")
  if stats_resource == null:
    stats_resource = PortalStats.new()
    stats_resource.max_health = 1.0
    stats_resource.is_red = is_red
  Stats.register(self, stats_resource)
  enter_area.body_entered.connect(_on_body_entered)
  if is_red:
    var mat: StandardMaterial3D = StandardMaterial3D.new()
    mat.albedo_color = Color(0.95, 0.2, 0.2)
    mat.emission_enabled = true
    mat.emission = Color(1.0, 0.4, 0.3)
    mat.emission_energy_multiplier = 1.5
    mesh.material_override = mat
    name_label.text = "Red Portal"
  else:
    name_label.text = "Portal"

func _exit_tree() -> void:
  Stats.deregister(self)

func _on_body_entered(body: Node) -> void:
  if not body.is_in_group("player"):
    return
  if not body.is_multiplayer_authority():
    return
  if triggered:
    return
  triggered = true
  EventBus.portal_entered.emit(self, body)
  _request_enter.rpc_id(1, is_red, global_position)

@rpc("any_peer", "reliable", "call_local")
func _request_enter(red: bool, return_pos: Vector3) -> void:
  if not multiplayer.is_server() and multiplayer.multiplayer_peer != null:
    return
  var seed: int = randi()
  _do_enter.rpc(seed, red, return_pos)

@rpc("authority", "reliable", "call_local")
func _do_enter(seed: int, red: bool, return_pos: Vector3) -> void:
  GameState.dungeon_seed = seed
  GameState.dungeon_red = red
  GameState.portal_return_position = return_pos
  GameState.change_scene(GameState.SCENE_DUNGEON)
