using System;
using UnityEngine;
using UnityEngine.Events;

namespace Infrastructure.Unity
{
    public class BeatPulseController : MonoBehaviour
    {
        [Header("Music Settings")]
        [Tooltip("Beats Per Minute of your track")]
        [SerializeField] private float bpm = 90f; 
        [Tooltip("Delay in seconds to sync the first beat with the music start")]
        [SerializeField] private float startDelay = 0.0f;
        
        [Header("Events")]
        public UnityEvent OnBeat;       // Fires every beat (1, 2, 3, 4)
        public UnityEvent OnMeasure;    // Fires every 4th beat (The Drop)
        
        private float _beatInterval;
        private float _timer;
        private int _beatCount;
        private bool _isRunning;

        private void Start()
        {
            if (bpm > 0) _beatInterval = 60f / bpm;
        }
        
        public void BeginTracking()
        {
            _timer = -startDelay;
            _beatCount = 0;
            _isRunning = true;
        }

        public void StopTracking()
        {
            _isRunning = false;
        }
        
        private void Update()
        {
            if (!_isRunning) return;

            _timer += Time.deltaTime;

            if (_timer >= _beatInterval)
            {
                _timer -= _beatInterval;
                Pulse();
            }
        }

        private void Pulse()
        {
            _beatCount++;
            
            OnBeat?.Invoke();

            if (_beatCount % 4 == 0)
            {
                OnMeasure?.Invoke();
            }
        }
    }
}