extends Node3D

@export var base_spin_speed := 0.05       # Slow ambient rotation
@export var beat_boost := 0.2             # How much faster it spins with bass
@export var smoothness := 0.05            # Controls smoothing of the beat signal
@export var music_bus := "MusicBus"       # Audio bus with the SpectrumAnalyzer

@onready var analyzer = AudioServer.get_bus_effect_instance(
	AudioServer.get_bus_index(music_bus), 0
)

# Reference to your mesh
@onready var mesh: MeshInstance3D = $Sketchfab_model/SphereTest_fbx/RootNode/pSphere1/pSphere1_lambert2_0

var smoothed_bass := 0.0
var mat: Material = null

func _ready() -> void:
	if mesh:
		# Duplicate the material so it’s safe to modify
		var original_mat = mesh.get_active_material(0)
		if original_mat:
			mat = original_mat.duplicate()
			mesh.set_surface_override_material(0, mat)
		else:
			push_warning("Mesh has no material!")
	else:
		push_error("Mesh path is incorrect!")

func _process(delta: float) -> void:
	if not analyzer:
		return

	# Measure low frequencies for the "beat"
	var bass = analyzer.get_magnitude_for_frequency_range(20, 200)
	var bass_strength = bass.length() * 5.0

	# Smooth out the data
	smoothed_bass = lerp(smoothed_bass, bass_strength, smoothness)

	# Determine final spin speed
	var spin_speed = base_spin_speed + smoothed_bass * beat_boost

	# Apply slow rotation around Y axis (typical for skyboxes)
	rotation.y += spin_speed * delta

	# Optionally, adjust shader/material color or parameter
	if mat and mat is StandardMaterial3D:
		var brightness = 0.6 + smoothed_bass * 0.3
		mat.albedo_color = Color(brightness, brightness, brightness)
	elif mat and mat is ShaderMaterial:
		mat.set_shader_parameter("intensity", 1.0 + smoothed_bass * 0.5)
