using UnityEngine;
using UnityEngine.UIElements;

namespace LiveOpsExamples
{
  public class BootOverlayPanel : MonoBehaviour
  {
    private const float SpinnerDegreesPerSecond = 180f;

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

    private VisualElement _overlay;
    private Label _statusLabel;
    private VisualElement _spinner;
    private IVisualElementScheduledItem _spinSchedule;
    private float _angle;
    private float _lastTick;

    private void OnEnable()
    {
      panelRenderer.RegisterUIReloadCallback(OnUIReload);
      controller.PhaseChanged += ApplyVisibility;
    }

    private void OnDisable()
    {
      panelRenderer.UnregisterUIReloadCallback(OnUIReload);
      controller.PhaseChanged -= ApplyVisibility;
      _spinSchedule?.Pause();
    }

    private void OnUIReload(PanelRenderer renderer, VisualElement root)
    {
      _overlay = root.Q<VisualElement>("boot-overlay");
      _statusLabel = root.Q<Label>("boot-status");
      _spinner = root.Q<VisualElement>("boot-spinner");
      _spinSchedule = _spinner.schedule.Execute(Spin).Every(16);
      ApplyVisibility();
    }

    private void Update()
    {
      _statusLabel.text = controller.StatusMessage;
    }

    private void Spin()
    {
      var now = Time.unscaledTime;
      _angle = (_angle + SpinnerDegreesPerSecond * (now - _lastTick)) % 360f;
      _lastTick = now;
      _spinner.style.rotate = new Rotate(Angle.Degrees(_angle));
    }

    private void ApplyVisibility()
    {
      var visible = controller.Phase == CozyPhase.Booting || controller.Phase == CozyPhase.Connecting;
      _overlay.style.display = visible ? DisplayStyle.Flex : DisplayStyle.None;
      if (visible)
      {
        _lastTick = Time.unscaledTime;
        _spinSchedule.Resume();
      }
      else
      {
        _spinSchedule.Pause();
      }
    }
  }
}
