using UnityEngine;
using UnityEngine.UI;

[ExecuteAlways]
public class PlayerInBoxChecker : MonoBehaviour
{
    public Camera mainCamera;
    public Transform player;
    public Image boxImage;
    public LayerMask playerLayer;
    public float maxDistance = 100f;

    [Header("BoxCast Settings")]
    public Vector2 raycastViewportPoint = new Vector2(0.5f, 0.5f);
    public Vector3 halfExtents = new Vector3(1f, 1f, 1f); // You control this manually

    private Ray ray;
    private bool hitPlayer;

    void Update()
    {
        if (mainCamera == null || player == null) return;

        ray = mainCamera.ViewportPointToRay(new Vector3(raycastViewportPoint.x, raycastViewportPoint.y, 0f));
        hitPlayer = false;

        if (Physics.BoxCast(ray.origin, halfExtents, ray.direction, out RaycastHit hit, mainCamera.transform.rotation, maxDistance, playerLayer))
        {
            if (hit.transform == player)
            {
                hitPlayer = true;
            }
        }

        if (boxImage != null)
        {
            boxImage.color = hitPlayer ? Color.green : Color.red;
        }
    }

    private void OnDrawGizmos()
    {
        if (mainCamera == null) return;

        Gizmos.color = hitPlayer ? Color.green : Color.red;
        Gizmos.matrix = Matrix4x4.TRS(ray.origin + ray.direction * (maxDistance * 0.5f), mainCamera.transform.rotation, Vector3.one);
        Gizmos.DrawWireCube(Vector3.zero, halfExtents * 2f);
    }
}