/**
 * Custom Audio Player
 * This script enhances the HTML5 audio element to provide better compatibility
 * with various audio formats including opus files.
 */

document.addEventListener('DOMContentLoaded', function() {
    // Find all audio elements on the page
    const audioElements = document.querySelectorAll('audio.custom-audio-player');

    if (audioElements.length === 0) return;

    console.log('Found', audioElements.length, 'audio players to enhance');

    audioElements.forEach(function(audio) {
        // Get the source element
        const source = audio.querySelector('source');
        if (!source) return;

        // Get the source URL and type
        const sourceUrl = source.getAttribute('src');
        const sourceType = source.getAttribute('type');

        // Check if the URL contains opus to force ogg mime type for better compatibility
        if (sourceUrl.toLowerCase().includes('.opus')) {
            source.setAttribute('type', 'audio/ogg');
        }

        // Check if the browser supports the audio format
        let canPlay = audio.canPlayType(source.getAttribute('type'));

        if (canPlay === '' || canPlay === 'no') {
            console.log('Browser cannot play format:', sourceType);

            // Add a loading indicator
            const parent = audio.parentElement;
            const loadingIndicator = document.createElement('div');
            loadingIndicator.className = 'text-center my-2';
            loadingIndicator.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading audio...';
            parent.insertBefore(loadingIndicator, audio.nextSibling);

            // Try to load the audio file anyway
            fetch(sourceUrl)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! Status: ${response.status}`);
                    }
                    return response.blob();
                })
                .then(blob => {
                    // Create a URL for the blob
                    const url = URL.createObjectURL(blob);

                    // Update the source and force reload
                    source.src = url;

                    // Create an additional source element with a different MIME type for better compatibility
                    const alternativeSource = document.createElement('source');
                    alternativeSource.setAttribute('src', url);
                    alternativeSource.setAttribute('type', 'audio/mpeg'); // Try with audio/mpeg as fallback
                    audio.appendChild(alternativeSource);

                    audio.load();

                    // Remove loading indicator
                    loadingIndicator.remove();
                })
                .catch(error => {
                    console.error('Error loading audio:', error);
                    loadingIndicator.innerHTML = 'Error loading audio. Please try again or download the file.';
                });
        }

        // Add event listeners for debugging
        audio.addEventListener('error', function(e) {
            console.error('Audio error:', e);

            // Show a more visible error message
            const parent = audio.parentElement;
            const errorMsg = document.createElement('div');
            errorMsg.className = 'alert alert-warning mt-2 mb-0 py-1 px-2';
            errorMsg.innerHTML = 'Unable to play this audio format. Please download the file instead.';

            // Only add if not already added
            if (!parent.querySelector('.alert')) {
                parent.insertBefore(errorMsg, audio.nextSibling);
            }
        });

        audio.addEventListener('canplay', function() {
            console.log('Audio can play:', sourceUrl);

            // Remove any error messages if the audio can now play
            const parent = audio.parentElement;
            const errorMsg = parent.querySelector('.alert');
            if (errorMsg) {
                errorMsg.remove();
            }
        });

        // Force reload the audio element to ensure proper initialization
        audio.load();
    });

    // Fix for Safari and iOS
    // Safari requires user interaction to start playing audio
    document.addEventListener('click', function() {
        audioElements.forEach(function(audio) {
            if (audio.readyState < 2) { // HAVE_CURRENT_DATA
                audio.load();
            }
        });
    }, { once: true });
});
