extends Node3D

@onready var world: Node3D = $World/ChunkManager
@onready var dolphin: CharacterBody3D = $Dolphin
@onready var hud: CanvasLayer = $Dolphin/HUD
@onready var plankton_follower: Node3D = $PlanktonFollower

var inventory: Inventory = Inventory.new()
var _inventory_ui: CanvasLayer = null


func _ready() -> void:
	dolphin.block_break_requested.connect(_on_block_break)
	dolphin.block_place_requested.connect(_on_block_place)
	dolphin.echolocation_triggered.connect(_on_echolocation)

	if dolphin.has_signal("hotbar_scroll"):
		dolphin.hotbar_scroll.connect(inventory.scroll_hotbar)

	if is_instance_valid(hud) and hud.has_method("connect_to_dolphin"):
		hud.connect_to_dolphin(dolphin)

	# Load and attach InventoryUI
	var ui_scene: PackedScene = load("res://scenes/InventoryUI.tscn")
	if ui_scene != null:
		_inventory_ui = ui_scene.instantiate() as CanvasLayer
		add_child(_inventory_ui)
		_inventory_ui.setup(inventory)
	else:
		push_error("Main: could not load InventoryUI.tscn")

	AudioManager.play_ambient_loop("underwater_ambient")
	AudioManager.play_music("underwater_theme")
	AudioManager.play_whale_call_random()

	world.world_seed = 12345

	# Starting inventory
	inventory.add_item(2, 10)  # 10 SAND
	inventory.add_item(6, 5)   # 5 KELP
	inventory.add_item(8, 2)   # 2 ICE


func _process(_delta: float) -> void:
	world.update_player_position(dolphin.global_position)
	plankton_follower.global_position = dolphin.global_position


func _on_block_break(hit_position: Vector3, _normal: Vector3) -> void:
	var broken_id: int = world.break_block(hit_position)
	if broken_id > 0:
		inventory.add_item(broken_id, 1)
		AudioManager.play_bubble_sfx(hit_position)


func _on_block_place(hit_position: Vector3, normal: Vector3) -> void:
	var selected: Variant = inventory.get_selected_item()
	if selected == null:
		return
	if not ItemDatabase.is_placeable(selected["item_id"]):
		return
	var place_pos := hit_position + normal * 0.5
	if world.place_block(place_pos, selected["item_id"]):
		inventory.remove_item_from_slot(inventory.selected_hotbar, 1)


func _on_echolocation(position: Vector3, _radius: float) -> void:
	AudioManager.play_bubble_sfx(position)
