extends Control

var controller: TrainingController

@onready var hand_area: Node = $HandArea
@onready var play_button: Button = $Buttons/PlayButton
@onready var pass_button: Button = $Buttons/PassButton
@onready var hint_button: Button = $Buttons/HintButton
@onready var status_label: Label = $StatusLabel

func _ready() -> void:
	hand_area.training_controller = controller
	play_button.pressed.connect(_on_play_pressed)
	pass_button.pressed.connect(_on_pass_pressed)
	hint_button.pressed.connect(_on_hint_pressed)

func start_training() -> void:
	controller = TrainingController.new()
	controller.start_game(Config.rule_config, 0)
	controller.turn_ready.connect(_on_turn_ready)
	controller.state_changed.connect(_refresh_ui)
	controller.game_ended.connect(_on_game_ended)
	_refresh_ui()

func _on_turn_ready(player_idx: int, is_human: bool) -> void:
	if is_human:
		hand_area.enable_input()
		status_label.text = "你的回合"
	else:
		hand_area.disable_input()
		status_label.text = "%s 思考中..." % controller.game_state.player_names[player_idx]

func _on_play_pressed() -> void:
	var selected := hand_area.selected_cards
	if selected.is_empty():
		return
	var result := controller.handle_human_play(selected)
	if not result.ok:
		status_label.text = "无效出牌"
		return
	hand_area.clear_selection()
	_refresh_ui()

func _on_pass_pressed() -> void:
	var result := controller.handle_human_pass()
	if not result.ok:
		status_label.text = "不能过牌"
		return
	_refresh_ui()

func _on_hint_pressed() -> void:
	var hint := controller.get_hint()
	if hint == null or hint.type == -1:
		status_label.text = "建议：过牌"
		return
	hand_area.clear_selection()
	for card in hint.cards:
		for cn in hand_area.card_nodes:
			if cn.card_data != null and cn.card_data.card_id == card.card_id:
				cn.set_selected(true)
				hand_area.selected_cards.append(card)
	status_label.text = "建议牌型: %s (rank=%d)" % [hint.type, hint.primary_rank]

func _on_game_ended(winner_team: int, reason: String) -> void:
	status_label.text = "游戏结束! 队伍 %d 获胜" % winner_team
	hand_area.disable_input()

func _refresh_ui() -> void:
	if controller and controller.game_state:
		hand_area.update_hand(controller.game_state.get_hand(0))
