## DeliveryBed — tap to animate mama arriving and baby appearing; tap again to reset.
class_name DeliveryBed extends Node2D

enum State { IDLE, MAMA_ARRIVING, COMPLETE, RESETTING }

const MAMA_OFFSCREEN_X: float = -600.0
const MAMA_PARKED_X: float = -100.0
const ARRIVE_DURATION: float = 1.0
const BABY_FADE_DURATION: float = 0.6
const RESET_DURATION: float = 0.8
const BUTTON_HALF_WIDTH: float = 120.0
const BUTTON_HALF_HEIGHT: float = 40.0

var _state: State = State.IDLE


func _ready() -> void:
	var mama: Node2D = get_node_or_null("Mama") as Node2D
	if mama != null:
		mama.position.x = MAMA_OFFSCREEN_X
	var baby: Node2D = get_node_or_null("Baby") as Node2D
	if baby != null:
		baby.modulate.a = 0.0


func _input(event: InputEvent) -> void:
	if _state == State.MAMA_ARRIVING or _state == State.RESETTING:
		return
	var screen_pos: Vector2
	if event is InputEventScreenTouch and event.pressed:
		screen_pos = event.position
	elif event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
		screen_pos = event.position
	else:
		return
	var canvas_transform: Transform2D = get_viewport().get_canvas_transform()
	var world_pos: Vector2 = canvas_transform.affine_inverse() * screen_pos
	var local_pos: Vector2 = to_local(world_pos)
	if abs(local_pos.x) <= BUTTON_HALF_WIDTH and abs(local_pos.y) <= BUTTON_HALF_HEIGHT:
		if _state == State.IDLE:
			_start_arrival()
		elif _state == State.COMPLETE:
			_start_reset()


func _start_arrival() -> void:
	AudioManager.play_sfx("delivery_cheer")
	_state = State.MAMA_ARRIVING
	var mama: Node2D = get_node_or_null("Mama") as Node2D
	if mama == null:
		_state = State.IDLE
		return
	var tween: Tween = create_tween()
	tween.set_ease(Tween.EASE_OUT)
	tween.set_trans(Tween.TRANS_QUAD)
	tween.tween_property(mama, "position:x", MAMA_PARKED_X, ARRIVE_DURATION)
	tween.finished.connect(_on_mama_arrived)


func _on_mama_arrived() -> void:
	_state = State.COMPLETE
	var baby: Node2D = get_node_or_null("Baby") as Node2D
	if baby == null:
		return
	var tween: Tween = create_tween()
	tween.tween_property(baby, "modulate:a", 1.0, BABY_FADE_DURATION)


func _start_reset() -> void:
	_state = State.RESETTING
	var baby: Node2D = get_node_or_null("Baby") as Node2D
	if baby != null:
		var fade_tween: Tween = create_tween()
		fade_tween.tween_property(baby, "modulate:a", 0.0, BABY_FADE_DURATION)
	var mama: Node2D = get_node_or_null("Mama") as Node2D
	if mama == null:
		_state = State.IDLE
		return
	var slide_tween: Tween = create_tween()
	slide_tween.set_ease(Tween.EASE_IN)
	slide_tween.set_trans(Tween.TRANS_QUAD)
	slide_tween.tween_property(mama, "position:x", MAMA_OFFSCREEN_X, RESET_DURATION)
	slide_tween.finished.connect(func() -> void: _state = State.IDLE)
