using UnityEngine;

namespace NBF
{
    public class JointPinchController : MonoBehaviour
    {
        // 配置参数
        [SerializeField] private float moveSpeed = 5f;
        [SerializeField] private float snapDistance = 0.1f;

        // 组件引用
        private SpringJoint originalSpringJoint;
        private FixedJoint pinchJoint;
        private Rigidbody rb;


        private Transform targetTransform;
        private float originalSpring;

        public bool isPinched { get; private set; }


        private bool moveToTargetDone;
        private float _speed;

        void Start()
        {
            rb = GetComponent<Rigidbody>();
            originalSpringJoint = GetComponent<SpringJoint>();
        }

        void FixedUpdate()
        {
            if (isPinched && targetTransform != null)
            {
                transform.position =
                    Vector3.MoveTowards(transform.position, targetTransform.position, Time.deltaTime * _speed);
                if (!moveToTargetDone)
                {
                    if (Vector3.Distance(transform.position, targetTransform.position) < 0.1f)
                    {
                        moveToTargetDone = true;
                    }
                }

                if (moveToTargetDone)
                {
                    transform.position = targetTransform.position;
                }
            }
        }

        // 外部调用：开始捏住流程
        public void StartPinch(Transform fingerTransform, float speed = 3)
        {
            _speed = speed;
            Rigidbody fingerRb = fingerTransform.GetComponent<Rigidbody>();
            if (fingerRb == null)
            {
                Debug.LogError("目标必须带有Rigidbody");
                return;
            }

            isPinched = true;
            rb.useGravity = false;
            rb.isKinematic = true;
            moveToTargetDone = false;
            targetTransform = fingerTransform;
        }


        // 外部调用：释放捏住
        public void ReleasePinch()
        {
            isPinched = false;
            rb.useGravity = true;
            rb.isKinematic = false;
            targetTransform = null;
        }
    }
}