extends Node2D

@onready var player: CharacterBody2D = get_node_or_null("Player")
@onready var enemy: CharacterBody2D = get_node_or_null("Enemy")
@onready var hud: CanvasLayer = get_node_or_null("HUD")

var match_time: float = 0.0
var fight_finished: bool = false
var is_paused: bool = false
var pause_layer: CanvasLayer
var pause_panel: Panel
var btn_pause: Button
var btn_resume: Button
var btn_pause_exit: Button
var results_layer: CanvasLayer
var results_panel: Panel
var results_title: Label
var results_stats: Label
var btn_retry: Button
var btn_menu: Button


func _ready() -> void:
	_ensure_floor_exists()
	_ensure_hud_exists()
	_ensure_pause_input_action()
	_create_pause_ui()

	# fighter links
	if player != null and enemy != null:
		if player.has_method("set_enemy"):
			player.call("set_enemy", enemy)
		if enemy.has_method("set_player"):
			enemy.call("set_player", player)

		# bounds
		var vp: Vector2 = get_viewport().get_visible_rect().size
		var min_x: float = 40.0
		var max_x: float = vp.x - 40.0
		player.set("min_x", min_x)
		player.set("max_x", max_x)
		enemy.set("min_x", min_x)
		enemy.set("max_x", max_x)

	# HUD fighters
	if hud != null and hud.has_method("set_fighters") and player != null and enemy != null:
		hud.call("set_fighters", player, enemy)

	_create_results_ui()

func _process(delta: float) -> void:
	if fight_finished or is_paused:
		return

	match_time += delta

	if hud != null and hud.has_method("set_time"):
		hud.call("set_time", match_time)
	if hud != null and hud.has_method("update_bars"):
		hud.call("update_bars")

func end_fight(player_won: bool) -> void:
	if fight_finished:
		return
	fight_finished = true

	if player != null:
		player.set_physics_process(false)
		player.set_process(false)
	if enemy != null:
		enemy.set_physics_process(false)
		enemy.set_process(false)

	var time_sec: int = int(match_time)
	var p_hp: int = 0
	var e_hp: int = 0
	if hud != null and hud.has_method("get_player_hp_percent"):
		p_hp = int(hud.call("get_player_hp_percent"))
	if hud != null and hud.has_method("get_enemy_hp_percent"):
		e_hp = int(hud.call("get_enemy_hp_percent"))

	var score: int
	if player_won:
		score = 1000 - time_sec * 3 + p_hp * 5
	else:
		score = 200 - time_sec * 2 + e_hp * 2
	score = max(score, 0)

	# save to db 
	var gm: Node = get_node_or_null("/root/GameManager")
	if gm == null:
		gm = get_node_or_null("GameManager")
	if gm != null and gm.has_method("save_result_to_db"):
		var result_text: String = "win" if player_won else "lose"
		gm.call("save_result_to_db", result_text, score, time_sec)

	results_panel.visible = true
	results_title.text = "YOU WIN" if player_won else "YOU LOSE"
	results_stats.text = "Time: %ds\nScore: %d" % [time_sec, score]

# ----------------- ensure stuff exists -----------------

func _ensure_hud_exists() -> void:
	if hud != null:
		return
	hud = CanvasLayer.new()
	hud.name = "HUD"
	add_child(hud)

func _ensure_floor_exists() -> void:
	var floor_node: StaticBody2D = get_node_or_null("floor") as StaticBody2D
	if floor_node == null:
		floor_node = StaticBody2D.new()
		floor_node.name = "floor"
		add_child(floor_node)

	# collision shape
	var col: CollisionShape2D = floor_node.get_node_or_null("CollisionShape2D") as CollisionShape2D
	if col == null:
		col = CollisionShape2D.new()
		col.name = "CollisionShape2D"
		floor_node.add_child(col)

	if col.shape == null:
		var shape := RectangleShape2D.new()
		var vp: Vector2 = get_viewport().get_visible_rect().size
		shape.size = Vector2(vp.x + 400.0, 40.0)
		col.shape = shape

	# pozīcija
	var vp2: Vector2 = get_viewport().get_visible_rect().size
	var floor_y: float = 500.0
	floor_node.position = Vector2(vp2.x * 0.5, floor_y)

	# vizuālais grīdas taisnstūris 
	var visual: ColorRect = get_node_or_null("FloorVisual") as ColorRect
	if visual == null:
		visual = ColorRect.new()
		visual.name = "FloorVisual"
		visual.color = Color(0.2, 0.2, 0.2)
		visual.size = Vector2(vp2.x, 40)
		visual.position = Vector2(0, floor_y - 20)
		add_child(visual)

# ----------------- results ui -----------------

