using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

namespace eagle {
    public class DynamicHeroTextUpdater : IDisposable {
        private List<GeneratedTextListener> textListeners = new();
        private Dictionary<string, TMP_Text> textComponents = new();
        private Dictionary<string, string> fallbackTexts = new();

        public void SetHeroText(TMP_Text textComponent, string nameTextId, string fallbackText) {
            if (!textComponent) return;

            string componentKey = textComponent.GetInstanceID().ToString();
            textComponents[componentKey] = textComponent;
            fallbackTexts[componentKey] = fallbackText;

            // Set initial text
            if (!string.IsNullOrEmpty(nameTextId)) {
                var textEntry = ClientTextProvider.Provider.GetTextEntry(nameTextId);
                if (textEntry != null && !string.IsNullOrEmpty(textEntry.Text)) {
                    textComponent.text = textEntry.Text;
                } else {
                    textComponent.text = fallbackText;

                    // Create listener for dynamic updates
                    var listener = new GeneratedTextListener(
                            nameTextId,
                            "",
                            "",
                            0,
                            (index, text) => UpdateComponentText(componentKey, text));

                    textListeners.Add(listener);
                    ClientTextProvider.Provider.AddListener(listener);
                }
            } else {
                textComponent.text = fallbackText;
            }
        }

        private void UpdateComponentText(string componentKey, string newText) {
            if (textComponents.TryGetValue(componentKey, out var component) && component != null) {
                component.text = newText;
            }
        }

        public void Dispose() {
            foreach (var listener in textListeners) {
                ClientTextProvider.Provider.RemoveListener(listener);
            }
            textListeners.Clear();
            textComponents.Clear();
            fallbackTexts.Clear();
        }
    }
}