extends Node2D

@onready var area = $ClickArea
@onready var arrow = $Arrow

var respawn_timer: Timer
var original_y: float = 0.0

func _ready():
	original_y = position.y  
	area.input_event.connect(_on_area_input_event)
	area.mouse_entered.connect(_on_mouse_entered)
	area.mouse_exited.connect(_on_mouse_exited)

	# Create the respawn timer
	respawn_timer = Timer.new()
	respawn_timer.one_shot = true
	respawn_timer.timeout.connect(_on_respawn_timer_timeout)
	add_child(respawn_timer)

func _on_area_input_event(_viewport, event, _shape_idx):
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_LEFT and event.pressed:
			on_clicked()

func _on_mouse_entered():
	Input.set_default_cursor_shape(Input.CURSOR_POINTING_HAND)

func _on_mouse_exited():
	Input.set_default_cursor_shape(Input.CURSOR_ARROW)

func on_clicked():
	Audio.play_chop_sound()
	Inventory.add_wood(Unlocks.get_wood_per_click())
	play_pop_animation()

func play_pop_animation():
	arrow.visible = false
	
	# Create a tween for smooth animation
	var tween = create_tween()
	tween.set_parallel(true) # Run animations simultaneously

	# Scale up quickly (pop effect)
	tween.tween_property(self, "scale", scale * 1.3, 0.1).set_ease(Tween.EASE_OUT)

	# Fade out
	tween.tween_property(self, "modulate:a", 0.0, 0.2)

	# Optional: slight upward movement for extra effect
	tween.tween_property(self, "position:y", position.y - 3, 0.2)

	# Hide and disable, then start respawn timer
	tween.finished.connect(func():
		visible = false
		area.monitoring = false
		area.monitorable = false

		# Start the respawn timer with the value from Unlocks
		var respawn_time = Unlocks.get_wood_respawn_time()
		respawn_timer.start(respawn_time)
	)

func _on_respawn_timer_timeout():
	pop_back_in()

func pop_back_in():
	if visible:
		return # Already visible

	position.y = original_y

	# Reset properties
	visible = true
	arrow.visible = true
	area.monitoring = true
	area.monitorable = true

	# Create a tween for the pop-in animation
	var tween = create_tween()
	tween.set_parallel(true)

	# Start from scaled down and transparent
	scale = Vector2.ONE * 0.7
	modulate.a = 0.0

	# Scale up to normal
	tween.tween_property(self, "scale", Vector2.ONE, 0.2).set_ease(Tween.EASE_OUT)

	# Fade in
	tween.tween_property(self, "modulate:a", 1.0, 0.2)
