extends Node2D

var StarScene = preload("res://scenes/star.tscn")
var PlanetScene = preload("res://scenes/planet.tscn")
@onready var PlanetStatPanel = $PlanetStatPanel
@onready var BackButton: TextureButton = $BackButton


var tracked_planet: Node = null

func _ready():
	randomize()
	_init_background()
	spawn_star()
	spawn_planets()
	BackButton.pressed.connect(_on_back_pressed)
	var screen_center = get_viewport_rect().size / 2
	var offset = 20
	var button_size = BackButton.get_size()  # Vector2(width, height)
	BackButton.position = get_viewport_rect().size - button_size - Vector2(offset, offset)
	PlanetStatPanel.scale = Vector2(0.5, 0.5)

	
	
	

func _process(delta):
	if tracked_planet and PlanetStatPanel.visible:
		_update_panel()


func _on_back_pressed():
	get_tree().change_scene_to_file("res://scenes/galaxy.tscn")

# --- Planet spawning ---
const GLOBAL_OBJECT_SCALE = 0.75
func spawn_planets():
	var center = get_viewport_rect().size / 2
	var sector_index = Manager.current_sector

	if sector_index < 0:
		push_error("Current sector is not set!")
		return

	# przygotuj sektor jeśli jeszcze nie istnieje
	if Manager.sectors_data.size() <= sector_index:
		Manager.sectors_data.resize(sector_index + 1)
	if Manager.sectors_data[sector_index] == null:
		Manager.sectors_data[sector_index] = {"planets": [], "star": {}}
	elif not Manager.sectors_data[sector_index].has("planets"):
		Manager.sectors_data[sector_index]["planets"] = []

	var sector_planets = Manager.sectors_data[sector_index]["planets"]

	for i in range(sector_planets.size()):
		var planet_data = sector_planets[i]
		var planet_node = PlanetScene.instantiate()
		add_child(planet_node)
		
		planet_node.data = planet_data
		planet_node.orbit_center = center
		if i == 0:
			planet_node.orbit_radius = planet_data.get("orbit_radius", Settings.FIRST_ORBIT_STEP * (i + 1))
		else:
			planet_node.orbit_radius = planet_data.get("orbit_radius", Settings.ORBIT_STEP * (i + 1))
			
		planet_node.angle = planet_data.get("angle", randf() * TAU)
		planet_node.rotation_speed = planet_data.get("rotation_speed", randf_range(0.00001, 1))

		# Tekstura
		if planet_data.has("texture_path"):
			planet_node.set_texture(load(planet_data["texture_path"]))
		else:
			var tex_path = "res://assets/planets/p%d.png" % randi_range(1,18)
			planet_node.set_texture(load(tex_path))
			planet_data["texture_path"] = tex_path

		planet_node.connect("show_stats", Callable(self, "_on_show_stats"))
		planet_node.connect("hide_stats", Callable(self, "_on_hide_stats"))

		# Zapis aktualnych parametrów do Managera
		planet_data["orbit_radius"] = planet_node.orbit_radius
		planet_data["angle"] = planet_node.angle
		planet_data["rotation_speed"] = planet_node.rotation_speed

# --- Star ---
func spawn_star():
	var sector_index = Manager.current_sector
	if sector_index < 0:
		push_error("Current sector is not set!")
		return

	if not Manager.sectors_data[sector_index].has("star"):
		Manager.sectors_data[sector_index]["star"] = {}

	var star_data = Manager.sectors_data[sector_index]["star"]

	var star = StarScene.instantiate()
	add_child(star)
	star.position = get_viewport_rect().size / 2
	star.scale *= GLOBAL_OBJECT_SCALE 
	# jeśli gwiazda ma zapisaną teksturę – użyj jej
	if star_data.has("texture_path"):
		star.set_texture(load(star_data["texture_path"]))
	else:
		var tex_path = random_star_texture_path()
		star.set_texture(load(tex_path))
		star_data["texture_path"] = tex_path
		Manager.sectors_data[sector_index]["star"] = star_data

func random_star_texture_path() -> String:
	var id = randi_range(1,8)
	return "res://assets/stars/s%d.png" % id

# --- Background ---
func _init_background():
	var background = Sprite2D.new()
	background.texture = load("res://assets/background/space1.jpg")
	background.centered = true
	background.position = get_viewport_rect().size / 2
	var screen_size = get_viewport_rect().size
	var tex_size = background.texture.get_size()
	var scale_factor = max(screen_size.x / tex_size.x, screen_size.y / tex_size.y)
	background.scale = Vector2(scale_factor, scale_factor)
	add_child(background)
	background.z_index = -10

# --- GUI ---
func _on_show_stats(planet):
	tracked_planet = planet
	PlanetStatPanel.visible = true
	_update_panel()

func _on_hide_stats():
	tracked_planet = null
	PlanetStatPanel.visible = false

func _update_panel():
	if tracked_planet == null or tracked_planet.data == null:
		return
	var colonized_text = " (Skolonizowana)" if tracked_planet.data["is_colonized"] else ""
	PlanetStatPanel.get_node("PlanetName").text = "Nazwa: " + tracked_planet.data["name"] + colonized_text
	PlanetStatPanel.get_node("PopulationPanel").text = "Populacja: %d / %d" % [tracked_planet.data["population"], tracked_planet.data["max_population"]]
	PlanetStatPanel.get_node("MiningRate").text = "Potencjał surowcowy: %.2f" % tracked_planet.data["mining_rate"]
	var mined_per_cycle = Manager.get_mined_per_cycle(tracked_planet.data)
	PlanetStatPanel.get_node("ResourcePlanet").text = "Surowce: %.2f (+%.2f)" % [tracked_planet.data["resources"], mined_per_cycle]
	PlanetStatPanel.get_node("GrowthRate").text = "Biosfera: %.2f" % tracked_planet.data["growth_rate"]
