extends Node

@onready var bubbles: HBoxContainer = %Bubbles
@onready var bubbles_back: TileMapLayer = %BubblesBack
@onready var bubbles_interior: TileMapLayer = %BubblesInterior
@onready var bubble_label: RichTextLabel = %BubbleLabel

@onready var ui_flicker_timer: Timer = $UIFlickerTimer
@onready var e_ui_button: TextureRect = %E
@onready var next_label: Label = %NextLabel

@onready var choices_container: MarginContainer = %ChoicesContainer
@onready var accept_indicator: ColorRect = %AcceptIndicator
@onready var accept_label: Label = %AcceptLabel
@onready var reject_indicator: ColorRect = %RejectIndicator
@onready var reject_label: Label = %RejectLabel

@export_multiline var choice = ""
@export var accept_option = ""
@export var reject_option = ""

@onready var wait_a_sec: Timer = $WaitASec

signal accepted
signal rejected

var is_accept_selected = true
var is_choice_happening = false

func _process(delta: float) -> void:
	if not is_choice_happening:
		return
	
	if Input.is_action_just_pressed("move_right"):
		is_accept_selected = false
		update_ui()
	
	if Input.is_action_just_pressed("move_left"):
		is_accept_selected = true
		update_ui()
	
	if Input.is_action_just_pressed("interact"):
		stop_choice()
		

func update_ui():
	accept_indicator.visible = is_accept_selected
	reject_indicator.visible = not is_accept_selected

func toggle_ui():
	e_ui_button.visible = not e_ui_button.visible

func start_choice():
	bubbles.visible = true
	bubbles_back.visible = true
	bubbles_interior.visible = true
	bubble_label.visible = true
	e_ui_button.visible = true
	next_label.visible = true
	choices_container.visible = true
	
	bubble_label.text = choice
	
	accept_label.text = accept_option
	reject_label.text = reject_option
	
	is_accept_selected = true
	update_ui()
	
	wait_a_sec.start()

func stop_choice():
	is_choice_happening = false
	
	ui_flicker_timer.stop()
	
	bubbles.visible = false
	bubbles_back.visible = false
	bubbles_interior.visible = false
	bubble_label.visible = false
	e_ui_button.visible = false
	next_label.visible = false
	choices_container.visible = false
	
	if is_accept_selected:
		accepted.emit()
	else:
		rejected.emit()

func _on_wait_a_sec_timeout() -> void:
	is_choice_happening = true
	ui_flicker_timer.start()
