using UnityEngine;
using UnityEngine.XR;

public class PhoneInteraction : MonoBehaviour
{
    public GameObject Controller;
    public GameObject Plane;

    [Header("Input")]
    [Tooltip("The XR input device to read trigger from. Leave at None for automatic detection.")]
    public XRNode inputDevice = XRNode.RightHand;

    [Tooltip("Trigger threshold to register as pressed")]
    [Range(0.1f, 0.9f)]
    public float triggerThreshold = 0.5f;

    private bool wasTouching = false;
    private bool wasTriggerPressed = false;
    private Vector2 lastNormalized;

    void Update()
    {
        var t = Controller.GetComponent<Transform>();

        // Check if ray hits the phone plane
        bool isTouching = Physics.Raycast(t.position, t.forward, out RaycastHit hit) &&
                          hit.collider == Plane.GetComponent<Collider>();

        if (isTouching)
        {
            // Calculate normalized UV coordinates
            var local = Plane.transform.InverseTransformPoint(hit.point);
            var normalized = new Vector2((local.x + 5) / 10, (local.z + 5) / 10);
            lastNormalized = new Vector2(normalized.x, 1 - normalized.y);

            // Check trigger input
            bool triggerPressed = IsTriggerPressed();

            if (triggerPressed)
            {
                if (!wasTriggerPressed)
                {
                    // Trigger just pressed - send touch down
                    KotlinBridge.SendTouchDown(lastNormalized.x, lastNormalized.y);
                }
                else
                {
                    // Trigger held - send touch move
                    KotlinBridge.SendTouchMove(lastNormalized.x, lastNormalized.y);
                }
            }
            else if (wasTriggerPressed)
            {
                // Trigger just released - send touch up
                KotlinBridge.SendTouchUp(lastNormalized.x, lastNormalized.y);
            }

            wasTriggerPressed = triggerPressed;
        }
        else if (wasTriggerPressed)
        {
            // Lost contact while touching - send touch up at last position
            KotlinBridge.SendTouchUp(lastNormalized.x, lastNormalized.y);
            wasTriggerPressed = false;
        }

        wasTouching = isTouching;
    }

    private bool IsTriggerPressed()
    {
        // Try to get trigger value from XR input
        InputDevice device = InputDevices.GetDeviceAtXRNode(inputDevice);
        if (device.isValid)
        {
            if (device.TryGetFeatureValue(CommonUsages.trigger, out float triggerValue))
            {
                return triggerValue > triggerThreshold;
            }
            if (device.TryGetFeatureValue(CommonUsages.triggerButton, out bool triggerButton))
            {
                return triggerButton;
            }
        }

        // Fallback to Unity's legacy input (for testing in editor)
        return Input.GetMouseButton(0);
    }
}
