extends StaticBody3D

@export var stats: PortalStats

func _ready() -> void:
  add_to_group("portals")
  if stats.variant == PortalStats.Kind.RED:
    add_to_group("red_portal")
  _apply_appearance()
  PortalData.register(self, stats)

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

func _process(delta: float) -> void:
  var mesh: Node3D = get_node_or_null("Mesh")
  if mesh:
    mesh.rotate_y(delta * 1.5)

func _apply_appearance() -> void:
  var mesh: MeshInstance3D = get_node_or_null("Mesh")
  if not mesh:
    return
  var mat := StandardMaterial3D.new()
  mat.emission_enabled = true
  mat.emission_energy_multiplier = 0.8
  if stats.variant == PortalStats.Kind.RED:
    mat.albedo_color = Color(0.9, 0.1, 0.1, 1)
    mat.emission = Color(1.0, 0.25, 0.25, 1)
  else:
    mat.albedo_color = Color(0.4, 0.2, 0.85, 1)
    mat.emission = Color(0.6, 0.35, 1.0, 1)
  mesh.material_override = mat

func _on_detection_area_body_entered(body: Node3D) -> void:
  if body is CharacterBody3D and body.name == "Player":
    EventBus.portal_entered.emit(self, body)
