using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

namespace LiveOpsExamples
{
  public class EventInspectorPanel : MonoBehaviour
  {
    private static readonly Dictionary<string, Color> CapabilityColors = new Dictionary<string, Color>
    {
      { "auth", new Color(0.486f, 0.769f, 1f) },
      { "config", new Color(0.945f, 0.776f, 0.490f) },
      { "scenario", new Color(0.769f, 0.635f, 1f) },
      { "store", new Color(1f, 0.698f, 0.490f) },
      { "leaderboard", new Color(0.482f, 0.878f, 0.690f) },
      { "storage", new Color(0.624f, 0.690f, 0.769f) },
      { "inventory", new Color(0.898f, 0.604f, 0.796f) },
      { "wallet", new Color(1f, 0.831f, 0.475f) },
      { "system", new Color(0.667f, 0.706f, 0.635f) },
    };

    private static readonly Dictionary<string, string> CapabilityLabels = new Dictionary<string, string>
    {
      { "auth", "Auth" },
      { "config", "Config" },
      { "scenario", "Scenario" },
      { "store", "Store" },
      { "leaderboard", "Board" },
      { "storage", "Storage" },
      { "inventory", "Items" },
      { "wallet", "Wallet" },
      { "system", "System" },
    };

    private static readonly Color FallbackColor = new Color(0.667f, 0.706f, 0.635f);

    [SerializeField] private PanelRenderer panelRenderer;
    [SerializeField] private CozyCollectorController controller;
    [SerializeField] private VisualTreeAsset logRowTemplate;

    private ScrollView _scroll;
    private VisualElement _emptyNote;

    private void OnEnable()
    {
      panelRenderer.RegisterUIReloadCallback(OnUIReload);
      controller.LogAdded += Rebuild;
    }

    private void OnDisable()
    {
      panelRenderer.UnregisterUIReloadCallback(OnUIReload);
      controller.LogAdded -= Rebuild;
    }

    private void OnUIReload(PanelRenderer renderer, VisualElement root)
    {
      _scroll = root.Q<ScrollView>("event-log-scroll");
      _emptyNote = root.Q("event-log-empty");

      Rebuild();
    }

    private void Rebuild()
    {
      var container = _scroll.contentContainer;
      container.Clear();

      var entries = controller.LogEntries;
      _emptyNote.style.display = entries == null || entries.Count == 0 ? DisplayStyle.Flex : DisplayStyle.None;
      if (entries == null)
      {
        return;
      }

      foreach (var entry in entries)
      {
        var rowRoot = logRowTemplate.CloneTree();
        container.Add(rowRoot);

        string key = entry.Capability == null ? string.Empty : entry.Capability.ToLowerInvariant();
        string label = CapabilityLabels.TryGetValue(key, out var known) ? known : entry.Capability;
        Color color = CapabilityColors.TryGetValue(key, out var knownColor) ? knownColor : FallbackColor;
        string detail = string.IsNullOrEmpty(entry.Detail) ? string.Empty : $" — {entry.Detail}";
        new LogRowView(rowRoot).Set(entry.Timestamp.ToString("HH:mm:ss"), label, color, entry.Message, detail);
      }
    }
  }
}
