// Import the function
import { searchChordByName } from './my-chords.js';
import { loadInstrument, initAudio, playChordWithDuration } from './js/audio.js';

// Replace the debug section with this more comprehensive check:

console.log('=== SVGuitar Debug Info ===');
console.log('typeof svguitar:', typeof svguitar);
console.log('svguitar object:', svguitar);
console.log('Object.keys(svguitar):', typeof svguitar === 'object' ? Object.keys(svguitar) : 'N/A');

// Check all possible constructor locations
const possibleConstructors = [
    () => typeof svguitar === 'function' ? svguitar : null,
    () => svguitar?.SVGuitar,
    () => svguitar?.default,
    () => svguitar?.SVGuitarChord,
    () => window.SVGuitar,
    () => window.svguitar
];

possibleConstructors.forEach((getter, index) => {
    try {
        const constructor = getter();
        console.log(`Constructor option ${index}:`, typeof constructor, constructor);
    } catch (e) {
        console.log(`Constructor option ${index}: error -`, e.message);
    }
});

// Test creating an instance with different approaches
if (typeof svguitar === 'object' && svguitar) {
    console.log('Trying to create test instances...');
    
    // Try each property that might be a constructor
    Object.keys(svguitar).forEach(key => {
        const prop = svguitar[key];
        console.log(`svguitar.${key}:`, typeof prop, prop);
        
        if (typeof prop === 'function') {
            try {
                // Create a temporary div for testing
                const testDiv = document.createElement('div');
                document.body.appendChild(testDiv);
                
                const instance = new prop(testDiv);
                console.log(`SUCCESS: new svguitar.${key}() works!`, instance);
                
                // Clean up
                document.body.removeChild(testDiv);
            } catch (e) {
                console.log(`FAILED: new svguitar.${key}():`, e.message);
            }
        }
    });
}

class SongPlayer {
    constructor() {
        this.songData = null;
        this.currentChordIndex = 0;
        this.isPlaying = false;
        this.isPaused = false;
        this.beatTimer = null;
        this.tempo = 120; // Default BPM
        this.timeSignature = '4/4';
        this.beatsPerMeasure = 4;
        this.chordCache = new Map(); // Cache for fetched chord data
        this.audioEnabled = true; // Add this line
        
        this.initializeElements();
        this.attachEventListeners();
        this.loadSongFromURL();
        
        // Add this method call
        this.initializeAudio();
    }

    // Add this method
    async initializeAudio() {
        try {
            await initAudio();
            loadInstrument('guitar-acoustic');
            console.log('Audio system initialized');
        } catch (error) {
            console.error('Failed to initialize audio:', error);
            this.audioEnabled = false;
        }
    }

    // Add this method
    toggleAudio() {
        this.audioEnabled = !this.audioEnabled;
        console.log('Audio', this.audioEnabled ? 'enabled' : 'disabled');
    }

    // Direct chord playing method that doesn't use Tone.js Transport timing
    async playChordDirectly(chordName, durationSeconds) {
        try {
            // Import audio functions
            const { getNotesFromVoicing, getCurrentInstrument, isInstrumentReady } = await import('./js/audio.js');
            
            // Check if instrument is ready
            if (!isInstrumentReady()) {
                console.log('Instrument not ready for direct playback');
                return;
            }
            
            const currentInstrument = getCurrentInstrument();
            const notes = getNotesFromVoicing(chordName);
            
            if (notes && notes.length > 0 && currentInstrument) {
                // Convert seconds to Tone.js time format
                const toneTime = durationSeconds.toString() + 's';
                currentInstrument.triggerAttackRelease(notes, toneTime);
                console.log(`Triggered chord ${chordName} with notes ${notes} for ${toneTime}`);
            } else {
                console.log(`Cannot play chord: notes=${notes?.length || 0}, instrument=${!!currentInstrument}`);
            }
        } catch (error) {
            console.error('Error in direct chord playback:', error);
        }
    }

