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

namespace IStalk.Shared
{
    public class PingSystem : NetworkBehaviour
    {
        [SerializeField] private GameObject _pingMarkerPrefab;
        [SerializeField] private float _pingCooldown = 3f;
        [SerializeField] private float _pingLifetime = 5f;
        [SerializeField] private AudioClip _pingSound;

        private float _cooldownTimer;

        public override void OnStartClient()
        {
            base.OnStartClient();
            if (!IsOwner)
            {
                enabled = false;
                return;
            }
        }

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

            _cooldownTimer -= Time.deltaTime;
            if (_cooldownTimer > 0) return;

            if (Input.GetKeyDown(KeyCode.Z))
            {
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                if (Physics.Raycast(ray, out RaycastHit hit, 100f))
                {
                    ServerPing(hit.point);
                    _cooldownTimer = _pingCooldown;
                }
            }
        }

        [ServerRpc]
        private void ServerPing(Vector3 position)
        {
            ShowPingObservers(position, Owner.ClientId);
        }

        [ObserversRpc]
        private void ShowPingObservers(Vector3 position, int senderId)
        {
            if (_pingMarkerPrefab != null)
            {
                var marker = Instantiate(_pingMarkerPrefab, position, Quaternion.identity);
                Destroy(marker, _pingLifetime);
            }

            if (_pingSound != null)
                AudioSource.PlayClipAtPoint(_pingSound, position, 0.7f);
        }
    }
}
