// Assets/_Project/Scripts/Combat/TeslaTowerFireSound.cs
using UnityEngine;

namespace TD.Combat
{
    /// <summary>
    /// Local-only audio for the Tesla Coil tower. Subscribes to
    /// <see cref="TowerCombat.OnAreaFired"/> and plays a one-shot fire sound
    /// on every peer each time the coil discharges.
    /// </summary>
    /// <remarks>
    /// Pure client-side — nothing here is networked. Add additional
    /// <see cref="AudioClip"/> fields and <see cref="AudioSource"/> calls here
    /// as the Tesla Coil gains more audio (idle hum, charge-up, etc.).
    /// </remarks>
    [RequireComponent(typeof(TowerCombat))]
    [RequireComponent(typeof(AudioSource))]
    public class TeslaTowerFireSound : MonoBehaviour
    {
        [Tooltip("Sound played each time the coil discharges.")]
        [SerializeField] private AudioClip fireClip;

        [Tooltip("Pitch is randomized within this range each shot to avoid a mechanical loop.")]
        [SerializeField] private float minPitch = 0.93f;
        [SerializeField] private float maxPitch = 1.07f;

        private TowerCombat combat;
        private AudioSource audioSource;

        private void Awake()
        {
            combat      = GetComponent<TowerCombat>();
            audioSource = GetComponent<AudioSource>();
        }

        private void OnEnable()
        {
            if (combat != null) combat.OnAreaFired += HandleAreaFired;
        }

        private void OnDisable()
        {
            if (combat != null) combat.OnAreaFired -= HandleAreaFired;
        }

        private void HandleAreaFired(Vector3[] positions)
        {
            if (fireClip != null)
            {
                audioSource.pitch = Random.Range(minPitch, maxPitch);
                audioSource.clip  = fireClip;
                audioSource.Play();
            }
        }
    }
}