    initializeElements() {
        this.playButton = document.getElementById('play-button');
        this.countdown = document.getElementById('countdown');
        this.playerContainer = document.getElementById('player-container');
        this.songInfo = document.getElementById('song-info');
        this.controls = document.getElementById('controls');
        this.songTitleMain = document.getElementById('song-title-main');
        
        // Current chord elements
        this.chordName = document.getElementById('chord-name');
        this.chordDiagram = document.getElementById('chord-diagram');
        this.beatIndicator = document.getElementById('beat-indicator');
        
        // Previous chord elements
        this.previousChordName = document.getElementById('previous-chord-name');
        this.previousChordDiagram = document.getElementById('previous-chord-diagram');
        this.previousBeatIndicator = document.getElementById('previous-beat-indicator');
        
        // Next chord elements
        this.nextChordName = document.getElementById('next-chord-name');
        this.nextChordDiagram = document.getElementById('next-chord-diagram');
        this.nextBeatIndicator = document.getElementById('next-beat-indicator');
        
        // Updated lyrics display elements
        this.lyricsDisplay = document.getElementById('lyrics-display');
        this.previousLyrics = document.getElementById('previous-lyrics');
        this.currentLyrics = document.getElementById('current-lyrics');
        this.nextLyrics = document.getElementById('next-lyrics');
        
        this.songTitleDisplay = document.getElementById('song-title-display');
        this.tempoDisplay = document.getElementById('tempo-display');
        this.timeSignatureDisplay = document.getElementById('time-sig-display');
    }

    attachEventListeners() {
        this.playButton.addEventListener('click', () => this.startCountdown());
        document.getElementById('stop-btn').addEventListener('click', () => this.stop());
        document.getElementById('pause-btn').addEventListener('click', () => this.togglePause());
        // Remove this line:
        // document.getElementById('player-launch-btn').addEventListener('click', () => this.launchSongPlayer());
        
        // Keyboard controls
        document.addEventListener('keydown', (e) => {
            switch(e.code) {
                case 'Space':
                    e.preventDefault();
                    if (!this.isPlaying) {
                        this.startCountdown();
                    } else {
                        this.togglePause();
                    }
                    break;
                case 'Escape':
                    this.stop();
                    break;
                case 'KeyM': // Add this case
                    this.toggleAudio();
                    break;
            }
        });
    }

    loadSongFromURL() {
        const urlParams = new URLSearchParams(window.location.search);
        const songParam = urlParams.get('song');
        
        if (songParam) {
            try {
                const songData = decodeURIComponent(songParam);
                document.getElementById('song-data').value = songData;
                this.parseSongData(songData);
            } catch (error) {
                console.error('Error loading song data from URL:', error);
            }
        } else {
            // If no URL parameter, try to load from textarea
            const textareaContent = document.getElementById('song-data').value.trim();
            if (textareaContent) {
                try {
                    this.parseSongData(textareaContent);
                } catch (error) {
                    console.error('Error loading song data from textarea:', error);
                }
            }
        }
    }

