extends Node2D
class_name Planet
@onready var label = $Label

@onready var info_label = $CanvasLayer/Info
@onready var area = $Area2D
# --- Timery ---
var pop_timer: float = 0.0
var res_timer: float = 0.0
var cons_timer: float = 0.0
var since_pop: float = 0.0

var pname: String = ""
var orbit_radius: float = 30.0
var orbit_speed: float = 0.01
var biosfere: float = 0.1
var is_colonized = false
var size = 1
var max_pop = 1
var population: int = 0
var res_rich: float = 0.0
var since_doc: float = 0.0
var since_potential: float = 0.5
var resources := {}
var buildings := []
var bonuses = {
	"total_pop_bonus": 0,   # w %
	"biosfere": 0.0,        # mnożnik bazowy
}
 # słownik z ID -> stan budynku


var texture: Texture2D
var angle = randf() * TAU
func _ready():
	
	add_to_group("planets")

	# Podłącz sygnały
	area.mouse_entered.connect(_on_mouse_entered)
	area.mouse_exited.connect(_on_mouse_exited)
	area.connect("input_event", Callable(self, "_on_area_input"))
	  #str(round(biosfere * 100) / 100.0)
	_update_position()
	
	# Testowanie funkcji
	
	
	#print("Lista budynków na planecie:", buildings)
	#var data = BuildingsList.BUILDINGS["iron_mine"]
	#print(data.name, data.cost)


func _process(delta):
	angle += orbit_speed * delta   # obrót w czasie
	angle = fmod(angle, TAU)      # utrzymanie kąta w 0..2π
	_update_position()
	if is_colonized:
		_pop_growth(delta)
		_res_growth(delta)
		_since_growth(delta)
		_res_consumption(delta)
		print_data()
	label.text = str(pname)
	update_buildings(delta)

func _update_position():
	# pozycja lokalna względem gwiazdy
	position = Vector2(cos(angle), sin(angle)) * orbit_radius
	
	
func _on_mouse_entered():
	info_label.visible = true
	print_data()

	

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


func _on_mouse_exited():
	info_label.visible = false
func _on_mouse_click():
	if not is_colonized:
		colonize()
	else:
		var panel = get_tree().root.get_node("Galaxy/UI/PlanetPanel")
		panel.show_for_planet(self)

	
func colonize():
	if is_colonized == false:
		is_colonized = true
		label.add_theme_color_override("font_color", Color(0.0, 0.454, 0.0, 1.0))
		
		#add_building("iron_mine")
		#add_building("water_purifier")
		#add_building("terraforming_center") 
		#add_building("aluminium_ore_mine") 
		population = 100
		print_data()
	
func print_data():
	check_max_pop()
	var text = "🌍 %s\n" % pname
	text += "Biosfera: %.2f\n" % biosfere 
	text += "Zasobność surowców: %.2f\n" % res_rich
	text += "Limit populacji: %s\n" % GameData.format_number(max_pop)


	text += "Populacja: " + str(int(population)).pad_decimals(0) + "\n"
	text += "Status: " + ("Skolonizowana" if is_colonized else "Nieskolonizowana") + "\n"
	var has_any_resource = false
	for key in resources.keys():
		var res = resources[key]
		if res.has("exist") and res["exist"]:
			if not has_any_resource:
				text += "Zasoby:\n"
				has_any_resource = true

			var display_name = tr(key)  
			text += "%s: %.2f +(%s)\n" % [display_name, round(res.get("amount", 0) * 100) / 100.0, check_growth()]
	# --- Budynki ---
	if buildings.size() > 0:
		text += "Budynki na planecie:\n"
		for b in buildings:
			var data = BuildingsList.BUILDINGS[b.id]
			var status = tr("Under construction") if b.is_building else tr("ready")
			text += "- %s [%s]\n" % [tr(data.name), status]

	info_label.text = text

func check_max_pop():
	max_pop = min(1.0, biosfere + bonuses["biosfere"]) * 10000000 * (1.0 + bonuses["total_pop_bonus"] / 100.0)


	return max_pop
	
