'use client';
import { useCallback, useEffect, useRef } from 'react';
import { useSoundEnabled } from './use-sound-enabled.js';
const SOUND_NAMES = [
    'button',
    'caution',
    'celebration',
    'disabled',
    'notification',
    'progress_loop',
    'ringtone_loop',
    'select',
    'swipe',
    'swipe_01',
    'swipe_02',
    'swipe_03',
    'swipe_04',
    'swipe_05',
    'tap_01',
    'tap_02',
    'tap_03',
    'tap_04',
    'tap_05',
    'toggle_off',
    'toggle_on',
    'transition_down',
    'transition_up',
    'type_01',
    'type_02',
    'type_03',
    'type_04',
    'type_05',
];
// Module-level cache: Audio objects are created once per sound name and reused
// across component mounts to avoid re-downloading WAV files on every drawer open.
const audioCache = new Map();
function getOrCreateAudio(name) {
    let audio = audioCache.get(name);
    if (!audio) {
        audio = new Audio(`/sounds/${name}.wav`);
        audio.preload = 'auto';
        audioCache.set(name, audio);
    }
    return audio;
}
export function useSound(name, options = {}) {
    const { volume = 1, loop = false } = options;
    const { enabled } = useSoundEnabled();
    const audioRef = useRef(null);
    const isPlayingRef = useRef(false);
    useEffect(() => {
        if (typeof window === 'undefined')
            return;
        const audio = getOrCreateAudio(name);
        audio.loop = loop;
        audio.volume = Math.max(0, Math.min(1, volume));
        audio.addEventListener('ended', () => {
            isPlayingRef.current = false;
        });
        audioRef.current = audio;
        return () => {
            audio.pause();
            audioRef.current = null;
            isPlayingRef.current = false;
        };
    }, [name, loop, volume]);
    const play = useCallback(() => {
        if (!enabled)
            return;
        const audio = audioRef.current;
        if (!audio)
            return;
        audio.currentTime = 0;
        audio.play()?.catch((err) => {
            if (process.env.NODE_ENV === 'development') {
                // eslint-disable-next-line no-console
                console.warn(`[useSound] play("${name}") blocked:`, err.message);
            }
        });
        isPlayingRef.current = true;
    }, [enabled, name]);
    const stop = useCallback(() => {
        const audio = audioRef.current;
        if (!audio)
            return;
        audio.pause();
        audio.currentTime = 0;
        isPlayingRef.current = false;
    }, []);
    return { play, stop, isPlaying: isPlayingRef.current };
}
/** All available sound names for enumeration (e.g. in Storybook). */
export { SOUND_NAMES };
