using FishNet.Object;
using UnityEngine;

namespace Players
{
    public sealed class PlayerRevealController : NetworkBehaviour
    {
        private static readonly int RevealCenterId = Shader.PropertyToID("_RevealCenter");
        private static readonly int RevealRadiusId = Shader.PropertyToID("_GlobalRevealRadius");
        private static readonly int RevealEdgeSoftnessId = Shader.PropertyToID("_GlobalRevealEdgeSoftness");

        [SerializeField] private Transform _center;
        [SerializeField, Min(0f)] private float _revealRadius = 6f;
        [SerializeField, Min(0.001f)] private float _edgeSoftness = 1f;
        [SerializeField] private Vector3 _centerOffset;

        public override void OnStartClient()
        {
            base.OnStartClient();
            UpdateShaderGlobals();
        }

        public override void OnStopClient()
        {
            if (IsOwner)
                ClearShaderGlobals();

            base.OnStopClient();
        }

        private void LateUpdate()
        {
            if (!IsOwner)
                return;

            UpdateShaderGlobals();
        }

        private void OnDisable()
        {
            if (IsOwner)
                ClearShaderGlobals();
        }

        private void UpdateShaderGlobals()
        {
            if (!IsOwner)
                return;

            Transform center = _center != null ? _center : transform;
            Vector3 worldCenter = center.position + _centerOffset;

            Shader.SetGlobalVector(RevealCenterId, new Vector4(worldCenter.x, worldCenter.y, worldCenter.z, 1f));
            Shader.SetGlobalFloat(RevealRadiusId, _revealRadius);
            Shader.SetGlobalFloat(RevealEdgeSoftnessId, _edgeSoftness);
        }

        private void ClearShaderGlobals()
        {
            Shader.SetGlobalVector(RevealCenterId, Vector4.zero);
            Shader.SetGlobalFloat(RevealRadiusId, 0f);
            Shader.SetGlobalFloat(RevealEdgeSoftnessId, 0f);
        }
    }
}
