class_name StrategyPhase extends Node2D

@onready var player_controller: PlayerController = $PlayerController
@onready var combat_system: CombatSystem = $CombatSystem
@onready var combat_ui: CombatUI = $CombatUI
@onready var combat_map: CombatMap = $CombatMap
@onready var camera: CameraController = $Camera2D

func _ready() -> void:
	# -- Test room layout (remove once map editor exists) --
	var room_a := Room.new()
	room_a.id = 0
	room_a.tiles = [
		Vector2i(2, 2), Vector2i(3, 2), Vector2i(4, 2),
		Vector2i(2, 3), Vector2i(3, 3), Vector2i(4, 3),
		Vector2i(2, 4), Vector2i(3, 4), Vector2i(4, 4),
	]

	var room_b := Room.new()
	room_b.id = 1
	room_b.tiles = [
		Vector2i(5, 2), Vector2i(6, 2), Vector2i(7, 2),
		Vector2i(5, 3), Vector2i(6, 3), Vector2i(7, 3),
		Vector2i(5, 4), Vector2i(6, 4), Vector2i(7, 4),
	]

	var layout := MapLayout.new()
	layout.rooms = [room_a, room_b]
	# Opening between (4,3) in room_a and (5,3) in room_b
	layout.openings = [Vector2i(4, 3), Vector2i(5, 3)]
	layout.size = Vector2i(10, 7)

	combat_map.apply_layout(layout)
	camera.set_map_bounds(combat_map.get_map_rect())
	# -- End test room layout --

	player_controller.combat_requested.connect(_on_combat_requested)
	player_controller.mouse_grid_changed.connect(_on_mouse_grid_changed)
	player_controller.camera_drag.connect(camera.apply_drag)
	combat_ui.fight_confirmed.connect(_on_fight_confirmed)
	combat_ui.fight_cancelled.connect(_on_fight_cancelled)
	combat_ui.combat_system = combat_system


func _on_mouse_grid_changed(coords: Vector2i) -> void:
	combat_map.target_tile(coords)

func _on_combat_requested(attacker: DeployedUnit, defender: DeployedUnit) -> void:
	var atk_coords := BattleMapHelper.world_to_coords(attacker.position)
	var def_coords := BattleMapHelper.world_to_coords(defender.position)
	var distance := absi(atk_coords.x - def_coords.x) + absi(atk_coords.y - def_coords.y)
	var proposal := combat_system.create_proposal(attacker, defender, distance)
	_set_input_disabled(true)
	combat_ui.show_proposal(proposal)


func _on_fight_confirmed(proposal: CombatProposal) -> void:
	combat_system.apply_proposal(proposal)
	_set_input_disabled(false)


func _on_fight_cancelled() -> void:
	_set_input_disabled(false)


func _set_input_disabled(disabled: bool) -> void:
	player_controller.input_disabled = disabled
