using UnityEngine;

public class HostageRescue : MonoBehaviour
{
    public float rescueDistance = 3f;
    public float escapeDistance = 15f;
    public float runSpeed = 5f;

    private Transform player;
    private bool rescued;
    private Vector3 escapeDirection;
    private Vector3 startPosition;

    void Start()
    {
        PlayerHealth playerHealth = FindFirstObjectByType<PlayerHealth>();
        if (playerHealth != null) player = playerHealth.transform;

        startPosition = transform.position;
    }

    void Update()
    {
        if (PauseMenu.GameIsPaused || player == null) return;

        if (rescued)
        {
            transform.position += escapeDirection * runSpeed * Time.deltaTime;
            if (Vector3.Distance(startPosition, transform.position) >= escapeDistance)
                enabled = false;
            return;
        }

        if (Vector3.Distance(transform.position, player.position) <= rescueDistance &&
            Input.GetKeyDown(KeyCode.E))
        {
            RunAway();
        }
    }

    void RunAway()
    {
        rescued = true;
        startPosition = transform.position;
        escapeDirection = (transform.position - player.position).normalized;
        escapeDirection.y = 0f;
        transform.rotation = Quaternion.LookRotation(escapeDirection);
    }
}
