class_name MaskDrop extends Node2D

@export var mask_type : MaskData
@export var time_to_live = 14
@export var initial_blink_speed: float = 0.7

@onready var popup := $Popup
@onready var sprite := $Sprite2D
@onready var blink_timer = $Timer

var alive_time = 0
var target_position : Vector2

func _ready() -> void:
	blink_timer.wait_time = initial_blink_speed
	blink_timer.timeout.connect(_on_timeout)
	blink_timer.start()
	blink_timer.paused = true
	sprite.rotate(randf() * PI - (PI / 2))
	sprite.rotate(randf() * PI - (PI / 2))

func _process(delta: float) -> void:
	alive_time += delta
	sprite.texture = mask_type.drop_texture

	var progress = alive_time / time_to_live
	if progress > 0.5:
		blink_timer.paused = false
	blink_timer.wait_time = lerp(initial_blink_speed, 0.02, progress)
	
	if alive_time >= time_to_live:
		queue_free()

func show_popup():
	var tween = create_tween()
	tween.tween_property(popup, "modulate:a", 1, 0.2)
	tween.parallel().tween_property(popup, "position:y", -23, 0.2)

func hide_popup():
	var tween = create_tween()
	tween.tween_property(popup, "modulate:a", 0, 0.2)
	tween.parallel().tween_property(popup, "position:y", -16, 0.2)

func collect(target : Vector2):
	target_position = target
	var tween = create_tween()
	tween.set_trans(Tween.TRANS_EXPO)

	tween.tween_method(_lerp_to_target, 0.0, 1.0, 0.3)
	
func _lerp_to_target(progression:float):
	global_position = lerp(global_position, target_position, progression)
	
	if global_position.distance_to(target_position)<=10.0:
		queue_free()

func _on_timeout():
	
	visible = !visible
