extends Area2D

# A coin that rewards you for grabbing it: a sparkle burst, a rising pickup
# pitch as you chain coins, a floating "+1" popup, and a tiny screen nudge.

const PIXEL_FONT = preload("res://assets/fonts/PixelOperator8.ttf")
const COIN_COLOR = Color(1.0, 0.85, 0.25)

@onready var game_manager = %GameManager
@onready var animation_player = $AnimationPlayer
@onready var pickup_sound = $PickupSound


func _ready():
	# A lazy vertical bob gives the coins a bit of life even before you grab
	# them — static pickups read as dead; floating ones invite you over.
	var base_y := position.y
	var bob := create_tween().set_loops()
	bob.tween_property(self, "position:y", base_y - 2.0, 0.7) \
		.set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_IN_OUT)
	bob.tween_property(self, "position:y", base_y, 0.7) \
		.set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_IN_OUT)


func _on_body_entered(body):
	var combo = game_manager.add_point()

	# Each coin in a chain plays a little higher than the last (caps out so it
	# never gets shrill). That climbing pitch is most of the "feel good" here.
	pickup_sound.pitch_scale = 1.0 + min(combo - 1, 8) * 0.07

	# Sparkle + a small kick to the camera.
	Juice.spawn_burst(global_position, COIN_COLOR, 12, 95.0)
	if body.has_method("add_shake"):
		body.add_shake(0.4)

	_spawn_popup(combo)

	# The existing "pickup" animation hides the coin, plays the sound and frees it.
	animation_player.play("pickup")


# Floats a "+1" (or "+1 x3") up from the coin and fades it out.
func _spawn_popup(combo: int):
	var label := Label.new()
	label.text = "+1" if combo <= 1 else "+1  x%d" % combo
	label.add_theme_font_override("font", PIXEL_FONT)
	label.add_theme_font_size_override("font_size", 8)
	label.add_theme_color_override("font_color", COIN_COLOR)
	label.z_index = 30

	var scene := get_tree().current_scene
	if scene == null:
		return
	scene.add_child(label)
	label.global_position = global_position + Vector2(-6, -10)

	var tween := label.create_tween()
	tween.tween_property(label, "global_position", label.global_position + Vector2(0, -14), 0.6) \
		.set_trans(Tween.TRANS_QUAD).set_ease(Tween.EASE_OUT)
	tween.parallel().tween_property(label, "modulate:a", 0.0, 0.6)
	tween.tween_callback(label.queue_free)
