import { useRef } from "react";

export function useSound() {
    const audioRef = useRef<HTMLAudioElement | null>(null); 
    const loopingAudioRef = useRef<HTMLAudioElement | null>(null);

    const stopSound = () => {
        if (!audioRef.current) {
            return;
        }
        audioRef.current.pause();
        audioRef.current.currentTime = 0;
        audioRef.current.removeAttribute("src");
        audioRef.current.load();
    };

    const playSound = async (sound : string, loop: boolean = false) => {
        try {
            if(loop){
                if (!loopingAudioRef.current) {
                    loopingAudioRef.current = new Audio();
                    loopingAudioRef.current.volume = 0.1;
                    loopingAudioRef.current.preload = "auto";
                    loopingAudioRef.current.loop = true;
                }

                const url = await window.mediaApi.getSoundUrl(sound);
                const player = loopingAudioRef.current;

                player.src = url;
                const playPromise = player.play();
                if (playPromise) {
                    void playPromise.catch((e) => {
                        console.error("Failed to play looping UI sound:", e);
                    });
                }
                return;
            }
            if (!audioRef.current) {
                audioRef.current = new Audio();
                audioRef.current.volume = 0.1;
                audioRef.current.preload = "auto";
                audioRef.current.loop = loop;
            }

            const url = await window.mediaApi.getSoundUrl(sound);
            const player = audioRef.current;

            stopSound();

            player.src = url;
            const playPromise = player.play();
            if (playPromise) {
                void playPromise.catch((e) => {
                    console.error("Failed to play UI sound:", e);
                });
            }
        } catch (e) {
            console.error("Failed to prepare UI sound:", e);
        }
    }

    const stopLoopSound = () => {
        if (!loopingAudioRef.current) {
            return;
        }
        loopingAudioRef.current.pause();
        loopingAudioRef.current.currentTime = 0;
        loopingAudioRef.current.removeAttribute("src");
        loopingAudioRef.current.load();
    }

    return {
        playSound,
        stopSound,
        stopLoopSound
    }
}