//Morten
using UnityEngine;

public class Door_Rotate : MonoBehaviour
{
    [SerializeField] private float openAngle = 90f;
    [SerializeField] private float rotationSpeed = 2f;
    [SerializeField] private float interactionDistance = 5f;
    [SerializeField] private Vector3 rotationOffset = Vector3.zero;

    private float targetRotation = 0f;
    private float currentRotation = 0f;
    private bool isOpen = false;
    private Camera playerCamera;
    private Vector3 pivotPoint;


    void Start()
    {
        playerCamera = Camera.main;
        currentRotation = transform.localEulerAngles.y;
        targetRotation = currentRotation;

        pivotPoint = transform.position + rotationOffset;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E) && IsPlayerLooking())
        {
            ToggleDoor();
        }

        SmoothRotateDoor();
    }

    private void ToggleDoor()
    {
        isOpen = !isOpen;
        targetRotation = isOpen ? currentRotation + openAngle : currentRotation - openAngle;
    }
    //glatte bewegung der tür
    private void SmoothRotateDoor()
    {
        currentRotation = Mathf.Lerp(currentRotation, targetRotation, Time.deltaTime * rotationSpeed);

        transform.RotateAround(pivotPoint, Vector3.up, (currentRotation - transform.localEulerAngles.y));
        transform.localEulerAngles = new Vector3(
            transform.localEulerAngles.x,
            currentRotation,
            transform.localEulerAngles.z
        );
    }
    //checkt ob der spieler auf die Tür schaut und ob er nah genug ist, um sie zu öffnen https://docs.unity3d.com/6000.4/Documentation/ScriptReference/Physics.Raycast.html
    private bool IsPlayerLooking()
    {
        if (playerCamera == null) return false;

        Ray ray = new Ray(playerCamera.transform.position, playerCamera.transform.forward);
        float distanceToPlayer = Vector3.Distance(playerCamera.transform.position, transform.position);

        if (distanceToPlayer > interactionDistance) return false;

        if (Physics.Raycast(ray, out RaycastHit hit, interactionDistance))
        {
            return hit.collider.gameObject == gameObject;
        }

        return false;
    }
}
