using FishNet.Object;
using FishNet.Object.Synchronizing;
using UnityEngine;

namespace IStalk.Core
{
    public class Altar : NetworkBehaviour
    {
        [SerializeField] private ParticleSystem _idleVfx;
        [SerializeField] private ParticleSystem _activeVfx;
        [SerializeField] private Light _glowLight;
        [SerializeField] private float _glowIntensityIdle = 1f;
        [SerializeField] private float _glowIntensityActive = 4f;
        [SerializeField] private AudioSource _ambientAudio;

        private readonly SyncVar<bool> _extractionReady = new();
        private float _pulseTimer;

        public override void OnStartClient()
        {
            base.OnStartClient();
            _extractionReady.OnChange += OnExtractionStateChanged;
            UpdateVisuals(false);
        }

        public override void OnStartServer()
        {
            base.OnStartServer();
            var extraction = FindAnyObjectByType<ExtractionManager>();
            if (extraction != null)
                extraction.OnExtractionThresholdMet += () => _extractionReady.Value = true;
        }

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

            _pulseTimer += Time.deltaTime;
            if (_glowLight != null)
            {
                float baseIntensity = _extractionReady.Value ? _glowIntensityActive : _glowIntensityIdle;
                float pulse = 1f + Mathf.Sin(_pulseTimer * 2f) * 0.2f;
                _glowLight.intensity = baseIntensity * pulse;
            }
        }

        private void OnExtractionStateChanged(bool prev, bool next, bool asServer)
        {
            UpdateVisuals(next);
        }

        private void UpdateVisuals(bool ready)
        {
            if (_idleVfx != null)
            {
                if (ready) _idleVfx.Stop();
                else _idleVfx.Play();
            }
            if (_activeVfx != null)
            {
                if (ready) _activeVfx.Play();
                else _activeVfx.Stop();
            }
            if (_glowLight != null)
                _glowLight.color = ready ? Color.green : Color.cyan;
        }
    }
}
