using System;
using UnityEngine;

// Responsible ONLY for physics, movement, and facing direction
[RequireComponent(typeof(Rigidbody2D))]
public class EnemyMotor : MonoBehaviour
{
    private Rigidbody2D _rb;
    private Transform _transform;
    private Transform _spriteTransform;
    private bool _facingRight = true;
    
    public void Initialize(Transform spriteTransform)
    {
        _rb = GetComponent<Rigidbody2D>();
        _transform = transform;
        _spriteTransform = spriteTransform;
    }
    
    public void MoveTowardsSlot(Vector2 targetPosition, float speed, float tolerance)
    {
        Vector2 pos = _rb.position;
        Vector2 direction = (targetPosition - pos).normalized;
        float distance = Vector2.Distance(pos, targetPosition);

        if (distance > tolerance)
        {
            _rb.MovePosition(pos + direction * (speed * Time.fixedDeltaTime));
        }
    }
    
    public void Retreat(Vector2 targetPosition, float speed)
    {
        Vector2 pos = _rb.position;
        Vector2 direction = (pos - targetPosition).normalized;

        _rb.MovePosition(pos + direction * (speed * Time.fixedDeltaTime));
    }
    
    public void HandleFacing(float targetX)
    {
        float dirX = targetX - _transform.position.x;
        if (dirX > 0 && !_facingRight) Flip();
        else if (dirX < 0 && _facingRight) Flip();
    }
    
    private void Flip()
    {
        _facingRight = !_facingRight;
        Vector3 scale = _spriteTransform.localScale;
        scale.x *= -1;
        _spriteTransform.localScale = scale;
    }
}