using System.Collections;
using UnityEngine;

public class EnemyShooter : MonoBehaviour
{
    public float moveSpeed = 2f;
    public float shootInterval = 2f;
    public GameObject bulletPrefab;
    public Transform gunTransform;
    public Transform firePoint;
    public float bulletSpeed = 10f;
    public float detectionRange = 10f;

    private Transform player;
    private Rigidbody2D rb;
    private bool facingRight = true;

    private void Awake()
    {
        player = FindObjectOfType<PlayerMovement>().transform;
        rb = GetComponent<Rigidbody2D>();
    }

    void Start()
    {
        StartCoroutine(ShootAtIntervals());
    }

    void Update()
    {
        if (PlayerInRange())
        {
            AimAtPlayer();
        }
    }

    private void FixedUpdate()
    {
        if (PlayerInRange())
        {
            FollowPlayer();
        }
    }

    private bool PlayerInRange()
    {
        return Vector2.Distance(transform.position, player.position) <= detectionRange;
    }

    private void FollowPlayer()
    {
        Vector2 direction = (player.position - transform.position).normalized;


        if ((direction.x > 0 && !facingRight) || (direction.x < 0 && facingRight))
        {
            Flip();
        }
    }

    /* This code I used AI for */
    private void AimAtPlayer()
    {
        Vector2 direction = player.position - gunTransform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

        if (!facingRight)
        {
            angle += 180;
        }

        gunTransform.rotation = Quaternion.Euler(new Vector3(0, 0, angle));
    }

    private void Flip()
    {
        facingRight = !facingRight;
        Vector3 theScale = transform.localScale;
        theScale.x *= -1;
        transform.localScale = theScale;
        firePoint.Rotate(0f, 180f, 0f);
    }

    private IEnumerator ShootAtIntervals()
    {
        while (true)
        {
            yield return new WaitForSeconds(shootInterval);
            if (PlayerInRange())
            {
                Shoot();
            }
        }
    }

    private void Shoot()
    {

        GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);

        Rigidbody2D bulletRb = bullet.GetComponent<Rigidbody2D>();


        bulletRb.velocity = firePoint.right * bulletSpeed;
    }
}
