using UnityEngine;

// Attach this to your world-space icon prefabs (with SpriteRenderer, MeshRenderer, or Quad)
// so they are visible to a top-down minimap camera looking straight down.
[ExecuteAlways]
public class MinimapBillboard : MonoBehaviour
{
    [Tooltip("Optional: Assign the minimap camera. If not set, will try to find the camera with MinimapManager.")]
    public Camera minimapCamera;

    [Tooltip("If true, the icon rotates with the camera/player yaw; otherwise it always points up.")]
    public bool rotateWithYaw = false;

    private Camera _cached;

    void LateUpdate()
    {
        var cam = ResolveCamera();
        if (cam == null) return;

        // Make the icon face upward (lie on XZ plane). Optionally align yaw with camera.
        float yaw = rotateWithYaw ? cam.transform.eulerAngles.y : 0f;
        transform.rotation = Quaternion.Euler(90f, yaw, 0f);
    }

    private Camera ResolveCamera()
    {
        if (minimapCamera != null) return minimapCamera;
        if (_cached != null) return _cached;

    MinimapManager mm;
#if UNITY_2023_1_OR_NEWER
    mm = Object.FindFirstObjectByType<MinimapManager>();
#else
    mm = Object.FindObjectOfType<MinimapManager>();
#endif
        if (mm != null) _cached = mm.GetComponent<Camera>();
        if (_cached == null) _cached = Camera.main;
        return _cached;
    }
}
