using UnityEngine;
using KBCore.Refs;

namespace Infrastructure.Unity
{
    [RequireComponent(typeof(Rigidbody))]
    public class HunterNpcController : MonoBehaviour
    {
        [SerializeField] private float moveSpeed = 7f;
        [SerializeField] private LayerMask tileLayer;
        
        [Self] [SerializeField] private Rigidbody rb;
        
        private PlayerController _target;
        
        public void Initialize(PlayerController target)
        {
            _target = target;
        }

        private void FixedUpdate()
        {
            if (_target == null) return;
            
            if (IsGrounded())
            {
                var direction = (_target.transform.position - transform.position).normalized;
                // Flatten direction to avoid flying/digging
                direction.y = 0; 
                direction.Normalize();
                
                rb.MovePosition(rb.position + direction * (moveSpeed * Time.fixedDeltaTime));
            }
            
            // Trigger tiles
            if (Physics.Raycast(transform.position, Vector3.down, out var hit, 1.5f, tileLayer))
            {
                if (hit.collider.TryGetComponent<TileViewAdapter>(out var tile))
                {
                    tile.OnPlayerStep();
                }
            }
        }
        
        private bool IsGrounded()
        {
            return Physics.Raycast(transform.position, Vector3.down, out var hit, 1.15f, tileLayer);
        }
        
        private void OnDrawGizmos()
        {
            if (_target)
            {
                Gizmos.color = Color.red;
                Gizmos.DrawLine(transform.position, _target.transform.position);
            }
        }
    }
}