func _create_results_ui() -> void:
	results_layer = CanvasLayer.new()
	add_child(results_layer)

	results_panel = Panel.new()
	results_panel.visible = false
	results_panel.size = get_viewport().get_visible_rect().size
	results_layer.add_child(results_panel)

	var overlay := ColorRect.new()
	overlay.color = Color(0, 0, 0, 0.55)
	overlay.size = results_panel.size
	results_panel.add_child(overlay)

	results_title = Label.new()
	results_title.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	results_title.position = Vector2(0, 160)
	results_title.size = Vector2(results_panel.size.x, 60)
	results_title.add_theme_font_size_override("font_size", 44)
	results_panel.add_child(results_title)

	results_stats = Label.new()
	results_stats.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	results_stats.position = Vector2(0, 230)
	results_stats.size = Vector2(results_panel.size.x, 90)
	results_stats.add_theme_font_size_override("font_size", 20)
	results_panel.add_child(results_stats)

	btn_retry = Button.new()
	btn_retry.text = "Mēģināt vēlreiz"
	btn_retry.position = Vector2(results_panel.size.x * 0.5 - 140, 340)
	btn_retry.size = Vector2(280, 42)
	btn_retry.pressed.connect(func(): get_tree().reload_current_scene())
	results_panel.add_child(btn_retry)

	btn_menu = Button.new()
	btn_menu.text = "Uz galveno izvēlni"
	btn_menu.position = Vector2(results_panel.size.x * 0.5 - 140, 390)
	btn_menu.size = Vector2(280, 42)
	btn_menu.pressed.connect(func():
		var menu_path := "res://scenes/MainMenu.tscn"
		if ResourceLoader.exists(menu_path):
			get_tree().change_scene_to_file(menu_path)
	)
	results_panel.add_child(btn_menu)

# ----------------- pause ui -----------------

func _input(event: InputEvent) -> void:
	if fight_finished:
		return

	if event.is_action_pressed("pause_game"):
		toggle_pause()


func toggle_pause() -> void:
	_set_pause(not is_paused)


func _set_pause(value: bool) -> void:
	is_paused = value
	get_tree().paused = value

	if pause_panel != null:
		pause_panel.visible = value

	if btn_pause != null:
		btn_pause.visible = not value


func _ensure_pause_input_action() -> void:
	if not InputMap.has_action("pause_game"):
		InputMap.add_action("pause_game")

		var ev := InputEventKey.new()
		ev.physical_keycode = KEY_ESCAPE
		InputMap.action_add_event("pause_game", ev)


func _create_pause_ui() -> void:
	pause_layer = CanvasLayer.new()
	pause_layer.name = "PauseLayer"
	pause_layer.process_mode = Node.PROCESS_MODE_ALWAYS
	add_child(pause_layer)

	var vp: Vector2 = get_viewport().get_visible_rect().size

	btn_pause = Button.new()
	btn_pause.text = "⏸"
	btn_pause.position = Vector2(vp.x / 2 - 25, 75)
	btn_pause.size = Vector2(50, 42)
	btn_pause.process_mode = Node.PROCESS_MODE_ALWAYS
	btn_pause.pressed.connect(func(): _set_pause(true))
	pause_layer.add_child(btn_pause)

	pause_panel = Panel.new()
	pause_panel.visible = false
	pause_panel.size = vp
	pause_panel.process_mode = Node.PROCESS_MODE_ALWAYS
	pause_layer.add_child(pause_panel)

	var overlay := ColorRect.new()
	overlay.color = Color(0, 0, 0, 0.60)
	overlay.size = vp
	overlay.process_mode = Node.PROCESS_MODE_ALWAYS
	pause_panel.add_child(overlay)

	var title := Label.new()
	title.text = "PAUSE"
	title.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	title.position = Vector2(0, 155)
	title.size = Vector2(vp.x, 60)
	title.add_theme_font_size_override("font_size", 46)
	title.process_mode = Node.PROCESS_MODE_ALWAYS
	pause_panel.add_child(title)

	btn_resume = Button.new()
	btn_resume.text = "Resume"
	btn_resume.position = Vector2(vp.x * 0.5 - 140, 280)
	btn_resume.size = Vector2(280, 44)
	btn_resume.process_mode = Node.PROCESS_MODE_ALWAYS
	btn_resume.pressed.connect(func(): _set_pause(false))
	pause_panel.add_child(btn_resume)

	btn_pause_exit = Button.new()
	btn_pause_exit.text = "Exit"
	btn_pause_exit.position = Vector2(vp.x * 0.5 - 140, 340)
	btn_pause_exit.size = Vector2(280, 44)
	btn_pause_exit.process_mode = Node.PROCESS_MODE_ALWAYS
	btn_pause_exit.pressed.connect(func():
		_set_pause(false)
		get_tree().change_scene_to_file("res://scenes/MainMenu.tscn")
	)
	pause_panel.add_child(btn_pause_exit)
