@tool
extends StaticBody2D

enum Direction { LEFT, RIGHT, FRONT }

@onready var sprite: Sprite2D = $Sprite2D
@onready var collision_shape: CollisionShape2D = $CollisionShape2D

var seat_height_offset = 8
var player: Player
var input_released = true
var move_input = Vector2.ZERO

@export var direction: Direction = Direction.RIGHT:
	set(value):
		direction = value
		update_chair_visuals()

func _ready() -> void:
	update_chair_visuals()

func update_chair_visuals() -> void:
	if not sprite:
		return
	var atlas_tex = sprite.texture as AtlasTexture
	if direction == Direction.FRONT:
		atlas_tex.region.position.x = -3
		seat_height_offset = -5
		sprite.flip_h = false
	else:
		atlas_tex.region.position.x = 32
		seat_height_offset = 8
		sprite.flip_h = direction == Direction.LEFT

func _on_interacted(p_player: Player) -> void:
	if player:
		unmount_player()
	else:
		mount_player(p_player)

func mount_player(p_player: Player) -> void:
	collision_shape.disabled = true
	y_sort_enabled = false
	z_index = -1
	player = p_player
	input_released = move_input.length() == 0
	player.animated_sprite.flip_h = direction == Direction.LEFT
	player.position = Vector2(position.x, position.y - seat_height_offset)
	player.animated_sprite.animation = "sit_down" if direction == Direction.FRONT else "sit_side"

func _process(_delta: float) -> void:
	if Engine.is_editor_hint() || !EventManager.player_free || !player:
		return
	move_input = Input.get_vector("move_left", "move_right", "move_up", "move_down")
	if move_input.length() == 0:
		input_released = true
	elif input_released:
		unmount_player()

func unmount_player() -> void:
	if direction == Direction.FRONT:
		player.position = Vector2(position.x - 16, position.y)
	else:
		player.position = Vector2(position.x, position.y + 8)
	player.animated_sprite.animation = "down"
	z_index = 0
	player = null
	input_released = true
	y_sort_enabled = true
	collision_shape.disabled = false
