using UnityEngine;
using UnityEngine.InputSystem;

public class CameraOrbit : MonoBehaviour
{
    [Header("Obiekt, wokół którego obraca się kamera")]
    [SerializeField] private Transform target;

    [Header("Odległość kamery od obiektu")]
    [SerializeField] private float distance = 5f;
    [SerializeField] private float minDistance = 2f;
    [SerializeField] private float maxDistance = 10f;

    [Header("Szybkość obrotu i zoomu")]
    [SerializeField] private float rotationSpeed = 0.2f;
    [SerializeField] private float zoomSpeed = 0.01f;

    [Header("Ograniczenie obrotu w pionie")]
    [SerializeField] private float minPitch = -20f;
    [SerializeField] private float maxPitch = 80f;

    // Kąt obrotu w poziomie
    private float yaw = 0f;

    // Kąt obrotu w pionie
    private float pitch = 20f;

    private void Update()
    {
        RotateCamera();
        ZoomCamera();
        UpdateCameraPosition();
    }

    private void RotateCamera()
    {
        if (Mouse.current == null)
            return;

        if (Mouse.current.rightButton.isPressed)
        {
            Vector2 mouseDelta = Mouse.current.delta.ReadValue();

            yaw = yaw + mouseDelta.x * rotationSpeed;
            pitch = pitch - mouseDelta.y * rotationSpeed;
            pitch = Mathf.Clamp(pitch, minPitch, maxPitch);
        }
    }

    private void ZoomCamera()
    {
        if (Mouse.current == null)
            return;

        Vector2 scroll = Mouse.current.scroll.ReadValue();

        distance = distance - scroll.y * zoomSpeed;
        distance = Mathf.Clamp(distance, minDistance, maxDistance);
    }

    private void UpdateCameraPosition()
    {
        Quaternion rotation = Quaternion.Euler(pitch, yaw, 0f);
        Vector3 direction = rotation * Vector3.forward;
        Vector3 cameraPosition = target.position - direction * distance;

        transform.position = cameraPosition;
        transform.LookAt(target.position);
    }
}