# Shop.gd
extends Node2D

signal purchase_attempted(item_data: Dictionary, shop_item: Node)
signal next_round_requested

@onready var shop_item_scene = preload("res://scenes/ShopItem.tscn")


var shop_items = {
	"pieces": [
		{"name": "Pawn", "price": 1, "tier": "bronze", "texture": "res://assets/Resized Chess Piece Assets/White_Pawn.png", "purchased": false},
		{"name": "Rook", "price": 3, "tier": "silver", "texture": "res://assets/Resized Chess Piece Assets/White_Rook.png", "purchased": false},
		{"name": "Bishop", "price": 3, "tier": "silver", "texture": "res://assets/Resized Chess Piece Assets/White_Bishop.png", "purchased": false},
		{"name": "Knight", "price": 3, "tier": "silver", "texture": "res://assets/Resized Chess Piece Assets/White_Knight.png", "purchased": false},
		{"name": "Queen", "price": 5, "tier": "gold", "texture": "res://assets/Resized Chess Piece Assets/White_Queen.png", "purchased": false}
	],
	"upgrades": [
		{"name": "Upgrade 1", "price": 3, "tier": "bronze", "texture": "res://assets/Resized Chess Piece Assets/Black_Pawn.png", "purchased": false},
		{"name": "Upgrade 2", "price": 5, "tier": "silver", "texture": "res://assets/Resized Chess Piece Assets/Black_Rook.png", "purchased": false},
		{"name": "Upgrade 3", "price": 5, "tier": "silver", "texture": "res://assets/Resized Chess Piece Assets/Black_Bishop.png", "purchased": false},
		{"name": "Upgrade 4", "price": 5, "tier": "silver", "texture": "res://assets/Resized Chess Piece Assets/Black_Knight.png", "purchased": false},
		{"name": "Upgrade 5", "price": 5, "tier": "gold", "texture": "res://assets/Resized Chess Piece Assets/Black_Queen.png", "purchased": false}
	]
}

var tier_weights = {
	"bronze": 5,
	"silver": 3,
	"gold": 1
}

func _ready():
	self.visible = false  # Start hidden
	# Connect the reset button
	var reset_button = $MainContainer/RowsContainer/BottomSection/ResetShopButton  # Adjust the path to your button
	reset_button.connect("pressed", Callable(self, "_on_reset_button_pressed"))
	populate_rows()  # Populate the shop rows
	# self.custom_minimum_size = get_viewport_rect().size  # Fill the screen
	
func set_visibility(visible: bool):
	self.visible = visible

func _on_back_button_pressed():
	get_tree().change_scene_to_file("res://Game.tscn")  # Return to game

func populate_rows():
	clear_row($MainContainer/RowsContainer/PiecesRow)
	clear_row($MainContainer/RowsContainer/UpgradesRow)
	
	# Add 3 random pieces
	for i in 3:
		var piece = select_random_item("pieces")
		add_item_to_row(piece, $MainContainer/RowsContainer/PiecesRow)
	
	# Add 3 random upgrades
	for i in 3:
		var upgrade = select_random_item("upgrades")
		add_item_to_row(upgrade, $MainContainer/RowsContainer/UpgradesRow)


func _on_reset_button_pressed():
	# Clear existing items
	clear_row($MainContainer/RowsContainer/PiecesRow)
	clear_row($MainContainer/RowsContainer/UpgradesRow)
	
	# Repopulate the shop
	populate_rows()

func clear_row(row: HBoxContainer):
	for child in row.get_children():
		child.queue_free()


func select_random_item(category: String) -> Dictionary:
	var items = shop_items[category]
	var total_weight = 0
	
	# Calculate total weight
	for item in items:
		total_weight += tier_weights[item["tier"]]
	
	# Select random item
	var random_value = randf() * total_weight
	var cumulative = 0.0
	
	for item in items:
		cumulative += tier_weights[item["tier"]]
		if random_value < cumulative:
			return item.duplicate()  # Return a copy to avoid modifying original
	
	return items[0].duplicate()  # Fallback


func add_item_to_row(item_data: Dictionary, row: HBoxContainer):
	var shop_item = shop_item_scene.instantiate()

	# Set the tier style FIRST
	shop_item.set_tier_style(item_data["tier"])

	shop_item.get_node("MarginContainer/VBoxContainer/ItemName").text = item_data["name"]
	shop_item.get_node("MarginContainer/VBoxContainer/ItemPrice").text = "%dg" % item_data["price"]
	shop_item.get_node("MarginContainer/VBoxContainer/ItemSprite").texture = load(item_data["texture"])

	# Connect the BuyButton
	var buy_button = shop_item.get_node("MarginContainer/VBoxContainer/BuyButton")
	buy_button.connect("pressed", Callable(self, "_on_buy_button_pressed").bind(item_data, shop_item))

	row.add_child(shop_item)

func _on_buy_button_pressed(item_data: Dictionary, shop_item: Node):
	if !item_data["purchased"]:
		print("Attempting to Purchase: ", item_data["name"])
		# Emit signals to let Game.gd handle the purchase
		emit_signal("purchase_attempted", item_data, shop_item)  # Emit the full item data
		# TODO: Add a sound effect / Animation for purchasing items
	else:
		print("Item already purchased!")
	


func _on_next_round_button_pressed():
	print("Next Round button pressed!")
	visible = false  # Hide the shop
	emit_signal("next_round_requested")  # Notify the main game script


func _on_reset_shop_button_pressed() -> void:
	pass # Replace with function body.