using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;

/// <summary>
/// Legacy camera follow script. Auto-disables when CinemachineBrain is present
/// on the same camera to prevent LateUpdate transform conflicts.
/// Only active as fallback when NO Cinemachine pipeline exists.
/// </summary>
public class CameraFollow : MonoBehaviour
{
    public Transform target;
    public Vector3 offset;

    public float smoothSpeed = 0.1f;
    
    private bool cinemachineActive = false;

    private void Start()
    {
        // Check if CinemachineBrain is controlling this camera
        CinemachineBrain brain = GetComponent<CinemachineBrain>();
        if (brain == null)
        {
            // Also check Camera.main in case CameraFollow is on a child
            Camera mainCam = Camera.main;
            if (mainCam != null)
            {
                brain = mainCam.GetComponent<CinemachineBrain>();
            }
        }
        
        if (brain != null && brain.enabled)
        {
            cinemachineActive = true;
            Debug.Log($"[CameraFollow] CinemachineBrain detected — disabling CameraFollow to prevent LateUpdate conflict.");
            enabled = false;
            return;
        }
        
        // Legacy fallback: compute offset from target
        if (target != null)
        {
            offset = transform.position - target.position;
        }
    }

    private void LateUpdate()
    {
        // Double-check: if Cinemachine got enabled after Start, bail out
        if (cinemachineActive) return;
        
        if (target == null) return;
        
        SmoothFollow();
    }

    public void SmoothFollow()
    {
        if (target == null) return;
        
        Vector3 targetPos = target.position + offset;
        Vector3 smoothFollow = Vector3.Lerp(transform.position, targetPos, smoothSpeed);

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