using UnityEngine;
using UnityEngine.InputSystem;

public class BounceAndSound : MonoBehaviour
{
    public AudioClip clickSound;        // drag your sound file here in Inspector
    public float bounceHeight = 0.08f;  // how high it bounces
    public float bounceSpeed  = 4f;     // how fast it bounces

    private AudioSource audioSource;
    private bool isBouncing = false;
    private Vector3 startPosition;

    void Start()
    {
        startPosition = transform.position;
        audioSource = gameObject.AddComponent<AudioSource>();
        audioSource.clip = clickSound;
        audioSource.loop = false;
        audioSource.playOnAwake = false;
    }

    void Update()
    {
        // Handle click using raycast
        if (Mouse.current.leftButton.wasPressedThisFrame)
        {
            Ray ray = Camera.main.ScreenPointToRay(Mouse.current.position.ReadValue());
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit) && hit.transform == this.transform)
            {
                isBouncing = !isBouncing;

                if (isBouncing)
                {
                    startPosition = transform.position;
                    audioSource.Play();
                }
                else
                {
                    audioSource.Stop();
                    transform.position = startPosition;
                }
            }
        }

        // Bounce animation using a sine wave
        if (isBouncing)
        {
            float newY = startPosition.y + Mathf.Abs(Mathf.Sin(Time.time * bounceSpeed)) * bounceHeight;
            transform.position = new Vector3(startPosition.x, newY, startPosition.z);
        }
    }
}