    async parseSongData(chordProText) {
        console.log('Parsing song data:', chordProText);
        
        const lines = chordProText.split('\n');
        this.songData = {
            title: '',
            artist: '',
            tempo: 120,
            timeSignature: '4/4',
            chords: [],
            lyricLines: []
        };

        // Parse metadata and collect all chord names
        const uniqueChords = new Set();
        let currentLineIndex = 0;
        
        lines.forEach(line => {
            const trimmed = line.trim();
            
            // Parse directives
            const titleMatch = trimmed.match(/\{title:\s*(.+)\}/i);
            if (titleMatch) this.songData.title = titleMatch[1];
            
            const artistMatch = trimmed.match(/\{artist:\s*(.+)\}/i);
            if (artistMatch) this.songData.artist = artistMatch[1];
            
            const tempoMatch = trimmed.match(/\{tempo:\s*(\d+)\}/i);
            if (tempoMatch) this.songData.tempo = parseInt(tempoMatch[1]);
            
            const timeMatch = trimmed.match(/\{time:\s*([\d]+\/[\d]+)\}/i);
            if (timeMatch) this.songData.timeSignature = timeMatch[1];
            
            // Parse chord lines and collect chord names
            if (!trimmed.startsWith('{') && !trimmed.startsWith('#') && trimmed.length > 0) {
                this.parseChordLine(trimmed, uniqueChords, currentLineIndex);
                currentLineIndex++;
            }
        });

        this.tempo = this.songData.tempo;
        this.timeSignature = this.songData.timeSignature;
        this.beatsPerMeasure = parseInt(this.timeSignature.split('/')[0]);
        
        // Group chords by their original line numbers
        this.groupChordsByLines();
        
        console.log('Parsed song data:', this.songData);
        console.log('Found chords:', this.songData.chords.length);
        console.log('Found lyric lines:', this.songData.lyricLines.length);
        console.log('Unique chords to fetch:', Array.from(uniqueChords));
        
        // Fetch all chord data before continuing
        await this.fetchAllChordData(uniqueChords);
        
        this.updateSongInfo();
        
        // Validate that we have chords to play
        if (this.songData.chords.length === 0) {
            console.warn('No chords found in song data');
            alert('No chords found in the song. Please check the ChordPro format.');
        }
    }

    parseChordLine(line, uniqueChords, lineIndex) {
        const chordRegex = /\[([^\]]+)\]/g;
        let lastIndex = 0;
        let match;
        let currentText = '';

        while ((match = chordRegex.exec(line)) !== null) {
            // Add text before chord
            currentText += line.substring(lastIndex, match.index);
            
            const chordInfo = match[1];
            let chordName = chordInfo;
            let beats = 4; // Default to 4 beats

            // Check for beat annotation (e.g., "C;4")
            if (chordInfo.includes(';')) {
                const parts = chordInfo.split(';');
                chordName = parts[0];
                beats = parseInt(parts[1]) || 4;
            }
            
            // Add chord name to unique set for fetching
            uniqueChords.add(chordName);
            
            // Trim the lyrics to remove extra spaces
            const trimmedLyrics = currentText;
            
            this.songData.chords.push({
                chord: chordName,
                beats: beats,
                lyrics: trimmedLyrics,
                originalLineIndex: lineIndex // Track which original line this chord came from
            });
            
            currentText = '';
            lastIndex = match.index + match[0].length;
        }
        
        // Add remaining text after the last chord
        currentText += line.substring(lastIndex);
        const remainingText = currentText;
        
