#if UDONSHARP && UNITY_2022_3_OR_NEWER
using UdonSharp;
using UnityEngine;
using VRC.SDKBase;

namespace WPFMA.Udon
{
    [UdonBehaviourSyncMode(BehaviourSyncMode.None)]
    public class WPFMAAudioZone : UdonSharpBehaviour
    {
        public AudioSource[] sources;
        public float fadeSeconds = 1.5f;

        private float[] fullVolumes;
        private bool inside;
        private float level;

        private void Start()
        {
            if (sources == null)
                return;

            fullVolumes = new float[sources.Length];
            for (int i = 0; i < sources.Length; i++)
            {
                if (sources[i] == null)
                    continue;

                fullVolumes[i] = sources[i].volume;
                sources[i].volume = 0f;
            }
        }

        public override void OnPlayerTriggerEnter(VRCPlayerApi player)
        {
            if (player != null && player.isLocal)
                inside = true;
        }

        public override void OnPlayerTriggerExit(VRCPlayerApi player)
        {
            if (player != null && player.isLocal)
                inside = false;
        }

        private void Update()
        {
            if (sources == null || fullVolumes == null)
                return;

            float target = inside ? 1f : 0f;
            if (level == target)
                return;

            level = Mathf.MoveTowards(level, target, Time.deltaTime / Mathf.Max(0.01f, fadeSeconds));

            for (int i = 0; i < sources.Length; i++)
            {
                if (sources[i] == null)
                    continue;

                sources[i].volume = fullVolumes[i] * level;
                if (level > 0f && !sources[i].isPlaying)
                    sources[i].Play();
            }
        }
    }
}
#endif
