using UnityEngine;

public class FlyEnemyMovement : Entity
{
    [SerializeField] private float detectionRange = 8.0f;
    [SerializeField] private float moveSpeed = 3.0f; 
    [SerializeField] private LayerMask obstacleLayer;

    private GameObject playerObject;

    protected override void Awake()
    {
        base.Awake();
    }

    private void Start()
    {
        playerObject = GameObject.FindWithTag("Player");
    }

    public override void RunAI()
    {
        if (playerObject != null)
        {
            float distance = Vector3.Distance(transform.position, playerObject.transform.position);
            if (distance <= detectionRange)
            {
                MoveTowardsPlayer();
            }
        }
    }

    private void MoveTowardsPlayer()
    {
        Vector3 direction = (playerObject.transform.position - transform.position).normalized;
        RaycastHit2D hit = Physics2D.Raycast(transform.position, direction, 1.0f, obstacleLayer);

        if (hit.collider != null)
        {
            Vector2 tangent = Vector2.Perpendicular(hit.normal);
            direction = Vector3.Lerp(direction, tangent, 0.5f).normalized;
        }

        transform.position += direction * moveSpeed * Time.deltaTime;

        if (direction.x != 0)
        {
            transform.localScale = new Vector3(direction.x > 0 ? 1 : -1, 1, 1);
        }

    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, detectionRange);
    }
}