extends Node2D
class_name Planet

@onready var area = $Area2D

var sprite: Sprite2D

# Dane orbitalne
var orbit_center: Vector2 = Vector2.ZERO
var orbit_radius: float = 0.0
var rotation_speed: float = 0.02
var angle: float = 0.0

# Dane planety (przypisywane z Managera)
var data: Dictionary = {}

# Rysowanie obwódki kolonizacji
var show_outline := false

signal show_stats(planet)
signal hide_stats()

func _ready():
	_ensure_sprite()
	
	# Jeśli zapisano pozycję i kąt w danych, użyj ich
	if data.has("angle"):
		angle = data["angle"]
	else:
		angle = randf() * TAU

	if area:
		area.mouse_entered.connect(_on_mouse_entered)
		area.mouse_exited.connect(_on_mouse_exited)
		area.input_event.connect(_on_area_input)

func _ensure_sprite():
	if sprite == null:
		sprite = Sprite2D.new()
		add_child(sprite)
		sprite.centered = true

func _process(delta):
	# Ruch orbitalny
	angle += rotation_speed * delta
	if orbit_center != Vector2.ZERO and orbit_radius > 0.0:
		position = orbit_center + Vector2(cos(angle), sin(angle)) * orbit_radius
		if data != null:
			data["angle"] = angle

	# Obwódka kolonizacji
	if data != null:
		show_outline = data.get("is_colonized", false)
		queue_redraw()  # <-- Godot 4 sposób na wymuszenie _draw()

func _draw():
	if show_outline and sprite != null and sprite.texture != null:
		var radius = max(sprite.texture.get_size().x, sprite.texture.get_size().y) * 0.35 * sprite.scale.x
		var color = Color(0.717, 0.647, 0.234, 1.0)
		var width = 2  # grubość obwódki
		var start_angle = 0
		var end_angle = TAU  # pełny okrąg
		var point_count = 64  # ile punktów w łuku, im więcej tym gładsza obwódka
		draw_arc(Vector2.ZERO, radius, start_angle, end_angle, point_count, color, width)



func set_texture(tex: Texture2D):
	_ensure_sprite()
	sprite.texture = tex
	if data != null and data.has("size"):
		sprite.scale = get_scale_for_size(data["size"])

func get_scale_for_size(size: int) -> Vector2:
	match size:
		1: return Vector2(0.10, 0.10)
		2: return Vector2(0.15, 0.15)
		3: return Vector2(0.20, 0.20)
		4: return Vector2(0.25, 0.25)
	return Vector2(0.3, 0.3)

func _on_area_input(viewport, event, shape_idx):
	if event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
		colonize()

func colonize():
	if data != null and not data["is_colonized"]:
		data["is_colonized"] = true
		data["population"] = 10
		print(data["name"] + " has been colonized!")
		emit_signal("show_stats", self)

func _on_mouse_entered():
	if sprite != null and data != null:
		sprite.scale = get_scale_for_size(data["size"]) * 1.15
	emit_signal("show_stats", self)

func _on_mouse_exited():
	if sprite != null and data != null:
		sprite.scale = get_scale_for_size(data["size"])
	emit_signal("hide_stats")
