using Unity.Netcode;
using UnityEngine;

[RequireComponent(typeof(CharacterController))]
public class OVRStickAndRoomscaleMovement : NetworkBehaviour
{
    public float speed = 2.0f;
    public float gravity = -9.81f;
    public Transform cameraTransform; // CenterEyeAnchor
    public Transform rigRoot;         // OVRCameraRig Root – wichtig für Höhe!

    private CharacterController characterController;
    private Vector3 velocity;

    public float minHeight = 1.0f;  // Kleinster Collider
    public float maxHeight = 2.2f;  // Größter Collider
    public float skinWidth = 0.05f; // Charaktercontroller-Skin

    void Start()
    {
        //if (!IsOwner) return;

        characterController = GetComponent<CharacterController>();

        if (cameraTransform == null && Camera.main != null)
            cameraTransform = Camera.main.transform;
    }

    void Update()
    {
        //if (!IsOwner) return;

        // 1. Real-World Position des Headsets bestimmen
        Vector3 headLocalPos = rigRoot.InverseTransformPoint(cameraTransform.position);

        // 2. Höhe anpassen (Stehen, Hocken)
        float height = Mathf.Clamp(headLocalPos.y, minHeight, maxHeight);
        characterController.height = height;

        // 3. Center des CharacterControllers so setzen, dass er immer den Spieler umschließt
        characterController.center = new Vector3(headLocalPos.x, height / 2f + characterController.skinWidth, headLocalPos.z);

        // 4. Stick Movement
        Vector2 inputPos = OVRInput.Get(OVRInput.Axis2D.PrimaryThumbstick);
        Vector2 inputRot = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick);

        Vector3 move = cameraTransform.forward * inputPos.y + cameraTransform.right * inputPos.x;
        move.y = 0;
        move.Normalize();

        characterController.Move(move * speed * Time.deltaTime);

        // 5. Gravity
        velocity.y += gravity * Time.deltaTime;
        characterController.Move(velocity * Time.deltaTime);

        if (characterController.isGrounded)
        {
            velocity.y = 0f;
        }
    }
}
