// ~/components/global-audio-player.tsx
import { useEffect, useRef } from 'react';
import { useWebRTCStore } from '~/store/webrtc';

export function GlobalWebRTCAudioPlayer() {
    const audioRef = useRef<HTMLAudioElement>(null);
    const remoteStream = useWebRTCStore(state => state.remoteStream);
    const webRTCStatus = useWebRTCStore(state => state.status);

    useEffect(() => {
        const audioElement = audioRef.current;
        if (audioElement) {
            if (remoteStream && webRTCStatus === 'CONNECTED') {
                console.log('GlobalAudioPlayer: Setting remote stream to audio element.');
                if (audioElement.srcObject !== remoteStream) { // Avoid unnecessary re-assignments
                    audioElement.srcObject = remoteStream;
                    audioElement.play().catch(error => {
                        // Autoplay policy might prevent play without user interaction.
                        // You might need a UI element for the user to click to start playback.
                        console.warn('GlobalAudioPlayer: Error trying to play audio automatically:', error);
                        // A common pattern is to mute the element initially and then allow unmuting by user action
                        // audioElement.muted = true; // Then provide an unmute button
                    });
                }
            } else {
                // If stream is null or not connected, clear the srcObject
                // This also handles the case when leaving a channel.
                if (audioElement.srcObject) {
                    console.log('GlobalAudioPlayer: Clearing remote stream from audio element.');
                    audioElement.srcObject = null;
                }
            }
        }
    }, [remoteStream, webRTCStatus]); // Re-run when remoteStream or connection status changes

    // This component renders the audio element.
    // It's generally good practice for <audio> and <video> to have controls if user interaction is expected.
    // For background audio, you might hide it, but be mindful of autoplay policies.
    // `playsInline` is more relevant for video but doesn't hurt.
    // `autoPlay` is desired but subject to browser restrictions.
    return (
        <audio
            ref={audioRef}
            autoPlay
            playsInline
            // controls // Optional: for debugging or if you want user to control volume/mute from here
            // muted={true} // Start muted if autoplay is problematic, then provide an unmute button
            style={{ display: 'none' }} // Hide it if it's just for background audio
        />
    );
}