using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.EventSystems;

public class UIDragSpawner : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    public RectTransform rectTransform;
    public GameObject prefabToSpawn;   
    public LayerMask mask;
    private GameObject dragPreview;
    private CanvasGroup canvasGroup;

    void Awake()
    {
        canvasGroup = gameObject.GetOrAddComponent<CanvasGroup>();
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        if (canvasGroup == null)
            canvasGroup = gameObject.AddComponent<CanvasGroup>();
        canvasGroup.alpha = 0.6f;
        canvasGroup.blocksRaycasts = false;

        dragPreview = Instantiate(prefabToSpawn); 
    }

    public void OnDrag(PointerEventData eventData)
    {
        if (dragPreview)
        {
            Ray ray = Camera.main.ScreenPointToRay(eventData.position);
            if (Physics.Raycast(ray, out RaycastHit hit, 100.0f, mask))
            {
                dragPreview.transform.position = hit.point; 
            } 
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        canvasGroup.alpha = 1f;
        canvasGroup.blocksRaycasts = true;

        if (IsPointerOverScrollRect(rectTransform))
        {
            Destroy(dragPreview);
            dragPreview = null;
        }  
    } 
    public bool IsPointerOverScrollRect(RectTransform rt)
    {
        return RectTransformUtility.RectangleContainsScreenPoint(rt, Input.mousePosition);
    }
}
