extends GunkNode

@export var jitter_scale_factor := 0.05
@export var jitter_inflation_factor := 1.0

@export var chitter: bool = false
@export var chitter_time_mean := 120.0
@export var chitter_time_st_dev := 30.0

@export var splatter_scene: PackedScene

@onready var mesh_instance: MeshInstance3D = %MeshInstance3D

@onready var chitter_sfx: AudioStreamPlayer3D = %ChitterSFX
@onready var chitter_timer: Timer = %ChitterTimer


func _ready() -> void:
	if chitter:
		start_chitter_timer()


func _process(delta: float) -> void:
	super._process(delta)
	var shader: ShaderMaterial = mesh_instance.mesh.surface_get_material(0)
	var damage := pct_damage()
	shader.set_shader_parameter("jitter_time_scale", pow(damage * jitter_scale_factor, 1.2))
	shader.set_shader_parameter("vertex_inflation", pow(damage * jitter_inflation_factor, 3))


func _destroy() -> void:
	var splatter: GPUParticles3D = splatter_scene.instantiate()
	add_sibling(splatter)
	splatter.global_position = global_position
	splatter.emitting = true


func start_chitter_timer() -> void:
	var interval := randfn(chitter_time_mean, chitter_time_st_dev)
	chitter_timer.start(interval)


func _on_chitter_timer_timeout() -> void:
	chitter_sfx.play()
	start_chitter_timer()
