extends Node2D


@export var _town_label: RichTextLabel
@export var _items: HFlowContainer
@export var _towns: VBoxContainer
@export var _weight_label: RichTextLabel
@export var _description_box_label: RichTextLabel
@export var _fade_rect: ColorRect


func _ready() -> void:
	_fade_rect.show()
	create_tween().tween_property(_fade_rect, "color:a", 0, 0.2)
	
	for i in range(Config.START_ITEMS):
		var item: Item = Config.ITEM_DB.pick_random()
		GameState.fetch().player_inventory.add_item(item.duplicate())
	
	_weight_label.text = (
		"%d/%d" % [
			GameState.fetch().player_inventory.total_weight(),
			GameState.fetch().player_inventory.max_weight
		]
	)
	
	for item in GameState.fetch().player_inventory.items:
		const ITEM_BOX_SCENE = preload("res://src/lib/item_box.tscn")
		const ItemBox = preload("res://src/lib/item_box.gd")
		
		var new_node: ItemBox = ITEM_BOX_SCENE.instantiate()
		new_node.update_from_item(item, true)
		
		new_node.gui_input.connect(_on_item_gui_input.bind(item))
		new_node.focus_entered.connect(_display_item_info.bind(item))
		
		_items.add_child(new_node)
	
	_set_town(Config.START_TOWN)
	var towns_to_add: Array[Town]
	towns_to_add.push_back(GameState.fetch().town)
	towns_to_add.append_array(GameState.fetch().town.neighboring_towns)
	for town in towns_to_add:
		var new_button := Button.new()
		new_button.text = town.name
		new_button.pressed.connect(_on_town_pressed.bind(town))
		_towns.add_child(new_button)


func _display_item_info(item: Item) -> void:
	var text := ""
	
	text += "[color=yellow]%s[/color]\n" % item.name
	text += "[color=white]%s[/color]\n\n" % item.description
	text += "[color=gray]%s[/color]\n" % item.category_list()
	text += "[color=gray]Weighs %d[/color]" % item.weight
	
	if item.states != Item.State.STATE_NONE:
		text += "\n\n[color=blue]%s[/color]" % item.state_list()
	
	_description_box_label.text = text


func _set_town(town: Town) -> void:
	GameState.fetch().town = town
	_town_label.text = "Going to \"%s\"" % GameState.fetch().town.name


func _on_item_gui_input(event: InputEvent, item: Item) -> void:
	if event is InputEventMouseMotion:
		_display_item_info(item)


func _on_town_pressed(town: Town) -> void:
	var text := ""
	text += "[color=yellow]%s[/color]\n" % town.name
	text += "[color=white]%s %s town[/color]" % [
		town.size_to_string().to_pascal_case(),
		town.status_to_string()
	]
	if town.workshops != Town.Workshop.WORKSHOP_NONE:
		text += "\n\n[color=gray]Has %s[/color]" % town.workshop_list(false)
	_description_box_label.text = text
	
	_set_town(town)


func _on_go_forth_pressed() -> void:
	var fade_tween := create_tween()
	fade_tween.tween_property(_fade_rect, "color:a", 1, 0.2)
	await fade_tween.finished
	await get_tree().create_timer(0.1).timeout
	MainEvents.scene_change_requested.emit("res://src/overworld/overworld.tscn")
