using FishNet.Object;
using UnityEngine;

namespace IStalk.Runner
{
    public class RunnerLook : NetworkBehaviour
    {
        [SerializeField] private Transform _cameraHolder;
        [SerializeField] private float _sensitivity = 2f;
        [SerializeField] private float _maxPitch = 85f;
        [SerializeField] private float _wallRunTiltAngle = 15f;
        [SerializeField] private float _tiltSpeed = 8f;
        [SerializeField] private float _slideFovBoost = 10f;

        private float _pitch;
        private float _yaw;
        private float _currentTilt;
        private float _baseFov;
        private Camera _cam;
        private RunnerController _runner;

        public override void OnStartClient()
        {
            base.OnStartClient();
            if (!IsOwner)
            {
                if (_cameraHolder != null)
                {
                    var cam = _cameraHolder.GetComponentInChildren<Camera>();
                    if (cam != null) cam.enabled = false;
                    var listener = _cameraHolder.GetComponentInChildren<AudioListener>();
                    if (listener != null) listener.enabled = false;
                }
                enabled = false;
                return;
            }

            _runner = GetComponent<RunnerController>();
            _cam = _cameraHolder.GetComponentInChildren<Camera>();
            if (_cam != null) _baseFov = _cam.fieldOfView;

            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
            _yaw = transform.eulerAngles.y;
        }

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

            float mx = Input.GetAxis("Mouse X") * _sensitivity;
            float my = Input.GetAxis("Mouse Y") * _sensitivity;

            _yaw += mx;
            _pitch -= my;
            _pitch = Mathf.Clamp(_pitch, -_maxPitch, _maxPitch);

            transform.rotation = Quaternion.Euler(0, _yaw, 0);

            float targetTilt = 0f;
            float targetFov = _baseFov;

            if (_runner != null)
            {
                if (_runner.IsWallRunning)
                    targetTilt = -_wallRunTiltAngle * _runner.WallRunSide;
                if (_runner.IsSliding)
                    targetFov = _baseFov + _slideFovBoost;
            }

            _currentTilt = Mathf.Lerp(_currentTilt, targetTilt, Time.deltaTime * _tiltSpeed);

            if (_cameraHolder != null)
                _cameraHolder.localRotation = Quaternion.Euler(_pitch, 0, _currentTilt);

            if (_cam != null)
                _cam.fieldOfView = Mathf.Lerp(_cam.fieldOfView, targetFov, Time.deltaTime * _tiltSpeed);
        }

        public override void OnStopClient()
        {
            base.OnStopClient();
            if (IsOwner)
            {
                Cursor.lockState = CursorLockMode.None;
                Cursor.visible = true;
            }
        }
    }
}
