using FishNet.Object;
using UnityEngine;

namespace Players
{
    public sealed class PlayerMoving : NetworkBehaviour
    {
        [SerializeField] private float _moveSpeed = 5f;
        [SerializeField] private CharacterController _characterController;

        private Transform _cameraTransform;

        private void Awake()
        {
            Camera playerCamera = GetComponentInChildren<Camera>(true);
            if (playerCamera != null)
                _cameraTransform = playerCamera.transform;
        }
        
        private void Update()
        {
            if (!IsOwner)
                return;
            
            float horizontal = Input.GetAxisRaw("Horizontal");
            float vertical = Input.GetAxisRaw("Vertical");

            Transform directionSource = _cameraTransform != null ? _cameraTransform : transform;
            Vector3 forward = Vector3.ProjectOnPlane(directionSource.forward, Vector3.up).normalized;
            Vector3 right = Vector3.ProjectOnPlane(directionSource.right, Vector3.up).normalized;
            Vector3 moveDirection = (right * horizontal + forward * vertical).normalized;
            Vector3 offset = moveDirection * (_moveSpeed * Time.deltaTime);

            _characterController.Move(offset);
        }
    }
}
