extends Node3D
## Station Controller - Manages the space station environment

@onready var player: VoidPlayer = $Player
@onready var lighting: Node3D = $Lighting
@onready var interactables: Node3D = $Interactables

var emergency_lights: Array[OmniLight3D] = []
var emergency_light_timer: float = 0.0

func _ready() -> void:
	# Collect emergency lights
	for child in lighting.get_children():
		if child is OmniLight3D and "Emergency" in child.name:
			emergency_lights.append(child)
	
	# Connect game state signals
	GameState.power_restored.connect(_on_power_restored)
	
	# Set up procedural elements
	_spawn_interactables()
	
	# Initialize atmosphere
	_setup_atmosphere()

func _process(delta: float) -> void:
	# Emergency light flicker
	emergency_light_timer += delta
	if emergency_light_timer > 0.5:
		emergency_light_timer = 0.0
		_flicker_emergency_lights()

func _flicker_emergency_lights() -> void:
	for light in emergency_lights:
		if randf() > 0.7:
			var original = light.light_energy
			light.light_energy = 0.0
			await get_tree().create_timer(randf_range(0.05, 0.15)).timeout
			light.light_energy = original

func _spawn_interactables() -> void:
	# Spawn crew logs
	_spawn_log(Vector3(5, 1, -8), "log_001", "Commander's Log - Day 1", 
		"Station Erebus is now fully operational. The crew is in good spirits. We've begun our research into the anomaly detected in sector 7...")
	
	_spawn_log(Vector3(-8, 1, 3), "log_002", "Engineer's Notes", 
		"The power fluctuations are getting worse. I've rerouted auxiliary power but something is draining the main reactor...")
	
	_spawn_log(Vector3(12, 1, 12), "log_003", "Dr. Chen's Research Notes", 
		"The samples we collected from the anomaly... they're not behaving like normal matter. They seem to react to human presence...")
	
	# Spawn keycards
	_spawn_keycard(Vector3(-5, 1, -12), "keycard_red", Color.RED)
	_spawn_keycard(Vector3(15, 1, 8), "keycard_blue", Color.BLUE)
	
	# Spawn power switches
	_spawn_power_switch(Vector3(20, 1.5, 0), "power_section_a", "Section A")
	_spawn_power_switch(Vector3(-20, 1.5, 10), "power_section_b", "Section B")
	_spawn_power_switch(Vector3(0, 1.5, 20), "power_section_c", "Section C")

func _spawn_log(pos: Vector3, log_id: String, title: String, content: String) -> void:
	var log_obj = _create_interactable_base(pos, Color(0.2, 0.4, 0.8))
	log_obj.name = "Log_" + log_id
	log_obj.set_meta("log_id", log_id)
	log_obj.set_meta("title", title)
	log_obj.set_meta("content", content)
	log_obj.set_meta("type", "log")
	
	# Add glow
	var light = OmniLight3D.new()
	light.light_color = Color(0.2, 0.4, 1.0)
	light.light_energy = 0.5
	light.omni_range = 2.0
	log_obj.add_child(light)
	
	interactables.add_child(log_obj)

func _spawn_keycard(pos: Vector3, item_id: String, color: Color) -> void:
	var card = _create_interactable_base(pos, color)
	card.name = "Keycard_" + item_id
	card.set_meta("item_id", item_id)
	card.set_meta("type", "keycard")
	card.scale = Vector3(0.3, 0.05, 0.2)
	
	interactables.add_child(card)

func _spawn_power_switch(pos: Vector3, flag_id: String, label: String) -> void:
	var switch_obj = _create_interactable_base(pos, Color(0.8, 0.2, 0.2))
	switch_obj.name = "Switch_" + flag_id
	switch_obj.set_meta("flag_id", flag_id)
	switch_obj.set_meta("label", label)
	switch_obj.set_meta("type", "switch")
	switch_obj.set_meta("activated", false)
	switch_obj.scale = Vector3(0.3, 0.5, 0.1)
	
	interactables.add_child(switch_obj)

func _create_interactable_base(pos: Vector3, color: Color) -> StaticBody3D:
	var body = StaticBody3D.new()
	body.position = pos
	body.collision_layer = 4
	body.add_to_group("interactable")
	
	var shape = CollisionShape3D.new()
	var box = BoxShape3D.new()
	box.size = Vector3(0.5, 0.5, 0.5)
	shape.shape = box
	body.add_child(shape)
	
	var mesh_instance = MeshInstance3D.new()
	var mesh = BoxMesh.new()
	mesh.size = Vector3(0.5, 0.5, 0.5)
	var material = StandardMaterial3D.new()
	material.albedo_color = color
	material.emission_enabled = true
	material.emission = color * 0.3
	material.emission_energy_multiplier = 0.5
	mesh.material = material
	mesh_instance.mesh = mesh
	body.add_child(mesh_instance)
	
	# Add interact method via script
	var script = GDScript.new()
	script.source_code = """
extends StaticBody3D

func interact(player):
	var obj_type = get_meta("type", "")
	match obj_type:
		"log":
			player.read_log(get_meta("log_id"), get_meta("content"))
			# Visual feedback
			var tween = create_tween()
			tween.tween_property(self, "scale", scale * 1.2, 0.1)
			tween.tween_property(self, "scale", scale, 0.1)
		"keycard":
			player.collect_item(get_meta("item_id"))
			queue_free()
		"switch":
			if not get_meta("activated"):
				set_meta("activated", true)
				GameState.set_flag(get_meta("flag_id"), true)
				# Turn green
				$MeshInstance3D.mesh.material.albedo_color = Color.GREEN
				$MeshInstance3D.mesh.material.emission = Color.GREEN * 0.5
"""
	body.set_script(script)
	
	return body

func _on_power_restored(section: String) -> void:
	# Add lights for restored section
	print("Power restored to: ", section)

func _setup_atmosphere() -> void:
	# Add ambient sounds, particles, etc.
	pass

func _input(event: InputEvent) -> void:
	if event.is_action_pressed("pause"):
		if Input.mouse_mode == Input.MOUSE_MODE_CAPTURED:
			Input.mouse_mode = Input.MOUSE_MODE_VISIBLE
		else:
			Input.mouse_mode = Input.MOUSE_MODE_CAPTURED
