## XRayMachine — X-ray plate slides out when tapped; viewer lights up during exposure.
class_name XRayMachine extends Node2D

enum State { IDLE, SLIDING_IN, EXPOSING, SLIDING_OUT }

const SLIDE_DURATION: float = 0.8
const EXPOSE_DURATION: float = 1.5
const BUTTON_HALF_WIDTH: float = 50.0
const BUTTON_HALF_HEIGHT: float = 100.0
const PLATE_PARKED_X: float = -50.0
const PLATE_ACTIVE_X: float = 130.0
const VIEWER_LIT_COLOR: Color = Color(0.75, 0.90, 1.0, 1)
const VIEWER_DARK_COLOR: Color = Color(0.06, 0.08, 0.12, 1)

var _state: State = State.IDLE


func _ready() -> void:
	var plate: Node2D = get_node_or_null("Plate") as Node2D
	if plate != null:
		plate.position.x = PLATE_PARKED_X


func _input(event: InputEvent) -> void:
	if _state != State.IDLE:
		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:
		_start_scan()


func _start_scan() -> void:
	AudioManager.play_sfx("xray_scan")
	_state = State.SLIDING_IN
	var plate: Node2D = get_node_or_null("Plate") as Node2D
	if plate == null:
		_state = State.IDLE
		return
	var tween: Tween = create_tween()
	tween.set_ease(Tween.EASE_IN_OUT)
	tween.set_trans(Tween.TRANS_QUAD)
	tween.tween_property(plate, "position:x", PLATE_ACTIVE_X, SLIDE_DURATION)
	tween.finished.connect(_on_plate_in)


func _on_plate_in() -> void:
	_state = State.EXPOSING
	var viewer: ColorRect = get_node_or_null("Viewer") as ColorRect
	if viewer != null:
		viewer.color = VIEWER_LIT_COLOR
	var timer: SceneTreeTimer = get_tree().create_timer(EXPOSE_DURATION)
	timer.timeout.connect(_start_slide_out)


func _start_slide_out() -> void:
	_state = State.SLIDING_OUT
	var viewer: ColorRect = get_node_or_null("Viewer") as ColorRect
	if viewer != null:
		viewer.color = VIEWER_DARK_COLOR
	var plate: Node2D = get_node_or_null("Plate") as Node2D
	if plate == null:
		_state = State.IDLE
		return
	var tween: Tween = create_tween()
	tween.set_ease(Tween.EASE_IN_OUT)
	tween.set_trans(Tween.TRANS_QUAD)
	tween.tween_property(plate, "position:x", PLATE_PARKED_X, SLIDE_DURATION)
	tween.finished.connect(func() -> void: _state = State.IDLE)
