using UnityEngine;
using Cinemachine;
using System.Collections;

public class CameraShake : MonoBehaviour
{
    private CinemachineVirtualCamera virtualCamera;
    private CinemachineBasicMultiChannelPerlin perlin;
    private Coroutine shakeCoroutine;

    [Header("Shake Settings")]
    public float defaultShakeAmplitude = 2.0f;
    public float defaultShakeFrequency = 2.0f;
    public float defaultShakeDuration = 0.3f;

    void Awake()
    {
        virtualCamera = GetComponent<CinemachineVirtualCamera>();
        if (virtualCamera != null)
            perlin = virtualCamera.GetCinemachineComponent<CinemachineBasicMultiChannelPerlin>();
    }

    public void ShakeCamera(float amplitude, float frequency, float duration)
    {
        if (shakeCoroutine != null)
            StopCoroutine(shakeCoroutine);
        shakeCoroutine = StartCoroutine(DoShake(amplitude, frequency, duration));
    }

    public void ShakeCamera() // Overload for default values
    {
        ShakeCamera(defaultShakeAmplitude, defaultShakeFrequency, defaultShakeDuration);
    }

    private IEnumerator DoShake(float amplitude, float frequency, float duration)
    {
        if (perlin == null)
            yield break;
        perlin.m_AmplitudeGain = amplitude;
        perlin.m_FrequencyGain = frequency;
        float elapsed = 0f;
        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            yield return null;
        }
        perlin.m_AmplitudeGain = 0f;
        perlin.m_FrequencyGain = 0f;
    }
}
