document.addEventListener('DOMContentLoaded', () => {
    const audioSection = document.getElementById('audio-section');
    // If the audio section doesn't exist on this page, do nothing.
    if (!audioSection) {
        return;
    }

    const playPauseButton = document.getElementById('play-pause-button');
    const audioTitle = document.getElementById('audio-title');
    const audioProgress = document.getElementById('audio-progress'); // Get progress bar
    const currentTimeSpan = document.getElementById('current-time'); // Get current time span
    const totalDurationSpan = document.getElementById('total-duration'); // Get total duration span

    // It's better to find triggers and players within the context of the page,
    // rather than assuming they are always direct children of the body.
    const playTriggers = document.querySelectorAll('.play-trigger');
    const audioPlayers = document.querySelectorAll('audio'); // Select ALL audio elements
    const audioPlayerMap = new Map();
    audioPlayers.forEach(player => {
        audioPlayerMap.set(player.id, player);
    });

    let currentAudioPlayer = null;
    let currentTrigger = null;

    // Helper function to format time in MM:SS
    function formatTime(seconds) {
        const validSeconds = Number.isFinite(seconds) ? seconds : 0;
        const minutes = Math.floor(validSeconds / 60);
        const secs = Math.floor(validSeconds % 60);
        return `${minutes}:${secs < 10 ? '0' : ''}${secs}`;
    }

    // Function to stop all audio players managed by this script
    function stopAllAudio(exceptPlayer = null) {
        audioPlayers.forEach(player => {
            if (player !== exceptPlayer && !player.paused) {
                player.pause();
                // player.currentTime = 0; // Reset time if desired
            }
        });
    }

    // Function to update the shared UI elements
    function updateAudioUI(player, trigger) {
        const duration = player.duration;
        const songId = player.dataset.songId;

        // Use the trigger's text content or a data attribute for the title
        audioTitle.textContent = "'" + trigger.textContent + "'";
        
        // Set the href for the title link
        if (songId) {
            let youtubeUrl = `https://www.youtube.com/watch?v=${songId}`;
            const startTime = player.dataset.start;
            if (startTime && !isNaN(startTime)) {
                youtubeUrl += `&t=${Math.floor(startTime)}s`; 
            }
            audioTitle.href = youtubeUrl;
        }

        totalDurationSpan.textContent = formatTime(duration);
        audioProgress.max = duration || 1;
        audioProgress.value = player.currentTime;
        currentTimeSpan.textContent = formatTime(player.currentTime);
        audioSection.style.display = 'block'; // Make sure section is visible
    }

    // Universal Play function
    function playCurrentAudio() {
        if (!currentAudioPlayer || !currentTrigger) return;
        stopAllAudio(currentAudioPlayer);
        currentAudioPlayer.play().catch(error => console.error("Error playing audio:", error));
        playPauseButton.textContent = '⏸';
        updateAudioUI(currentAudioPlayer, currentTrigger);
    }

    // Universal Pause function
    function pauseCurrentAudio() {
        if (!currentAudioPlayer) return;
        currentAudioPlayer.pause();
        playPauseButton.textContent = '▶';
    }

    // Attach listeners to each trigger
    playTriggers.forEach(trigger => {
        trigger.addEventListener('click', () => {
            const targetAudioId = trigger.getAttribute('data-audio-target');
            const targetAudioPlayer = audioPlayerMap.get(targetAudioId);

            if (!targetAudioPlayer) {
                console.error(`Audio player with ID ${targetAudioId} not found.`);
                return;
            }

            if (currentAudioPlayer === targetAudioPlayer) {
                if (currentAudioPlayer.paused) {
                    playCurrentAudio();
                } else {
                    pauseCurrentAudio();
                }
            } else {
                stopAllAudio();
                currentAudioPlayer = targetAudioPlayer;
                currentTrigger = trigger;
                currentAudioPlayer.currentTime = 0;
                playCurrentAudio();
            }
        });
    });

    // Play/Pause button controls the current audio
    playPauseButton.addEventListener('click', () => {
        if (!currentAudioPlayer) return;
        if (currentAudioPlayer.paused) {
            playCurrentAudio();
        } else {
            pauseCurrentAudio();
        }
    });

    // Seek functionality for the progress bar
    audioProgress.addEventListener('click', (event) => {
        if (!currentAudioPlayer) return;

        const progressBar = event.target;
        const clickPosition = event.offsetX;
        const progressBarWidth = progressBar.offsetWidth;
        const duration = currentAudioPlayer.duration;

        if (duration && Number.isFinite(duration)) {
            const seekTime = (clickPosition / progressBarWidth) * duration;
            currentAudioPlayer.currentTime = seekTime;
            currentTimeSpan.textContent = formatTime(seekTime);
            audioProgress.value = seekTime;
        }
    });

    // Add universal listeners to all relevant audio players
    audioPlayers.forEach(player => {
        player.addEventListener('timeupdate', () => {
            if (player === currentAudioPlayer) {
                audioProgress.value = player.currentTime;
                currentTimeSpan.textContent = formatTime(player.currentTime);
            }
        });

        player.addEventListener('ended', () => {
            if (player === currentAudioPlayer) {
                playPauseButton.textContent = '▶';
                audioProgress.value = 0;
                currentTimeSpan.textContent = formatTime(0);
                // Optional: Reset currentAudioPlayer and currentTrigger if playback should stop completely
                // currentAudioPlayer = null;
                // currentTrigger = null;
                // audioSection.style.display = 'none'; // Hide if desired
            }
        });

        player.addEventListener('loadedmetadata', () => {
            // Update UI only if this player is the currently selected one *and* the UI is visible
            if (player === currentAudioPlayer && audioSection.style.display !== 'none') {
                totalDurationSpan.textContent = formatTime(player.duration);
                audioProgress.max = player.duration;
            }
        });
    });
}); 