## Character — base class for all playable figures (bunny, cat, etc.).
class_name Character extends Node2D

const _CharacterData = preload("res://scripts/characters/character_data.gd")

signal character_picked_up(character: Character)
signal character_placed(character: Character, position: Vector2)
signal state_changed(new_state: CharacterData.State)

@export var character_id: String = ""
@export var display_name: String = ""
@export var data: CharacterData

var _is_held: bool = false

const _STATE_COLORS: Dictionary = {
	CharacterData.State.HEALTHY: Color(0.6, 0.8, 1.0),
	CharacterData.State.SICK: Color(0.7, 0.9, 0.7),
	CharacterData.State.SLEEPING: Color(0.8, 0.7, 0.95),
	CharacterData.State.TIRED: Color(1.0, 0.95, 0.6),
	CharacterData.State.PREGNANT: Color(1.0, 0.85, 0.9),
	CharacterData.State.BABY: Color(0.9, 0.95, 1.0),
}


func _ready() -> void:
	var drag: DragDropComponent = get_node_or_null("DragDropComponent") as DragDropComponent
	if drag != null:
		drag.drag_picked_up.connect(_on_drag_picked_up)
		drag.drag_released.connect(_on_drag_released)
	if data != null:
		_update_visual_state()


func set_state(new_state: CharacterData.State) -> void:
	if data == null:
		return
	data.state = new_state
	_update_visual_state()
	state_changed.emit(new_state)


func _update_visual_state() -> void:
	if data == null:
		return
	var visual: ColorRect = get_node_or_null("Visual") as ColorRect
	if visual == null:
		return
	var color: Color = _STATE_COLORS.get(data.state, Color(0.6, 0.8, 1.0))
	visual.color = color
	var ear_left: ColorRect = get_node_or_null("Ears/EarLeft") as ColorRect
	var ear_right: ColorRect = get_node_or_null("Ears/EarRight") as ColorRect
	if ear_left != null:
		ear_left.color = color
	if ear_right != null:
		ear_right.color = color


func _on_drag_picked_up(_pos: Vector2) -> void:
	_is_held = true
	character_picked_up.emit(self)


func _on_drag_released(pos: Vector2) -> void:
	_is_held = false
	if data == null or data.id.is_empty():
		return
	GameState.set_character_position(character_id, global_position)
	character_placed.emit(self, global_position)
