using UnityEngine;

public class KeyAction : MonoBehaviour
{
    private Transform playerTransform;
    [HideInInspector] public bool isFollowing = false;

    [Header("Follow Settings")]
    public Vector3 followOffset = new Vector3(0, 1.5f, 0); // Position above player
    public float followSpeed = 5f;

    [Header("Levitation Settings")]
    public float floatAmplitude = 0.2f; // How high it bobs
    public float floatFrequency = 2f;  // How fast it bobs

    private void Update()
    {
        if (isFollowing && playerTransform != null)
        {
            // 1. Calculate the target position (Player pos + offset)
            Vector3 targetPos = playerTransform.position + followOffset;

            // 2. Add the levitation (Sine wave)
            float floatingY = Mathf.Sin(Time.time * floatFrequency) * floatAmplitude;
            targetPos.y += floatingY;

            // 3. Smoothly move the key to that position
            transform.position = Vector3.Lerp(transform.position, targetPos, Time.deltaTime * followSpeed);
        }
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Player"))
        {
            SoundManager.Instance.PlaySound("keyGet", 1f);

            playerTransform = collision.transform;
            isFollowing = true;

            // Optional: Disable the collider so it doesn't trigger again
            GetComponent<Collider2D>().enabled = false;
        }
    }
}