using UnityEngine;
using UnityEngine.UI;
using FishNet.Object;

namespace IStalk.UI
{
    public class Minimap : NetworkBehaviour
    {
        [SerializeField] private Camera _minimapCamera;
        [SerializeField] private RawImage _minimapDisplay;
        [SerializeField] private float _minimapZoom = 30f;
        [SerializeField] private float _minimapHeight = 50f;

        private Transform _target;
        private RenderTexture _rt;

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

            _target = transform;
            SetupRenderTexture();
        }

        private void SetupRenderTexture()
        {
            if (_minimapCamera == null) return;

            _rt = new RenderTexture(256, 256, 16);
            _minimapCamera.targetTexture = _rt;
            _minimapCamera.orthographic = true;
            _minimapCamera.orthographicSize = _minimapZoom;
            _minimapCamera.cullingMask = ~0;

            if (_minimapDisplay != null)
                _minimapDisplay.texture = _rt;
        }

        private void LateUpdate()
        {
            if (!IsOwner || _minimapCamera == null || _target == null) return;

            Vector3 pos = _target.position;
            pos.y = _minimapHeight;
            _minimapCamera.transform.position = pos;
            _minimapCamera.transform.rotation = Quaternion.Euler(90f, 0f, 0f);
        }

        private void OnDestroy()
        {
            if (_rt != null)
            {
                _rt.Release();
                Destroy(_rt);
            }
        }
    }
}
