using FishNet.Object;
using UnityEngine;
using IStalk.Core;
using IStalk.Data;

namespace IStalk.Eye
{
    public class EyeCameraController : NetworkBehaviour
    {
        [SerializeField] private Camera _camera;

        private GlobalRules_SO Rules => GlobalRules_SO.Instance;
        private Bounds _panBounds;
        private float _currentZoom;
        private Vector3 _targetPosition;

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

            _currentZoom = (Rules.zoomMin + Rules.zoomMax) / 2f;
            _camera.orthographicSize = _currentZoom;

            var mapGen = FindAnyObjectByType<MapGenerator>();
            if (mapGen != null)
            {
                _panBounds = mapGen.GetMapBounds();
                _targetPosition = mapGen.GetMapCenter();
            }
            else
            {
                _panBounds = new Bounds(Vector3.zero, Vector3.one * 100);
                _targetPosition = Vector3.zero;
            }

            _camera.transform.rotation = Quaternion.Euler(90f, 0f, 0f);
        }

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

            HandlePan();
            HandleZoom();
            ApplyPosition();
        }

        private void HandlePan()
        {
            float h = Input.GetAxisRaw("Horizontal");
            float v = Input.GetAxisRaw("Vertical");

            if (Input.GetMouseButton(2))
            {
                h -= Input.GetAxis("Mouse X") * 2f;
                v -= Input.GetAxis("Mouse Y") * 2f;
            }

            Vector3 move = new Vector3(h, 0, v).normalized * Rules.panSpeed * Time.deltaTime;
            _targetPosition += move;

            _targetPosition.x = Mathf.Clamp(_targetPosition.x, _panBounds.min.x, _panBounds.max.x);
            _targetPosition.z = Mathf.Clamp(_targetPosition.z, _panBounds.min.z, _panBounds.max.z);
        }

        private void HandleZoom()
        {
            float scroll = Input.mouseScrollDelta.y;
            if (Mathf.Abs(scroll) > 0.01f)
            {
                _currentZoom -= scroll * Rules.zoomSpeed;
                _currentZoom = Mathf.Clamp(_currentZoom, Rules.zoomMin, Rules.zoomMax);
                _camera.orthographicSize = _currentZoom;
            }
        }

        private void ApplyPosition()
        {
            Vector3 camPos = _targetPosition;
            camPos.y = 50f;
            _camera.transform.position = Vector3.Lerp(_camera.transform.position, camPos, Time.deltaTime * 10f);
        }
    }
}
