extends Node
class_name IsometricPlayerController

var player_node
var map_data
var map_renderer

func _init(player, map_data_ref, renderer):
    player_node = player
    map_data = map_data_ref
    map_renderer = renderer

# Initialize player at a specific position
func init_player(x=10, y=10, z=1):
    var tile = map_data.get_tile(x, y, z)
    if tile:
        tile["visibility"] = true
        tile["unit"] = player_node
        tile["unit_type"] = "PC"
        
        # Use renderer to position the player
        map_renderer.position_unit(player_node, tile["x"], tile["y"], tile["z"])
        return true
    return false

# Move player up or down a layer
func move_vertical(direction = "up"):
    var z_offset = 0
    if direction == "up":
        z_offset = 1 
    elif direction == "down":
        z_offset = -1 
        
    # Find current player position
    var player_position = map_data.find_unit_tile("PC")
    if not player_position:
        print("Cannot find player position")
        return false
    
    var current_x = player_position.x
    var current_y = player_position.y
    var current_z = player_position.z
    var new_z = current_z + z_offset
    
    # Check if new position is valid
    if new_z < 0 or new_z >= map_data.GRID_SIZE_HEIGHT:
        print("New Z position out of bounds: ", new_z)
        return false
    
    # Check if destination tile exists
    var destination_tile = map_data.get_tile(current_x, current_y, new_z)
    if destination_tile == null:
        print("Destination tile doesn't exist at: ", current_x, ", ", current_y, ", ", new_z)
        return false
    
    # Debug the current tile before moving
    var current_tile = map_data.get_tile(current_x, current_y, current_z)
    print("Current tile before move: ", current_tile)
    
    # Set up the destination tile to receive the player
    destination_tile["unit"] = current_tile["unit"]
    destination_tile["unit_type"] = "PC"
    destination_tile["visibility"] = true
    
    # Clear the current tile's unit data
    current_tile["unit"] = null
    current_tile["unit_type"] = null
    destination_tile["visibility"] = false
    
    # Update visual position
    map_renderer.position_unit(player_node, destination_tile["x"], destination_tile["y"], destination_tile["z"])
    print("Player moved to: ", current_x, ", ", current_y, ", ", new_z)
    
    return true
