using UnityEngine;

public class PlayerInteract : MonoBehaviour
{
    [SerializeField] private float interactRange = 2.5f;
    [SerializeField] private LayerMask interactableLayer;
    [SerializeField] private KeyCode interactKey = KeyCode.E;

    private InteractableObject _currentTarget;

    private void Update()
    {
        FindNearestInteractable();

        if (InputInteract() && _currentTarget != null)
        {
            _currentTarget.Interact();
        }
    }

    private bool InputInteract()
    {
        return Input.GetKeyDown(interactKey);
    }

    public void OnInteractButton()
    {
        if (_currentTarget != null)
            _currentTarget.Interact();
    }

    private void FindNearestInteractable()
    {
        Collider[] hits = Physics.OverlapSphere(transform.position, interactRange, interactableLayer);

        float closestDist = float.MaxValue;
        InteractableObject closest = null;

        foreach (var hit in hits)
        {
            var interactable = hit.GetComponent<InteractableObject>();
            if (interactable == null) continue;

            float dist = Vector3.Distance(transform.position, hit.transform.position);
            if (dist < closestDist)
            {
                closestDist = dist;
                closest = interactable;
            }
        }

        if (_currentTarget != closest)
        {
            if (_currentTarget != null) _currentTarget.SetHighlight(false);
            _currentTarget = closest;
            if (_currentTarget != null) _currentTarget.SetHighlight(true);
        }
    }

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