func _pop_growth(delta):
	pop_timer += delta
	max_pop = check_max_pop()
	if pop_timer >= Settings.UPDATE_INTERVAL:
		if resources["water"]["amount"] > 0:
			var growth = int(max(1, population * 0.05 * (biosfere + bonuses["biosfere"])))
			population = min(population + growth, max_pop)
			pop_timer = 0.0
		else:
			population = max(population - 1000, 100)
			pop_timer = 0.0
func _since_growth(delta):
	since_pop += delta
	if since_pop >= Settings.UPDATE_INTERVAL:
		if has_building("laboratory"):
			since_doc += since_potential * log(1 + population * 0.00001)
		since_pop = 0
		

func has_building(building_id: String) -> bool:
	for b in buildings:
		if typeof(b) == TYPE_DICTIONARY:
			if b.get("id", "") == building_id:
				return true
		# jeśli trzymasz budynki jako stringi (rzadziej), obsłuż to też:
		elif typeof(b) == TYPE_STRING and b == building_id:
			return true
	return false
		
func _res_growth(delta):
	res_timer += delta
	if res_timer < Settings.UPDATE_INTERVAL:
		return
	res_timer = 0.0
	
	for res_name in resources.keys():
		var res = resources[res_name]
		
		if res.exist:
			# Sprawdź, czy planeta ma budynek wydobywający ten surowiec
			var can_produce = false
			for b in buildings:
				if not b.is_building:  # tylko ukończone budynki
					var building_data = BuildingsList.BUILDINGS[b.id]
					if building_data.resource == res_name:
						can_produce = true
						break
			
			if can_produce:
				var growth = check_growth()  # np. funkcja zwraca ile przyrasta
				res.amount += growth
				resources[res_name] = res


func check_growth() -> float:
	# Zwraca przyrost zaokrąglony do 2 miejsc po przecinku
	var growth = res_rich * log(1 + population / 500.0)


	return round(growth * 100) / 100.0
	
func _res_consumption(delta):
	
	var water_usage = population * 0.000001  # np. 0.002 jednostki wody na osobę
	cons_timer += delta
	if cons_timer >= Settings.UPDATE_INTERVAL:  
		if "water" in resources:
			resources["water"].amount -= water_usage
			if resources["water"].amount < 0:
				resources["water"].amount = 0
		cons_timer = 0.0
		
func add_building(building_id: String):
	# Sprawdzenie czy istnieje w definicjach
	if not BuildingsList.BUILDINGS.has(building_id):
		print("Nie ma takiego budynku:", building_id)
		return

	# Sprawdzenie czy planeta już ma ten budynek
	for b in buildings:
		if b.id == building_id:
			print("Planeta już ma budynek:", building_id)
			return

	# Dodajemy budynek w budowie
	buildings.append({
		"id": building_id,
		"level": 1,
		"is_building": true,
		"built_time": 0.0
	})
	print("Rozpoczęto budowę budynku:", BuildingsList.BUILDINGS[building_id].name)
	
func update_buildings(delta: float):
	for b in buildings:
		if b.is_building:
			var build_time = BuildingsList.BUILDINGS[b.id].build_time
			b.built_time += delta
			if b.built_time >= build_time:
				b.is_building = false
				print("Budowa ukończona:", BuildingsList.BUILDINGS[b.id].name)

				# Pobierz dane zakończonego budynku
				var building_data = BuildingsList.BUILDINGS[b.id]

				# Jeśli budynek ma sekcję "bonuses", zastosuj je
				if "bonuses" in building_data:
					_apply_building_bonuses(building_data["bonuses"])

# Uniwersalna funkcja stosowania bonusów
func _apply_building_bonuses(bonus_dict: Dictionary) -> void:
	for key in bonus_dict.keys():
		var value = bonus_dict[key]

		# Jeśli taki bonus już istnieje – dodaj wartość
		if key in bonuses:
			bonuses[key] += value
		# Jeśli nie istnieje – dodaj nowy klucz do słownika bonuses
		else:
			bonuses[key] = value
		
		if (biosfere + bonuses["biosfere"] > 0.7):
			print("zmieniam texture")
			$Sprite2D.texture = load("res://assets/planets/p%d.png" % randi_range(1,9))

	print("Zastosowano bonusy:", bonus_dict)
