extends Control
## Main Menu for Circuit Logic

@onready var play_button: Button = $VBox/PlayButton
@onready var level_select_button: Button = $VBox/LevelSelectButton
@onready var quit_button: Button = $VBox/QuitButton
@onready var stars_label: Label = $VBox/StarsLabel
@onready var circuit_pattern: Control = $Background/CircuitPattern

func _ready() -> void:
	play_button.pressed.connect(_on_play)
	level_select_button.pressed.connect(_on_level_select)
	quit_button.pressed.connect(_on_quit)
	
	# Update stars display
	var total = ProgressManager.get_total_stars()
	var max_stars = ProgressManager.levels.size() * 3
	stars_label.text = "★ %d / %d" % [total, max_stars]
	
	# Draw decorative circuit pattern
	_draw_circuit_pattern()
	
	# Fade in
	modulate.a = 0.0
	var tween = create_tween()
	tween.tween_property(self, "modulate:a", 1.0, 0.5)

func _draw_circuit_pattern() -> void:
	# Create decorative background circuits
	var viewport = get_viewport_rect().size
	
	for i in 20:
		var line = ColorRect.new()
		line.color = Color(0.3, 0.8, 0.5, 0.1)
		
		if randf() > 0.5:
			# Horizontal line
			line.size = Vector2(randf_range(50, 200), 2)
			line.position = Vector2(randf() * viewport.x, randf() * viewport.y)
		else:
			# Vertical line
			line.size = Vector2(2, randf_range(50, 200))
			line.position = Vector2(randf() * viewport.x, randf() * viewport.y)
		
		circuit_pattern.add_child(line)
		
		# Add nodes at endpoints
		var node_size = 6
		var node = ColorRect.new()
		node.color = Color(0.3, 0.8, 0.5, 0.15)
		node.size = Vector2(node_size, node_size)
		node.position = line.position - Vector2(node_size/2, node_size/2)
		circuit_pattern.add_child(node)

func _on_play() -> void:
	# Find the first unlocked incomplete level, or first level
	var next_level = 1
	for level in ProgressManager.levels:
		if ProgressManager.is_level_unlocked(level.id) and not ProgressManager.completed_levels.has(level.id):
			next_level = level.id
			break
	
	_start_level(next_level)

func _on_level_select() -> void:
	get_tree().change_scene_to_file("res://scenes/level_select.tscn")

func _start_level(level_id: int) -> void:
	var tween = create_tween()
	tween.tween_property(self, "modulate:a", 0.0, 0.3)
	await tween.finished
	
	# Store level to load
	get_tree().set_meta("current_level", level_id)
	get_tree().change_scene_to_file("res://scenes/game.tscn")

func _on_quit() -> void:
	get_tree().quit()
