extends HBoxContainer

@export var config: PrestigeConfig

@onready var _label_start = $LabelStart
@onready var _label_end = $LabelEnd
@onready var _progress_bar = $ProgressBar

var _basis_value: BigNumber
var _next_threshold: BigNumber
var _manager: Node
var _connected: bool = false

func _ready() -> void:
	_manager = get_node_or_null("/root/PrestigeManager")
	if _manager == null:
		push_warning("PrestigeProgressBar '%s' cannot find PrestigeManager; progress bar disabled." % String(name))
		visible = false
		return
	
	if not _manager.has_signal("prestige_state_changed"):
		push_warning("PrestigeManager does not have 'prestige_state_changed' signal; progress bar will not update.")
		visible = false
		return
	
	if config == null:
		if _manager.has_method("get_config"):
			config = _manager.get_config()
	
	if config == null:
		push_warning("PrestigeProgressBar '%s' has no config; progress bar disabled." % String(name))
		visible = false
		return
	
	if _manager.has_signal("prestige_threshold_changed"):
		_manager.prestige_threshold_changed.connect(_on_prestige_threshold_changed)
	_manager.prestige_state_changed.connect(_on_prestige_state_changed)
	_connected = true
	_update_progress()

func _on_prestige_state_changed(_total: BigNumber, _pending: BigNumber) -> void:
	_update_progress()

func _on_prestige_threshold_changed(_threshold: BigNumber) -> void:
	_update_progress()

func _update_progress() -> void:
	if not _connected:
		return
	
	if _manager == null or config == null:
		return
	
	_basis_value = _manager.call("get_basis_value_for_display")
	if _manager.has_method("get_next_prestige_threshold"):
		_next_threshold = _manager.call("get_next_prestige_threshold")
	else:
		_next_threshold = _get_threshold_from_config()
	
	var basis_float: float = _big_number_to_float(_basis_value)
	var threshold_float: float = _big_number_to_float(_next_threshold)
	
	if threshold_float > 0.0 and basis_float >= 0.0:
		var ratio: float = minf(basis_float / threshold_float, 1.0)
		_progress_bar.value = ratio * 100.0
	else:
		_progress_bar.value = 0.0
	
	_label_start.text = _basis_value.to_string_suffix(2)
	_label_end.text = _next_threshold.to_string_suffix(2)

func _get_threshold_from_config() -> BigNumber:
	if config == null:
		return BigNumber.from_float(0.0)
	
	if not config.has_method("get_threshold"):
		return BigNumber.from_float(0.0)
	
	var threshold = config.call("get_threshold")
	if threshold is BigNumber:
		return threshold
	
	return BigNumber.from_float(0.0)

func _big_number_to_float(value: BigNumber) -> float:
	if value.mantissa <= 0.0:
		return 0.0
	if value.exponent > 308:
		return INF
	if value.exponent < -308:
		return 0.0
	return value.mantissa * pow(10.0, float(value.exponent))
