using UnityEngine;

public class FloatingDraggableRock : MonoBehaviour
{
    [Header("Floating Settings")]
    [SerializeField] float floatSpeed = 0.5f;

    private Vector3 targetPos;
    private bool isDragging = false;
    private Vector3 dragOffset;
    private float zCoord;
    private Camera cam;

    void Start()
    {
        cam = Camera.main;
        PickNewScreenTarget();
    }

    void Update()
    {
        if (!isDragging)
        {

            transform.position = Vector3.MoveTowards(transform.position, targetPos, floatSpeed * Time.deltaTime);
            if (Vector3.Distance(transform.position, targetPos) < 0.1f)
            {
                PickNewScreenTarget();
            }
        }
    }

    void PickNewScreenTarget()
    {

        Vector2 minScreen = cam.ViewportToWorldPoint(new Vector3(0.1f, 0.1f, 0)); 
        Vector2 maxScreen = cam.ViewportToWorldPoint(new Vector3(0.9f, 0.9f, 0));

        float x = Random.Range(minScreen.x, maxScreen.x);
        float y = Random.Range(minScreen.y, maxScreen.y);

        targetPos = new Vector3(x, y, transform.position.z);
    }

    void OnMouseDown()
    {
        isDragging = true;
        zCoord = cam.WorldToScreenPoint(gameObject.transform.position).z;
        dragOffset = gameObject.transform.position - GetMouseAsWorldPoint();
    }

    void OnMouseDrag()
    {
        transform.position = GetMouseAsWorldPoint() + dragOffset;
    }

    void OnMouseUp()
    {
        isDragging = false;
        PickNewScreenTarget();
    }

    private Vector3 GetMouseAsWorldPoint()
    {
        Vector3 mousePoint = Input.mousePosition;
        mousePoint.z = zCoord;
        return cam.ScreenToWorldPoint(mousePoint);
    }
}