        if (remainingText) {
            // If there's text after the last chord, add it to the last chord's lyrics
            if (this.songData.chords.length > 0) {
                const lastChord = this.songData.chords[this.songData.chords.length - 1];
                // Add a space before the remaining text if the last chord already has lyrics
                if (lastChord.lyrics) {
                    lastChord.lyrics += remainingText;
                } else {
                    lastChord.lyrics = remainingText;
                }
            }
        }
    }

    groupChordsByLines() {
        if (!this.songData.chords.length) return;
        
        // Group chords by their original line index
        const lineGroups = {};
        
        this.songData.chords.forEach((chord, chordIndex) => {
            const lineIndex = chord.originalLineIndex;
            
            if (!lineGroups[lineIndex]) {
                lineGroups[lineIndex] = {
                    fullText: '',
                    chordIndices: [],
                    hasLyrics: false
                };
            }
            
            lineGroups[lineIndex].chordIndices.push(chordIndex);
            
            // Build the full text for this line
            if (chord.lyrics) {
                lineGroups[lineIndex].hasLyrics = true;
                /*if (lineGroups[lineIndex].fullText && !lineGroups[lineIndex].fullText.endsWith(' ')) {
                    lineGroups[lineIndex].fullText += ' ';
                }*/
                lineGroups[lineIndex].fullText += chord.lyrics;
            }
        });
        
        // Convert to array and sort by line index
        const sortedLineIndices = Object.keys(lineGroups).map(k => parseInt(k)).sort((a, b) => a - b);
        
        this.songData.lyricLines = sortedLineIndices.map(lineIndex => ({
            fullText: lineGroups[lineIndex].fullText.trim(),
            chordIndices: lineGroups[lineIndex].chordIndices,
            originalLineIndex: lineIndex,
            hasLyrics: lineGroups[lineIndex].hasLyrics
        }));
        
        // Map each chord to its position in the lyricLines array
        this.songData.chords.forEach((chord, chordIndex) => {
            const lyricLineIndex = this.songData.lyricLines.findIndex(line => 
                line.chordIndices.includes(chordIndex)
            );
            chord.lineIndex = lyricLineIndex >= 0 ? lyricLineIndex : 0;
        });
        
        console.log('Grouped by original lines:', this.songData.lyricLines);
    }

    async fetchAllChordData(chordNames) {
        console.log('Fetching chord data for:', Array.from(chordNames));
        
        // Add this try/catch block at the beginning
        try {
            const stateModule = await import('./js/state.js');
            const chordApiData = stateModule.chordApiData || [];
            
            for (const chordName of chordNames) {
                try {
                    const results = await searchChordByName(chordName);
                    if (results && results.length > 0) {
                        this.chordCache.set(chordName, results[0]);
                        // Add this line to populate chordApiData for audio.js
                        if (!chordApiData.find(c => c.chordName === chordName)) {
                            chordApiData.push(results[0]);
                        }
                        console.log(`Cached chord data for ${chordName}:`, results[0]);
                    } else {
                        console.warn(`No chord data found for: ${chordName}`);
                        this.chordCache.set(chordName, null);
                    }
                } catch (error) {
                    console.error(`Error fetching chord ${chordName}:`, error);
                    this.chordCache.set(chordName, null);
                }
            }
        } catch (error) {
            console.error('Error importing state.js, using fallback:', error);
            // Keep your existing fallback code
            for (const chordName of chordNames) {
                try {
                    const results = await searchChordByName(chordName);
                    if (results && results.length > 0) {
                        this.chordCache.set(chordName, results[0]);
                        console.log(`Cached chord data for ${chordName}:`, results[0]);
                    } else {
                        console.warn(`No chord data found for: ${chordName}`);
                        this.chordCache.set(chordName, null);
                    }
                } catch (error) {
                    console.error(`Error fetching chord ${chordName}:`, error);
                    this.chordCache.set(chordName, null);
                }
            }
        }
        
        console.log('Chord data fetch complete. Cache size:', this.chordCache.size);
    }

    async generateChordDiagram(chordName, container, width = 200, height = 250) {
        // Clear previous diagram
        container.innerHTML = '';
        
        // Ensure container has proper dimensions
        container.style.width = `${width}px`;
        container.style.height = `${height}px`;
        container.style.display = 'block';
        container.style.position = 'relative';
        
        try {
            // Get chord data from cache
            const chordData = this.chordCache.get(chordName);
            
            if (chordData && chordData.fingers && chordData.barres !== undefined) {
                console.log(`Rendering chord ${chordName} with data:`, chordData);
                
                // Use the same pattern as ui.js
                var chart = new svguitar.SVGuitarChord(container);
                chart
                    .configure({
                        color: '#ffffff', // White for dark background
                        strings: 6, 
                        frets: 4, 
                        position: chordData.position || 1,
                        nutSize: 0, 
                        fingerSize: 0.85, 
                        strokeWidth: 4, 
                        style: 'normal',
                        orientation: 'vertical', 
                        fixedDiagramPosition: true, 
                        titleFontSize: Math.floor(width / 8)
                    })
                    .chord({
                        title: chordName,
                        fingers: JSON.parse(chordData.fingers),
                        barres: JSON.parse(chordData.barres),
                        position: chordData.position || 1
                    })
                    .draw();
                
                console.log(`Successfully rendered chord diagram for ${chordName}`);
            } else {
                console.log(`No chord data available for ${chordName}, using fallback`);
                this.createFallbackChordDisplay(chordName, container, width, height);
            }
        } catch (error) {
            console.error('Error generating chord diagram:', error);
            this.createFallbackChordDisplay(chordName, container, width, height);
        }
    }

    createFallbackChordDisplay(chordName, container, width, height) {
        container.innerHTML = '';
        const fallback = document.createElement('div');
        fallback.style.cssText = `
            width: ${width}px; 
            height: ${height}px; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            border: 2px solid #fff; 
            font-size: ${width/8}px;
            color: #fff;
            background: transparent;
            border-radius: 8px;
        `;
        fallback.innerHTML = chordName;
        container.appendChild(fallback);
    }

    async startCountdown() {
        // Make sure all chords are loaded before starting
        if (this.chordCache.size === 0) {
            console.log('Chord data not loaded yet, please wait...');
            return;
        }

        this.playButton.classList.add('hidden');
        this.countdown.classList.remove('hidden');
        
        let count = this.beatsPerMeasure;
        this.countdown.textContent = count;
        
        const countdownInterval = setInterval(() => {
            count--;
            if (count > 0) {
                this.countdown.textContent = count;
                // Re-trigger animation
                this.countdown.style.animation = 'none';
                this.countdown.offsetHeight; // Trigger reflow
                this.countdown.style.animation = 'pulse 1s ease-in-out';
            } else {
                clearInterval(countdownInterval);
                this.startPlaying();
            }
        }, (60 / this.tempo) * 1000); // Beat duration in milliseconds
    }

    async startPlaying() {
        this.countdown.classList.add('hidden');
        this.playButton.classList.add('hidden'); // Make sure it stays hidden
        this.playerContainer.classList.remove('hidden');
        this.songInfo.classList.remove('hidden');
        this.controls.classList.remove('hidden');
        
        // Ensure Tone.js Transport is stopped and cleared
        try {
            if (typeof Tone !== 'undefined') {
                Tone.Transport.stop();
                Tone.Transport.cancel(0);
                console.log('Cleared Tone.js Transport before starting player');
            }
        } catch (error) {
            console.log('Error clearing Tone.js Transport:', error);
        }
        
        this.isPlaying = true;
        this.currentChordIndex = 0;
        await this.playNextChord();
    }

    async playNextChord() {
        if (!this.isPlaying || this.isPaused) return;
        
        // Safety check for songData
        if (!this.songData || !this.songData.chords) {
            console.error('No song data available');
            this.stop();
            return;
        }
        
        if(this.currentChordIndex >= this.songData.chords.length) {
            this.stop();
            return;
        }
        
        const chordData = this.songData.chords[this.currentChordIndex];
        await this.displayChord(chordData);
        
        // Add this audio playing code after displayChord:
        if (this.audioEnabled && chordData.chord) {
            try {
                if (Tone.context.state !== 'running') {
                    await Tone.start();
                }
                
                // Calculate duration in seconds based on tempo and beats
                const beatDurationSeconds = (60 / this.tempo); // seconds per beat
                const chordDurationSeconds = beatDurationSeconds * chordData.beats;
                
                console.log(`Playing chord: ${chordData.chord} for ${chordDurationSeconds} seconds (${chordData.beats} beats)`);
                this.playChordDirectly(chordData.chord, chordDurationSeconds);
            } catch (error) {
                console.error('Error playing chord audio:', error);
            }
        }
        
        // Calculate duration for this chord based on beats
        const beatDuration = (60 / this.tempo) * 1000; // ms per beat
        const totalChordDuration = beatDuration * chordData.beats;
        
        // Start beat countdown
        this.startBeatCountdown(chordData.beats, beatDuration);
        
        this.beatTimer = setTimeout(() => {
            this.currentChordIndex++;
            this.playNextChord();
        }, totalChordDuration);
    }

    startBeatCountdown(totalBeats, beatDuration) {
        let currentBeat = totalBeats;
        
        // Update beat indicators immediately
        this.updateBeatIndicators(currentBeat, totalBeats);
        
        if (totalBeats > 1) {
            const beatCountdownInterval = setInterval(() => {
                currentBeat--;
                
                if (currentBeat > 0) {
                    this.updateBeatIndicators(currentBeat, totalBeats);
                } else {
                    clearInterval(beatCountdownInterval);
                }
            }, beatDuration);
            
            // Store interval reference for cleanup
            this.beatCountdownTimer = beatCountdownInterval;
        }
    }

    updateBeatIndicators(currentBeat, totalBeats) {
        // Update current chord beat indicator
        this.beatIndicator.textContent = currentBeat.toString();
        
        // Update previous chord beat indicator (show total beats)
        const previousIndex = this.currentChordIndex - 1;
        if (previousIndex >= 0 && this.songData.chords[previousIndex]) {
            const prevChord = this.songData.chords[previousIndex];
            this.previousBeatIndicator.textContent = prevChord.beats.toString();
        }
        
        // Update next chord beat indicator (show total beats)
        const nextIndex = this.currentChordIndex + 1;
        if (nextIndex < this.songData.chords.length && this.songData.chords[nextIndex]) {
            const nextChord = this.songData.chords[nextIndex];
            this.nextBeatIndicator.textContent = nextChord.beats.toString();
        }
    }

    async displayChord(chordData) {
        // Display current chord
        this.chordName.innerHTML = chordData.chord;
        await this.generateChordDiagram(chordData.chord, this.chordDiagram, 200, 250);
        
        // Update lyrics display with previous, current, and next
        this.updateLyricsDisplay();
        
        // Display previous chord
        const previousIndex = this.currentChordIndex - 1;
        if (previousIndex >= 0 && this.songData.chords[previousIndex]) {
            const prevChord = this.songData.chords[previousIndex];
            this.previousChordName.innerHTML = prevChord.chord;
            await this.generateChordDiagram(prevChord.chord, this.previousChordDiagram, 160, 200);
            document.getElementById('previous-chord').style.visibility = 'visible';
        } else {
            this.previousChordName.innerHTML = '';
            this.previousBeatIndicator.textContent = '';
            this.previousChordDiagram.innerHTML = '';
            document.getElementById('previous-chord').style.visibility = 'hidden';
        }
        
        // Display next chord
        const nextIndex = this.currentChordIndex + 1;
        if (nextIndex < this.songData.chords.length && this.songData.chords[nextIndex]) {
            const nextChord = this.songData.chords[nextIndex];
            this.nextChordName.innerHTML = nextChord.chord;
            await this.generateChordDiagram(nextChord.chord, this.nextChordDiagram, 160, 200);
            document.getElementById('next-chord').style.visibility = 'visible';
        } else {
            this.nextChordName.innerHTML = '';
            this.nextBeatIndicator.textContent = '';
            this.nextChordDiagram.innerHTML = '';
            document.getElementById('next-chord').style.visibility = 'hidden';
        }
    }

    updateSongInfo() {
        const title = this.songData.title || 'Untitled';
        
        // Update both displays
        this.songTitleMain.textContent = title;
        this.songTitleDisplay.textContent = title;
        this.tempoDisplay.innerHTML = `&#9833; = ${this.tempo}`;
        this.timeSignatureDisplay.textContent = this.timeSignature;
        
        // Show the main title when song data is loaded
        this.songTitleMain.classList.remove('hidden');
    }

    togglePause() {
        this.isPaused = !this.isPaused;
        const pauseBtn = document.getElementById('pause-btn');
        pauseBtn.innerHTML = this.isPaused ? '&#9654;' : '&#9208;';
        
        // Keep play button hidden during pause
        this.playButton.classList.add('hidden');
        
        // Handle beat countdown timer when pausing/resuming
        if(this.isPaused) {
            if (this.beatCountdownTimer) {
                clearInterval(this.beatCountdownTimer);
                this.beatCountdownTimer = null;
            }
        } else if (this.isPlaying) {
            this.playNextChord();
        }
    }

    stop() {
        this.isPlaying = false;
        this.isPaused = false;
        
        if (this.beatTimer) {
            clearTimeout(this.beatTimer);
            this.beatTimer = null;
        }
        
        if (this.beatCountdownTimer) {
            clearInterval(this.beatCountdownTimer);
            this.beatCountdownTimer = null;
        }
        
        // Add this Tone.js cleanup:
        try {
            if (typeof Tone !== 'undefined') {
                Tone.Transport.stop();
                Tone.Transport.cancel(0);
            }
        } catch (error) {
            console.log('Error stopping Tone.js audio:', error);
        }
        
        // Reset UI
        this.playerContainer.classList.add('hidden');
        this.songInfo.classList.add('hidden');
        this.controls.classList.add('hidden');
        this.countdown.classList.add('hidden');
        this.playButton.classList.remove('hidden');
        
        // Reset pause button
        document.getElementById('pause-btn').innerHTML = '&#9208;';
        
        this.currentChordIndex = 0;
    }

    updateLyricsDisplay() {
        // Get current chord data
        const currentChord = this.songData.chords[this.currentChordIndex];
        if (!currentChord) return;
        
        const currentLineIndex = currentChord.lineIndex || 0;
        const currentLine = this.songData.lyricLines[currentLineIndex];
        
        // If the current line has lyrics, show it in the current section
        if (currentLine && currentLine.hasLyrics) {
            // We're in a lyrical line - show it in current
            this.currentLyrics.textContent = currentLine.fullText;
            
            // Display previous lyrical line
            let prevLyricalLineIndex = currentLineIndex - 1;
            while (prevLyricalLineIndex >= 0) {
                const prevLine = this.songData.lyricLines[prevLyricalLineIndex];
                if (prevLine && prevLine.hasLyrics) {
                    this.previousLyrics.textContent = prevLine.fullText;
                    break;
                }
                prevLyricalLineIndex--;
            }
            if (prevLyricalLineIndex < 0) {
                this.previousLyrics.textContent = '';
            }
            
            // Display next lyrical line  
            let nextLyricalLineIndex = currentLineIndex + 1;
            while (nextLyricalLineIndex < this.songData.lyricLines.length) {
                const nextLine = this.songData.lyricLines[nextLyricalLineIndex];
                if (nextLine && nextLine.hasLyrics) {
                    this.nextLyrics.textContent = nextLine.fullText;
                    break;
                }
                nextLyricalLineIndex++;
            }
            if (nextLyricalLineIndex >= this.songData.lyricLines.length) {
                this.nextLyrics.textContent = '';
            }
        } else {
            // We're in an instrumental/intro line - show upcoming lyrical lines
            this.currentLyrics.textContent = '';
            
            // Find previous lyrical line
            let prevLyricalLineIndex = currentLineIndex - 1;
            while (prevLyricalLineIndex >= 0) {
                const prevLine = this.songData.lyricLines[prevLyricalLineIndex];
                if (prevLine && prevLine.hasLyrics) {
                    this.previousLyrics.textContent = prevLine.fullText;
                    break;
                }
                prevLyricalLineIndex--;
            }
            if (prevLyricalLineIndex < 0) {
                this.previousLyrics.textContent = '';
            }
            
            // Find next lyrical line
            let nextLyricalLineIndex = currentLineIndex + 1;
            while (nextLyricalLineIndex < this.songData.lyricLines.length) {
                const nextLine = this.songData.lyricLines[nextLyricalLineIndex];
                if (nextLine && nextLine.hasLyrics) {
                    this.nextLyrics.textContent = nextLine.fullText;
                    break;
                }
                nextLyricalLineIndex++;
            }
            if (nextLyricalLineIndex >= this.songData.lyricLines.length) {
                this.nextLyrics.textContent = '';
            }
        }
    }
}

// Initialize player when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    new SongPlayer();
});