extends Control

@export var SectorScenePath: String = "res://scenes/sector.tscn"
@onready var container = $VBoxContainer

func _ready():
	_init_background()
	_create_sector_buttons()

# --- TWORZENIE GWIAZD SEKTORÓW ---
const GLOBAL_STAR_REDUCTION = 0.45 # Zmniejsza gwiazdy do 65% oryginalnego rozmiaru
const FONT_PATH := "res://assets/fonts/font3.ttf"
func _create_sector_buttons():
	for child in container.get_children():
		child.queue_free()

	var font = load(FONT_PATH)
	
	for i in range(Manager.SECTOR_COUNT):
		var sector_info = Manager.get_sector(i)
		
		var button = TextureButton.new()
		button.texture_normal = load(sector_info["star"]["texture_path"])
		button.stretch_mode = TextureButton.STRETCH_KEEP_ASPECT_CENTERED
		
		# Skala gwiazdy
		var star_scale = sector_info["star"]["scale"] * GLOBAL_STAR_REDUCTION
		button.scale = Vector2(star_scale, star_scale)
		button.position = sector_info["position"]
		print(button.scale)
		# --- Podpis sektora ---
		var label = Label.new()
		label.text = sector_info["name"]
		label.add_theme_font_override("font", font)
		label.scale = Vector2(1 / star_scale, 1 / star_scale)
		# Ustawienie grubości konturu
		label.add_theme_constant_override("outline_size", 2) # Grubość konturu 2px

# Ustawienie koloru konturu
		label.add_theme_color_override("font_outline_color", Color.BLACK)

		label.add_theme_font_size_override("font_size", 11)
		label.modulate = Color(0.887, 0.867, 0.836, 1.0)
		label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
		label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
		
		# umieszczamy labelkę POD gwiazdą (np. 60 px niżej)
		var button_width = button.size.x
		var button_height = button.size.y

# ... reszta kodu do centrowania i pozycjonowania

		label.position = Vector2(
			button_width / 2 - label.get_rect().size.x / 2, # Centrujemy względem X
			button_height + 60 # 60 jednostek poniżej dolnej krawędzi przycisku
		)
		
		button.add_child(label)
		
		var index = i
		button.pressed.connect(func(): _on_sector_selected(index))
		
		container.add_child(button)

# --- WYBRANIE SEKTORA ---
func _on_sector_selected(index: int):
	Manager.current_sector = index
	var sector_scene = load(SectorScenePath)
	get_tree().change_scene_to_packed(sector_scene)

# --- TŁO ---
func _init_background():
	var background = Sprite2D.new()
	background.texture = load(Settings.GALAXY_BACKGROUND)
	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
