extends GPUParticles3D

@onready var player: Node3D = get_node("%Player")
var last_player_position: Vector3
var update_distance: float = 1

func _ready():
	setup_floating_particles()

func _process(delta):
	if player:
		var current_player_pos = player.global_position

		var target_pos = Vector3(
			current_player_pos.x,
			1.0,
			current_player_pos.z
		)

		global_position = global_position.lerp(target_pos, delta * 3.0)

func setup_floating_particles():
	# Basic particle setup
	emitting = true
	amount = 100
	lifetime = 8.0
	visibility_aabb = AABB(Vector3(-20, 0, -20), Vector3(40, 10, 40))
	
	# Create material
	var material = ParticleProcessMaterial.new()
	
	# Emission
	material.emission_shape = ParticleProcessMaterial.EMISSION_SHAPE_BOX
	material.emission_box_extents = Vector3(5, 2, 5)
	
	# Movement
	material.direction = Vector3(0.1, 0.8, 0.1)
	material.initial_velocity_min = 0.2
	material.initial_velocity_max = 0.8
	material.gravity = Vector3(0, -0.3, 0)
	
	# Floating motion
	material.orbit_velocity_min = 0.1
	material.orbit_velocity_max = 0.3
	material.radial_velocity_min = -0.2
	material.radial_velocity_max = 0.2
	
	# Size and fade
	material.scale_min = 0.01
	material.scale_max = 0.03
	material.scale_over_velocity_min = 0.0
	material.scale_over_velocity_max = 2.0
	
	# Color (golden dust particles)
	var gradient = Gradient.new()
	gradient.add_point(0.0, Color(1.0, 0.9, 0.6, 0.0)) # Fade in
	gradient.add_point(0.2, Color(1.0, 0.9, 0.6, 0.5)) # Full opacity
	gradient.add_point(0.8, Color(1.0, 0.8, 0.4, 0.3)) # Slight color shift
	gradient.add_point(1.0, Color(1.0, 0.7, 0.3, 0.0)) # Fade out
	
	var gradient_texture = GradientTexture1D.new()
	gradient_texture.gradient = gradient
	material.color_ramp = gradient_texture
	
	# Assign the material to the particle system
	process_material = material
	
	# Create and assign visual mesh (small billboard)
	var quad_mesh = QuadMesh.new()
	quad_mesh.size = Vector2(0.01, 0.01)
	draw_pass_1 = quad_mesh
	
	# Create a basic material for the particles to be visible
	var particle_material = StandardMaterial3D.new()
	particle_material.albedo_color = ColorData.grass_materials[Season.current]['top']
	particle_material.flags_transparent = true
	particle_material.flags_unshaded = true
	particle_material.billboard_mode = BaseMaterial3D.BILLBOARD_ENABLED
	material_override = particle_material
