extends Panel

@onready var name_label = $Name_Label
@onready var info_label = $Info_Label
@onready var buildings_container = $Buildings
@onready var send_button = $SendButton

var dragging := false
var drag_offset := Vector2.ZERO

func _gui_input(event):
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_LEFT:
			if event.pressed:
				# Kliknięto na panel → zaczynamy drag
				dragging = true
				drag_offset = get_local_mouse_position()
			else:
				# Zwolniono przycisk → kończymy drag
				dragging = false
	elif event is InputEventMouseMotion and dragging:
		# Przesuwamy panel względem pozycji myszy
		position += event.relative

func _ready():
	send_button.connect("pressed", Callable(self, "_on_send_resources_pressed"))
	
	
var planet: Planet = null
func _process(delta: float) -> void:
	_update_info()
func show_for_planet(p: Planet):
	planet = p
	name_label.text = p.pname
	_update_info()
	_create_building_buttons()
	show()

func hide_panel():
	hide()
	planet = null

func _update_info():
	if not planet:
		return
	
	# Tekst informacji wzorowany na print_data z Planet.gd
	var text = "🌍 %s\n" % planet.pname
	text += "Biosfera: %.2f (+%.2f)\n" % [planet.biosfere, planet.bonuses.get("biosfere", 0.0)]

	text += "Zasobność surowców: %.2f\n" % planet.res_rich
	text += "Potencjał naukowy: %.2f\n" % planet.since_potential
	text += "Limit populacji: %s\n" % GameData.format_number(planet.max_pop)
	text += "Populacja: %d\n" % int(planet.population)
	text += "Status: %s\n" % ("Skolonizowana" if planet.is_colonized else "Nieskolonizowana")
	text += "Raporty naukowe: %.2f\n" % planet.since_doc
	# Surowce
	var has_any_resource = false
	for key in planet.resources.keys():
		var res = planet.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,
				planet.check_growth()
			]

	# Budynki
	if planet.buildings.size() > 0:
		text += "Budynki na planecie:\n"
		for b in planet.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 _create_building_buttons():
	# Usuń stare przyciski
	for child in buildings_container.get_children():
		child.queue_free()

	# Tworzymy nowe przyciski dla wszystkich budynków w definicjach
	for b_id in BuildingsList.BUILDINGS.keys():
		var b_data = BuildingsList.BUILDINGS[b_id]
		
		# Sprawdź, czy budynek wymaga technologii
		var required_tech = b_data.get("required_tech", null)
		print("Tech unlocked:", PlayerData.unlocked_techs)
		print("Building:", b_id, "requires:", required_tech)
		# Jeżeli nie wymaga lub gracz ma już tę technologię
		if not required_tech or required_tech in PlayerData.unlocked_techs:
			var btn = TextureButton.new()
			btn.texture_normal = load(b_data.texture)
			
			btn.connect("pressed", Callable(self, "_on_building_pressed").bind(b_id))
			buildings_container.add_child(btn)
			


func _on_building_pressed(b_id):
	if not planet:
		return
	
	var b_data = BuildingsList.BUILDINGS[b_id]
	
	# Sprawdź czy planeta ma wymagany surowiec
	if b_data.has("resource") and b_data["resource"] != null:
		var required_resource = b_data["resource"]
		if not planet.resources.has(required_resource):
			print("❌ Planeta nie ma zasobu: %s" % required_resource)
			return
		
		var res_info = planet.resources[required_resource]
		if not res_info.has("exist") or not res_info["exist"]:
			print("❌ Surowiec %s nie występuje na planecie!" % required_resource)
			return

	# Sprawdź koszt budynku (czy planeta ma odpowiednie zasoby)
	if b_data.has("cost"):
		for cost_res in b_data.cost.keys():
			var cost_val = b_data.cost[cost_res]
			if not planet.resources.has(cost_res) or planet.resources[cost_res].get("amount", 0) < cost_val:
				print("❌ Brak wystarczającej ilości surowca: %s (wymagane %s)" % [cost_res, cost_val])
				return

	# Odejmij koszt budowy z zasobów planety
	for cost_res in b_data.cost.keys():
		var cost_val = b_data.cost[cost_res]
		planet.resources[cost_res]["amount"] -= cost_val

	# Dodaj budynek
	planet.add_building(b_id)
	_update_info()
	print("✅ Zbudowano budynek: %s" % b_data.name)



func _on_button_pressed() -> void:
	hide_panel() 
#do usuniecia po testach	
func _on_send_resources_pressed():
	
	if not planet:
		return
	PlayerData.since_doc += planet.since_doc
	planet.since_doc = 0
	for res_name in planet.resources.keys():
		var res = planet.resources[res_name]
		if res.has("amount") and res["amount"] > 0:
			# Jeżeli gracz ma ten typ zasobu, dodaj
			if PlayerData.resources.has(res_name):
				PlayerData.resources[res_name] += res["amount"]
				res["amount"] = 0
				planet.resources[res_name] = res
				PlayerData.emit_signal("stats_changed")
# Emituj sygnał tylko raz, po zakończeniu pętli
	


	
