using UnityEngine;

public class LineTouchDetector : MonoBehaviour
{
    public LineRenderer lineRenderer;
    public float touchRadius = 0.5f; // Max distance to detect a touch

    private ScrollingLineRenderer scrollingLineRenderer;

    private void Start()
    {
        scrollingLineRenderer = GetComponentInParent<ScrollingLineRenderer>();
    }

    private void Update()
    {
        DetectTouchOrClick();
    }

    private void DetectTouchOrClick()
    {
        Vector3 touchPos;
        bool touched = false;

        // Detect touch on mobile
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            touchPos = touch.position;
            touched = true;
        }
        // Detect mouse click on PC
        else if (Input.GetMouseButtonDown(0))
        {
            touchPos = Input.mousePosition;
            touched = true;
        }
        else
        {
            return; // No input detected
        }

        // Convert screen position to world position
        Ray ray = Camera.main.ScreenPointToRay(touchPos);
        if (Physics.Raycast(ray, out RaycastHit hit, 100f))
        {
            // Check if the touch is close to the LineRenderer
            if (IsTouchNearLine(hit.point))
            {
                Debug.Log("[LineTouchDetector] Line touched! Sending decision to server...");
                scrollingLineRenderer.SendDecisionToServer();
            }
        }
    }

    private bool IsTouchNearLine(Vector3 touchPoint)
    {
        float minDistance = float.MaxValue;
        Vector3[] positions = new Vector3[lineRenderer.positionCount];
        lineRenderer.GetPositions(positions);

        for (int i = 0; i < positions.Length - 1; i++)
        {
            float dist = DistanceFromPointToLineSegment(touchPoint, positions[i], positions[i + 1]);
            if (dist < minDistance)
            {
                minDistance = dist;
            }
        }

        return minDistance <= touchRadius;
    }

    private float DistanceFromPointToLineSegment(Vector3 point, Vector3 lineStart, Vector3 lineEnd)
    {
        Vector3 closestPoint = ClosestPointOnLineSegment(point, lineStart, lineEnd);
        return Vector3.Distance(point, closestPoint);
    }

    private Vector3 ClosestPointOnLineSegment(Vector3 point, Vector3 a, Vector3 b)
    {
        Vector3 ap = point - a;
        Vector3 ab = b - a;
        float ab2 = ab.sqrMagnitude;
        float ap_ab = Vector3.Dot(ap, ab);
        float t = Mathf.Clamp01(ap_ab / ab2);
        return a + ab * t;
    }
}