using UnityEngine;

public class TPPCameraFollow : MonoBehaviour
{
    [Header("Target Tracking")]
    public Transform target; // Drag your Moving Cube here
    public Vector3 offset = new Vector3(0f, 3f, -6f); // Behind and slightly above
    
    [Header("Dynamics")]
    public float smoothTime = 0.3f;
    public float dynamicFOVSpeedMultiplier = 0.5f; // How much the FOV stretches based on speed
    public float baseFOV = 60f;

    private Vector3 _velocity = Vector3.zero;
    private Camera _cam;
    private float _currentSpeed;

    private void Start()
    {
        _cam = GetComponent<Camera>();
        
        if (RowingInputManager.Instance != null)
        {
            RowingInputManager.Instance.OnVelocityChanged += UpdateDynamicFOV;
        }
    }

    private void UpdateDynamicFOV(float speed)
    {
        _currentSpeed = speed;
    }

    private void LateUpdate()
    {
        if (target == null) return;

        // 1. Smoothly follow the target's position
        Vector3 targetPosition = target.position + target.TransformDirection(offset);
        transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref _velocity, smoothTime);

        // 2. Look at the target
        transform.LookAt(target.position + Vector3.up * 1.5f); // Look slightly above the base of the cube

        // 3. The "Juice": Dynamically widen the FOV as you row faster (Speed Sense)
        if (_cam != null)
        {
            float targetFOV = baseFOV + (_currentSpeed * dynamicFOVSpeedMultiplier);
            _cam.fieldOfView = Mathf.Lerp(_cam.fieldOfView, targetFOV, Time.deltaTime * 2f);
        }
    }
}