using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

using JumpTower;

namespace JumpTower
{
    public class OnTouch : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler
    {
        [SerializeField] private float rotationSpeed = 150f; // Fine-tuned speed
        [SerializeField] private float maxRotationSpeed = 200f; // Maximum rotation speed
        [SerializeField] private GameObject cylinder;
        [SerializeField] private EnemyMovment enemyMovment;

        private Rigidbody cylinderRb;
        private bool isDragging = false;
        private float currentRotation;
        private float targetRotation;
        private float dragThreshold = 0.2f;  // Minimum drag sensitivity
        private float dragSmoothing = 12f;    // Smoothing factor for responsiveness

        void Start()
        {
            cylinderRb = cylinder.GetComponent<Rigidbody>();
            currentRotation = cylinderRb.rotation.eulerAngles.y;
        }

        public void OnPointerDown(PointerEventData eventData)
        {
            isDragging = true;
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            isDragging = false;
        }

        public void OnDrag(PointerEventData eventData)
        {
            if (!isDragging) return;

            // Cache the drag delta to avoid repeated calculations
            float dragDelta = eventData.delta.x * rotationSpeed * Time.deltaTime;

            // Apply rotation only if the drag is significant (avoiding jittery movement)
            if (Mathf.Abs(dragDelta) > dragThreshold)
            {
                // Clamp the dragDelta to not exceed maxRotationSpeed
                dragDelta = Mathf.Clamp(dragDelta, -maxRotationSpeed, maxRotationSpeed);

                targetRotation = currentRotation + dragDelta;

                // Update enemy movement with smoother transition
                enemyMovment.changeSpeedRotation(1 - eventData.delta.x);
            }
        }

        void FixedUpdate()
        {
            if (isDragging)
            {
                // Smoothly interpolate between the current and target rotation using Lerp
                currentRotation = Mathf.Lerp(currentRotation, targetRotation, Time.fixedDeltaTime * dragSmoothing);

                // Apply the smooth rotation to the Rigidbody
                cylinderRb.MoveRotation(Quaternion.Euler(0, currentRotation, 0));
            }
        }
    }
}
