using FishNet.Object;
using FishNet.Object.Synchronizing;
using IStalk.Data;

namespace IStalk.Eye
{
    public class DreadEconomy : NetworkBehaviour
    {
        private readonly SyncVar<float> _currentDread = new(new SyncTypeSettings(0.1f));
        private float _noiseBonus;
        private float _maxDread = 200f;

        private GlobalRules_SO Rules => GlobalRules_SO.Instance;

        public float CurrentDread => _currentDread.Value;
        public float MaxDread => _maxDread;

        public event System.Action<float> OnDreadChanged;

        public override void OnStartNetwork()
        {
            base.OnStartNetwork();
            _currentDread.OnChange += HandleDreadSynced;
        }

        public override void OnStartServer()
        {
            base.OnStartServer();
            _currentDread.Value = Rules.dreadStartingAmount;
        }

        private void HandleDreadSynced(float prev, float next, bool asServer)
        {
            OnDreadChanged?.Invoke(next);
        }

        private void Update()
        {
            if (!IsServerStarted) return;

            float baseRegen = _regenOverride >= 0 ? _regenOverride : Rules.dreadBaseRegenRate;
            float regen = baseRegen + _noiseBonus;
            _currentDread.Value = UnityEngine.Mathf.Min(_currentDread.Value + regen * UnityEngine.Time.deltaTime, _maxDread);
            _noiseBonus *= 0.95f;
        }

        [Server]
        public bool TrySpend(float amount)
        {
            if (_currentDread.Value < amount) return false;
            _currentDread.Value -= amount;
            return true;
        }

        [Server]
        public void AddNoiseBonus(float intensity)
        {
            _noiseBonus += intensity * Rules.dreadNoiseBonusMultiplier;
        }

        [Server]
        public void ApplyStartOverride(float amount)
        {
            _currentDread.Value = amount;
        }

        [Server]
        public void ApplyRegenOverride(float rate)
        {
            _regenOverride = rate;
        }

        private float _regenOverride = -1f;
    }
}
