using UnityEngine;

public class CameraOrbit : MonoBehaviour
{
    [Header("Target Settings")]
    public Transform target;        // Das Objekt, um das sich die Kamera drehen soll
    public float distance = 5.0f;   // Abstand zur Kamera

    [Header("Rotation Settings")]
    public float xSpeed = 120.0f;   // Geschwindigkeit für horizontale Drehung
    public float ySpeed = 120.0f;   // Geschwindigkeit für vertikale Drehung
    public float yMinLimit = -20f;  // Min. vertikaler Winkel
    public float yMaxLimit = 80f;   // Max. vertikaler Winkel

    private float x = 0.0f;
    private float y = 0.0f;

    void Start()
    {
        if (target == null)
        {
            Debug.LogWarning("Kein Target gesetzt! Bitte ein Objekt in 'target' zuweisen.");
            enabled = false;
            return;
        }

        Vector3 angles = transform.eulerAngles;
        x = angles.y;
        y = angles.x;

        // Cursor frei beweglich lassen
        Cursor.lockState = CursorLockMode.None;
        Cursor.visible = true;
    }

    void LateUpdate()
    {
        if (target == null) return;
        
        float scroll = Input.GetAxis("Mouse ScrollWheel");
        if (scroll != 0f)
        {
            float fov = -1;
            foreach (Camera _cam in transform.GetComponentsInChildren<Camera>())
            {
                if (fov < 0) // Calculate FOV for first Camera
                {
                    fov = _cam.fieldOfView - scroll * GameManager.Instance.zoomSpeed;
                    fov = Mathf.Clamp(fov, GameManager.Instance.minFOV, GameManager.Instance.maxFOV);                    
                }
                _cam.fieldOfView = fov;
            }
        }

        if (Input.GetMouseButton(1)) // Rechte Maustaste gedrückt
        {
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
            x += Input.GetAxis("Mouse X") * xSpeed * Time.deltaTime;
            y -= Input.GetAxis("Mouse Y") * ySpeed * Time.deltaTime;
            y = Mathf.Clamp(y, yMinLimit, yMaxLimit);
        } else
        {
            Cursor.lockState = CursorLockMode.None;
            Cursor.visible = true;
        }

        Quaternion rotation = Quaternion.Euler(y, x, 0);
        Vector3 position = rotation * new Vector3(0.0f, 0.0f, -distance) + target.position;

        transform.rotation = rotation;
        transform.position = position;

        Camera cam = transform.GetChild(0).GetComponent<Camera>();

        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, float.MaxValue))
        {
            GameManager gm = FindFirstObjectByType<GameManager>();

            if (hit.transform.CompareTag("Node"))
            {
                var obj = hit.transform.GetComponent<Node>();
                obj.hovered = true;
            }

            // Hover-Ermittlung Connections
            Vector2 mouse = Input.mousePosition;
            Vector3 mousePos = new Vector3(mouse.x, mouse.y, 0);
            bool cancelHover = false;
            float closestDist = float.MaxValue;
            int closestIdx = -1;
            var connections = gm.GetConnections();
            for (int i = 0; i < connections.Count; i++)
            {
                connections[i].hovered = false;

                if (cancelHover)
                    continue;

                var con = connections[i];
                Vector3 a = cam.WorldToScreenPoint(con.nodeA.transform.position);
                Vector3 b = cam.WorldToScreenPoint(con.nodeB.transform.position);

                Vector3 ab = b - a;
                Vector3 am = mousePos - a;
                float t = Mathf.Clamp01(Vector3.Dot(am, ab) / ab.sqrMagnitude);
                Vector3 proj = a + t * ab;
                float dist = Vector3.Distance(mousePos, proj);

                if (Vector3.Distance(a, mousePos) <= gm.hoverRadiusNode || Vector3.Distance(b, mousePos) <= gm.hoverRadiusNode)
                    cancelHover = true;

                if (dist < closestDist && dist < gm.hoverRadiusCon)
                {
                    closestDist = dist;
                    closestIdx = i;
                }       
            }
            if (closestIdx >= 0 && !cancelHover)
                connections[closestIdx].hovered = true;

            gm.hoverText.gameObject.transform.transform.forward = Camera.main.transform.forward;
            gm.hoverText.gameObject.transform.position = hit.point + Vector3.up * 3.0f;
            gm.hoverText.gameObject.transform.localPosition = gm.hoverText.gameObject.transform.localPosition.normalized * 23f;
        }
    }
}