using UnityEngine;
using System.Collections.Generic;

public class GroundEnemyMovement : Entity
{
    [SerializeField] private Rigidbody2D rigidBody;
    [SerializeField] private SpriteRenderer spriteRenderer;
    [SerializeField] private float Speed = 3f;
    [SerializeField] private float startDirection = 1.5f;
    [SerializeField] private LayerMask terrainLayer;

    private float currentDirection;
    private float halfWidth;
    private Vector2 movement; 

    private void Start()
    {
        halfWidth = spriteRenderer.bounds.extents.x;
        currentDirection = startDirection > 0 ? 1f : -1f;
        spriteRenderer.flipX = currentDirection == 1 ? false : true;
    }

    public override void RunAI()
    {
        movement.x = Speed * currentDirection;
        movement.y = rigidBody.linearVelocity.y;
        rigidBody.linearVelocity = movement;

        SetDirection();
    }

    private void SetDirection()
    {
        Vector2 frontVec = transform.position;
        Vector2 wallDir = Vector2.right;

        if (currentDirection > 0)
        {
            frontVec += Vector2.right * halfWidth;
            wallDir = Vector2.right;
        }
        else
        {
            frontVec += Vector2.left * halfWidth;
            wallDir = Vector2.left;
        }

        RaycastHit2D cliffHit = Physics2D.Raycast(frontVec, Vector2.down, 1f, terrainLayer);
        Debug.DrawRay(frontVec, Vector2.down * 1f, Color.green);

        float wallDist = halfWidth + 0.2f;
        RaycastHit2D wallHit = Physics2D.Raycast(transform.position, wallDir, wallDist, terrainLayer);
        Debug.DrawRay(transform.position, wallDir * wallDist, Color.blue);

        if (cliffHit.collider == null || wallHit.collider != null)
        {
            currentDirection *= -1;
            spriteRenderer.flipX = !spriteRenderer.flipX;
        }
    }
}
