using System.Runtime.InteropServices;
using UnityEngine;

public class MouseExplorationRotator : MonoBehaviour
{
    
#if UNITY_WEBGL && !UNITY_EDITOR
    [DllImport("__Internal")]
    private static extern int IsMobileBrowser();
#endif
    public float maxRotationAngle = 5f; // Max rotation in degrees for each axis
    public float rotationSmoothness = 5f;

    private Quaternion initialRotation;

    void Start()
    {       
        
#if UNITY_WEBGL && !UNITY_EDITOR
        bool isMobile = IsMobileBrowser() == 1;
        if (isMobile) {
            // Adjust settings for mobile browsers
            maxRotationAngle = maxRotationAngle * 2; // Reduce rotation for mobile
        }
        Debug.Log("WebGL running on " + (isMobile ? "Mobile" : "Desktop") + " browser.");
#else
        Debug.Log("Not WebGL or running in Editor.");
#endif

        initialRotation = transform.rotation;
    }

    void Update()
    {
        // Get mouse position relative to screen center (-0.5 to +0.5 range)
        Vector2 mousePosNormalized = new Vector2(
            (Input.mousePosition.x / Screen.width) - 0.5f,
            (Input.mousePosition.y / Screen.height) - 0.5f
        );

        // Clamp to 10% of the screen range
        mousePosNormalized = Vector2.ClampMagnitude(mousePosNormalized, 0.40f);

        // Calculate target rotation
        float targetX = -mousePosNormalized.y * maxRotationAngle; // invert for natural tilt
        float targetY = mousePosNormalized.x * maxRotationAngle;

        Quaternion targetRotation = Quaternion.Euler(targetX, targetY, 0f);

        // Smoothly rotate towards target
        transform.rotation = Quaternion.Slerp(transform.rotation, initialRotation * targetRotation, Time.deltaTime * rotationSmoothness);
    }
}