extends Node2D
## Демо-уровень 1: Волны и колебания.
## Задача: разместить источник колебаний так, чтобы волна достигла приёмника.

@onready var wave_source: WaveSource = $GameField/WaveSource
@onready var receiver: WaveReceiver = $GameField/Receiver
@onready var run_button: Button = $UILayer/BottomBar/RunButton
@onready var reset_button: Button = $UILayer/BottomBar/ResetButton
@onready var back_button: Button = $UILayer/TopBar/BackButton
@onready var win_panel: PanelContainer = $UILayer/WinPanel

var is_running: bool = false


func _ready() -> void:
	$UILayer/TopBar/LevelLabel.text = "Уровень %d" % GameManager.current_level
	$UILayer/TopBar/HintLabel.text = "Переместите источник ближе к приёмнику и нажмите Запуск"
	win_panel.visible = false

	run_button.pressed.connect(_on_run)
	reset_button.pressed.connect(_on_reset)
	back_button.pressed.connect(func(): GameManager.go_to_level_select())
	$UILayer/WinPanel/VBoxContainer/NextButton.pressed.connect(_on_next)
	$UILayer/WinPanel/VBoxContainer/MenuButton.pressed.connect(func(): GameManager.go_to_level_select())

	receiver.activated.connect(_on_receiver_activated)

	# Добавить в группы для обнаружения
	wave_source.add_to_group("wave_sources")
	receiver.add_to_group("receivers")


func _process(delta: float) -> void:
	if is_running and not receiver.is_activated:
		# Обновить амплитуду приёмника вручную (демо-версия)
		var dist := receiver.global_position.distance_to(wave_source.global_position)
		receiver.current_amplitude = wave_source.get_amplitude_at(dist)


func _on_run() -> void:
	if is_running:
		return
	is_running = true
	run_button.text = "▶ Работает..."
	run_button.disabled = true
	wave_source.is_fixed = true
	wave_source.activate()


func _on_reset() -> void:
	get_tree().reload_current_scene()


func _on_receiver_activated() -> void:
	_show_win()


func _show_win() -> void:
	win_panel.visible = true
	win_panel.modulate.a = 0.0
	var tween := create_tween()
	tween.tween_property(win_panel, "modulate:a", 1.0, 0.5)
	GameManager.complete_level(GameManager.current_level)


func _on_next() -> void:
	var next := GameManager.current_level + 1
	if next <= GameManager.total_levels:
		GameManager.go_to_level(next)
	else:
		GameManager.go_to_level_select()
