import * as dom from './dom.js';
import * as state from './state.js';
import {  generateId, parseChordPro, normalizeChordName, convertToSharp, attachDragHandlerToChord, displayChordName } from './editor.js';
import { setSongSections } from './state.js';
import { renderChordsInToolbar } from './chords.js';

window.attachDragHandlerToChord = attachDragHandlerToChord;


// Helper function to convert Unicode musical symbols back to ASCII for export
function toAsciiChordName(chordName) {
    return chordName.replace(/♭/g, 'b').replace(/♯/g, '#');
}

export const generateChordPro = (includeAnnotations = false) => {
    let output = '';
    const title = document.getElementById('song-title').value;
    const artist = document.getElementById('song-artist').value;
    const copyright = document.getElementById('song-copyright').value;

    if(title) output += `{title: ${title}}\n`;
    if(artist) output += `{artist: ${artist}}\n`;
    if(copyright) output += `{copyright: ${copyright}}\n`;
    // Export tempo directive
    const tempo = (typeof dom.tempoInput !== 'undefined' && dom.tempoInput.value) ? dom.tempoInput.value : '';
    if (tempo) output += `{tempo: ${tempo}}\n`;
    // Export time signature directive
    const timeSig = (typeof dom.timeSignatureSelect !== 'undefined' && dom.timeSignatureSelect.value) ? dom.timeSignatureSelect.value : '';
    if (timeSig) output += `{time: ${timeSig}}\n`;
    // Add meta tags for each chord in the toolbar
    const toolbar = document.getElementById('chord-toolbar');
    if (toolbar) {
        toolbar.querySelectorAll('.chord-placeholder[data-chord-uuid]').forEach(placeholder => {
            const wrapper = placeholder.parentElement;
            const chordSpan = wrapper.querySelector('.chord');
            const chordName = chordSpan ? (chordSpan.dataset.lookupName || chordSpan.dataset.chord || chordSpan.textContent.trim()) : '';
            const uuid = placeholder.getAttribute('data-chord-uuid');
            if (chordName && uuid) {
                output += `{meta: ${chordName} ${uuid}}\n`;
            }
        });
    }
    output += '\n';

    // Traverse DOM to reconstruct ChordPro
    const songContainer = document.getElementById('song-container');
    const sections = songContainer.querySelectorAll('.song-section');
    sections.forEach(sectionDiv => {
        const type = sectionDiv.dataset.type || '';
        if (type === 'Page Break') {
            output += '{new_page}\n\n';
            return;
        }
        if (type === 'Repeat Chorus') {
            output += '{chorus}\n\n';
            return;
        }
        // Handle ChordPro comment directives
        if (type === 'comment' || type === 'comment_italic' || type === 'comment_box') {
            const editorDiv = sectionDiv.querySelector('.comment-editor');
            let commentText = '';
            if (editorDiv) {
                // Only take the first line of text content
                commentText = editorDiv.textContent.split(/\r?\n/)[0].trim();
            }
            if (commentText) {
                output += `{${type}: ${commentText}}\n`;
            }
            return;
        }

        // Instrumental section: output only the chord line, no section directives
        if (type === 'Instrumental' || sectionDiv.classList.contains('instrumental-section')) {
            const table = sectionDiv.querySelector('table.instrumental-table');
            if (table) {
                const cells = table.querySelectorAll('td.instrumental-cell');
                let chordLine = '';
                cells.forEach((td, idx) => {
                    // Use .char[data-chord] for export
                    const charSpan = td.querySelector('.char[data-chord]');
                    if (charSpan) {
                        const chord = toAsciiChordName(charSpan.dataset.chord);
                        const beats = charSpan.dataset.beats;
                        if (includeAnnotations && beats) {
                            chordLine += `[${chord};${beats}]`;
                        } else {
                            chordLine += `[${chord}]`;
                        }
                        if (idx < cells.length - 1) chordLine += '   ';
                    }
                });
                if (chordLine.trim()) output += chordLine + '\n';
            }
            output += '\n';
            return;
        }

        // ...existing code for other section types...
        if (!(type === 'Instrumental' || sectionDiv.classList.contains('instrumental-section'))) {
            const headerText = sectionDiv.querySelector('.section-header span')?.textContent || '';
            const sectionTypeDirective = type.toLowerCase().replace(/\s+/g, '_');
            
            // Don't add section directives for default sections (lyrics without start/end directives in original)
            const isDefaultSection = type.toLowerCase() === 'default';
            
            if (!isDefaultSection) {
                output += `{start_of_${sectionTypeDirective}: ${headerText}}\n`;
            }
            
            // Process all child elements of the section in order (lyrics editors and instrumental tables)
            Array.from(sectionDiv.children).forEach(child => {
                // Skip the section header
                if (child.classList.contains('section-header')) {
                    return;
                }
                
                // Process lyrics editors
                if (child.classList.contains('lyrics-editor')) {
                    // Helper function to process nodes and extract lyrics/chords
                    const processNodes = (container) => {
                        let lineBuffer = '';
                        container.childNodes.forEach(node => {
                            if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains('char')) {
                                const chord = node.dataset.chord;
                                const beats = node.dataset.beats;
                                
                                // Get only the direct text content, excluding child elements like beat badges
                                let charText = '';
                                Array.from(node.childNodes).forEach(childNode => {
                                    if (childNode.nodeType === Node.TEXT_NODE) {
                                        charText += childNode.textContent;
                                    }
                                });
                                
                                if (chord) {
                                    const asciiChord = toAsciiChordName(chord);
                                    if (includeAnnotations && beats) {
                                        lineBuffer += `[${asciiChord};${beats}]${charText}`;
                                    } else {
                                        lineBuffer += `[${asciiChord}]${charText}`;
                                    }
                                } else {
                                    lineBuffer += charText;
                                }
                            } else if (node.nodeType === Node.ELEMENT_NODE) {
                                // Skip beat badges and delete icons during export
                                if (node.classList.contains('chord-beat-badge') || 
                                    node.classList.contains('chord-lyrics-delete-btn') ||
                                    node.classList.contains('inline-beat-badge')) {
                                    return; // Skip these elements
                                }
                                // For other elements, include their text content
                                lineBuffer += node.textContent;
                            } else if (node.nodeType === Node.TEXT_NODE) {
                                lineBuffer += node.textContent;
                            }
                        });
                        if (lineBuffer.trim()) {
                            output += lineBuffer + '\n';
                        }
                    };
                    
                    // Process content within div elements (multi-line content)
                    child.querySelectorAll('div').forEach(lineDiv => {
                        processNodes(lineDiv);
                    });
                    
                    // Also process direct children of the editor (single-line content without divs)
                    // But only if there are no div children (to avoid duplicating content)
                    if (child.querySelectorAll('div').length === 0) {
                        processNodes(child);
                    }
                }
                
                // Process instrumental tables
                else if (child.classList.contains('instrumental-table')) {
                    const cells = child.querySelectorAll('td.instrumental-cell');
                    let chordLine = '';
                    cells.forEach((td, idx) => {
                        // Use .char[data-chord] for export
                        const charSpan = td.querySelector('.char[data-chord]');
                        if (charSpan) {
                            const chord = toAsciiChordName(charSpan.dataset.chord);
                            const beats = charSpan.dataset.beats;
                            if (includeAnnotations && beats) {
                                chordLine += `[${chord};${beats}]`;
                            } else {
                                chordLine += `[${chord}]`;
                            }
                            if (idx < cells.length - 1) chordLine += '   ';
                        }
                    });
                    if (chordLine.trim()) output += chordLine + '\n';
                }
            });
            
            if (!isDefaultSection) {
                output += `{end_of_${sectionTypeDirective}}\n\n`;
            } else {
                output += '\n'; // Just add spacing for default sections
            }
        }
    });
    return output.trim();
};

export const importFromChordPro = async (text) => {
    let sectionType = '';
    let sectionName = '';
    const songDiv = document.getElementById('song');
    const songContainer = document.getElementById('song-container');
    // Clear previous song content and sections
    songDiv.innerHTML = '';
    songContainer.innerHTML = '';
    // Clear side panel section list
    if (dom.sectionList) {
        dom.sectionList.innerHTML = '';
    } else {
        const sectionList = document.getElementById('section-list');
        if (sectionList) sectionList.innerHTML = '';
    }
    let newSections = [];
    document.getElementById('song-title').value = '';
    document.getElementById('song-artist').value = '';
    document.getElementById('song-copyright').value = '';

    let lines = text.split('\n');
    // Look for tempo and time signature directives and set inputs
    lines.forEach(line => {
        const trimmed = line.trim();
        // Ignore meta tags
        if (trimmed.match(/^\{meta:/i)) return;
        const tempoMatch = trimmed.match(/^\{tempo:\s*(\d+)}/i);
        if (tempoMatch && typeof dom.tempoInput !== 'undefined') {
            dom.tempoInput.value = tempoMatch[1];
        }
        const timeMatch = trimmed.match(/^\{time:\s*([\d]+\/[\d]+)}/i);
        if (timeMatch && typeof dom.timeSignatureSelect !== 'undefined') {
            dom.timeSignatureSelect.value = timeMatch[1];
        }
    });
    let currentSectionDiv = null;
    let currentSection = null;

    // Use a Map to store the sharp-normalized name as the key and the original as the value.
    // This guarantees API lookup/playback will always work.
    const uniqueChordsMap = new Map();
    window.preferFlats = false;
    const chordRegex = /\[([^\]]+)\]/g;
    lines.forEach(line => {
        let match;
        while ((match = chordRegex.exec(line)) !== null) {
            const originalName = match[1];
            // Always normalize to sharp for API lookup and data-lookup-name
            const sharpName = convertToSharp(normalizeChordName(originalName));
            if (!uniqueChordsMap.has(sharpName)) {
                uniqueChordsMap.set(sharpName, originalName);
            }
            if (originalName.match(/^[A-G]b/)) {
                window.preferFlats = true;
            }
        }
    });

    // Pre-scan to check if there are any actual lyric lines (non-chord-only lines)
    let hasLyricLines = false;
    const chordOnlyRegex = /^\s*(\[[^\]]+\]\s*)+$/;
    
    lines.forEach(line => {
        const trimmedLine = line.trim();
        // Skip empty lines, metadata, directives, and chord definitions
        if (trimmedLine === '') return;
        if (trimmedLine.match(/^(title|artist|copyright|t|st):/i)) return;
        if (trimmedLine.match(/^(start_of_|end_of_|new_page)/i)) return;
        if (trimmedLine.match(/^\{.*\}/)) return; // Skip all directives
        
        // If this is not a chord-only line, we have lyrics
        if (!chordOnlyRegex.test(trimmedLine)) {
            hasLyricLines = true;
        }
    });

    let insideSection = false;
    lines.forEach(line => {
        const trimmedLine = line.trim();
        // Skip chorus directives in first pass - they'll be handled in the main parsing loop

        const directiveMatch = trimmedLine.match(/\{(\w+):\s*(.*)}/);
        if (directiveMatch) {
            const key = directiveMatch[1].toLowerCase();
            if (key.startsWith('start_of_')) {
                insideSection = true;
            } else if (key.startsWith('end_of_')) {
                insideSection = false;
            }
            // ...existing directive handling code...
        } else if (trimmedLine.toLowerCase() === '{new_page}') {
            // ...existing page break code...
        } else if (trimmedLine.match(/^\{end_of_/)) {
            insideSection = false;
            // ...skip end_of_*...
        } else {
            // Only process non-empty, non-metadata lines
            if (trimmedLine === '') return;
            if (trimmedLine.match(/^(title|artist|copyright|t|st):/i)) return;
            if (trimmedLine.match(/^(start_of_|end_of_|new_page)/i)) return;
            if (trimmedLine.match(/^\{chord:/i)) return;
            if (trimmedLine.toLowerCase() === '{chorus}' || trimmedLine.toLowerCase() === '{start_of_chorus}') return; // Skip chorus in first pass
            
            // Skip chord-only lines in this first pass - they'll be handled by the main parsing loop
            if (chordOnlyRegex.test(trimmedLine)) return;
            
            // Only create default section for actual lyrics NOT inside a section AND only if we have lyric lines
            // Also skip if we have any sectioned content at all to avoid duplication
            if (!insideSection && hasLyricLines && !lines.some(l => l.trim().match(/^\{start_of_/))) {
                if (!currentSectionDiv) {
                    currentSectionDiv = createSectionDiv('default');
                    songContainer.appendChild(currentSectionDiv);
                }
                const editorDiv = currentSectionDiv.querySelector('.lyrics-editor');
                if (editorDiv) {
                    // Render ChordPro line to HTML
                    const html = parseChordPro(line);
                    const lineDiv = document.createElement('div');
                    lineDiv.innerHTML = html;
                    lineDiv.querySelectorAll('.char[data-chord]').forEach(charSpan => {
                        const chordText = charSpan.dataset.chord;
                        const normalizedSharp = convertToSharp(normalizeChordName(chordText));
                        const asciiSharp = normalizedSharp.replace(/♭/g, 'b').replace(/♯/g, '#');
                        charSpan.dataset.lookupName = asciiSharp;
                        if (charSpan.dataset.beats) {
                            charSpan.dataset.beats = charSpan.dataset.beats;
                        } else {
                            charSpan.removeAttribute('data-beats');
                        }
                        if (window.attachChordHoverActions) window.attachChordHoverActions(charSpan);
                    });
                    setTimeout(() => {
                        document.querySelectorAll('.lyrics-editor').forEach((editorDiv) => {
                            if (window.attachEditorListeners) {
                                window.attachEditorListeners(editorDiv, editorDiv.closest('.song-section')?.id);
                            }
                        });
                    }, 0);
                    editorDiv.appendChild(lineDiv);
                    if (window.ensureCharSpansInLyricsEditor) window.ensureCharSpansInLyricsEditor(editorDiv);
                }
            }
        }
    });

    // After parsing, set currentChordsMap for toolbar
    window.currentChordsMap = new Map();
    uniqueChordsMap.forEach((original, sharpName) => {
        window.currentChordsMap.set(sharpName, original);
    });
    // Optionally update toolbar and chord cache if needed
    if (typeof window.updateChordDisplayForPreferFlats === 'function') {
        window.updateChordDisplayForPreferFlats();
    }
    // Update sidebar section list after import
    if (typeof window.renderSidePanel === 'function') {
        window.renderSidePanel();
    }
// End of importFromChordPro

    // Helper to convert chord display to match preferFlat state
    const FLAT_TO_SHARP = { 'Db': 'C#', 'Eb': 'D#', 'Gb': 'F#', 'Ab': 'G#', 'Bb': 'A#', 'Cb': 'B', 'Fb': 'E' };
    const SHARP_TO_FLAT = { 'C#': 'Db', 'D#': 'Eb', 'F#': 'Gb', 'G#': 'Ab', 'A#': 'Bb' };
    function convertChord(name, preferFlat) {
        const matchFlat = name.match(/^([A-G]b)(.*)$/);
        const matchSharp = name.match(/^([A-G]#)(.*)$/);
        if (preferFlat && matchSharp && SHARP_TO_FLAT[matchSharp[1]]) {
            return SHARP_TO_FLAT[matchSharp[1]] + matchSharp[2];
        }
        if (!preferFlat && matchFlat && FLAT_TO_SHARP[matchFlat[1]]) {
            return FLAT_TO_SHARP[matchFlat[1]] + matchFlat[2];
        }
        return name;
    }

    // Clear song meta fields
    document.getElementById('song-title').value = '';
    document.getElementById('song-artist').value = '';
    document.getElementById('song-copyright').value = '';

    // Parse ChordPro and render directly to DOM
    lines.forEach(line => {
        const trimmedLine = line.trim();
        const directiveMatch = trimmedLine.match(/{(\w+):\s*(.*)}/);
        if (directiveMatch) {
            let key = directiveMatch[1].toLowerCase();
            const value = directiveMatch[2];
            if (key === 't') key = 'title';
            if (key === 'st') key = 'artist';
            if (key === 'title') {
                document.getElementById('song-title').value = value;
            } else if (key === 'artist') {
                document.getElementById('song-artist').value = value;
            } else if (key === 'copyright') {
                document.getElementById('song-copyright').value = value;
                if(value) {
                    document.getElementById('copyright-label').style.display = 'inline';
                }
            } else if (key === 'comment' || key === 'comment_italic' || key === 'comment_box') {
                // Render ChordPro comment directives as editable comment sections
                const commentDiv = document.createElement('div');
                commentDiv.className = 'song-section comment-section';
                commentDiv.id = generateId();
                commentDiv.dataset.type = key;
                const editorDiv = document.createElement('div');
                editorDiv.className = 'comment-editor';
                editorDiv.contentEditable = true;
                editorDiv.spellcheck = false;
                editorDiv.textContent = value;
                // Style according to type
                if (key === 'comment') {
                    editorDiv.style.background = '#e0e0e0';
                } else if (key === 'comment_italic') {
                    editorDiv.style.fontStyle = 'italic';
                } else if (key === 'comment_box') {
                    editorDiv.style.border = '2px solid #888';
                    editorDiv.style.padding = '8px';
                    editorDiv.style.borderRadius = '6px';
                }
                commentDiv.appendChild(editorDiv);
                songContainer.appendChild(commentDiv);
                currentSectionDiv = null;
            } else if (key.startsWith('start_of_')) {
                sectionType = key.replace('start_of_', '').replace(/_/g, ' ');
                sectionName = value;
                if (sectionType.toLowerCase() === 'repeat chorus') {
                    // Render as a comment directive
                    const commentDiv = document.createElement('div');
                    commentDiv.className = 'song-section';
                    commentDiv.dataset.type = 'Comment';
                    const header = document.createElement('div');
                    header.className = 'section-header';
                    const headerText = document.createElement('span');
                    headerText.textContent = 'Repeat Chorus';
                    headerText.className = 'section-name';
                    headerText.style.fontStyle = 'italic';
                    header.appendChild(headerText);
                    commentDiv.appendChild(header);
                    songContainer.appendChild(commentDiv);
                    currentSectionDiv = null;
                } else {
                    currentSectionDiv = document.createElement('div');
                    currentSectionDiv.className = 'song-section';
                    currentSectionDiv.id = generateId();
                    currentSectionDiv.dataset.type = sectionType;
                    // Section header
                    const header = document.createElement('div');
                    header.className = 'section-header';
                    const headerText = document.createElement('span');
                    // Use section type as default when sectionName is empty
                    headerText.textContent = sectionName || sectionType.charAt(0).toUpperCase() + sectionType.slice(1);
                    headerText.className = 'section-name';
                    headerText.addEventListener('dblclick', (e) => {
                        e.stopPropagation();
                        window.handleSectionRename(e);
                    });
                    header.appendChild(headerText);
                    currentSectionDiv.appendChild(header);
                    // Lyrics editor
                    const editorDiv = document.createElement('div');
                    editorDiv.className = 'lyrics-editor';
                    editorDiv.contentEditable = true;
                    editorDiv.spellcheck = false;
                    currentSectionDiv.appendChild(editorDiv);
                    songContainer.appendChild(currentSectionDiv);
                }
            } else if (key.startsWith('end_of_')) {
                currentSectionDiv = null;
            }
        } else if (trimmedLine.toLowerCase() === '{new_page}') {
            const pageBreakDiv = document.createElement('div');
            pageBreakDiv.className = 'song-section';
            pageBreakDiv.id = generateId();
            pageBreakDiv.dataset.type = 'Page Break';
            // Only add the visual indicator, not the header
            const indicator = document.createElement('div');
            indicator.className = 'page-break-indicator';
            indicator.textContent = 'Page Break';
            pageBreakDiv.appendChild(indicator);
            songContainer.appendChild(pageBreakDiv);
        } else if (trimmedLine.toLowerCase() === '{chorus}') {
            // Create a Repeat Chorus section in the DOM at the correct position
            const repeatChorusDiv = createSectionDiv('Repeat Chorus');
            repeatChorusDiv.id = generateId();
            songContainer.appendChild(repeatChorusDiv);
            currentSectionDiv = null; // Reset current section after adding repeat chorus
        } else if (trimmedLine.toLowerCase() === '{start_of_chorus}') {
            // Handle {start_of_chorus} without colon as a regular chorus section with empty label
            currentSectionDiv = document.createElement('div');
            currentSectionDiv.className = 'song-section';
            currentSectionDiv.id = generateId();
            currentSectionDiv.dataset.type = 'chorus';
            // Section header
            const header = document.createElement('div');
            header.className = 'section-header';
            const headerText = document.createElement('span');
            headerText.textContent = 'Chorus'; // Default to "Chorus" when no label
            headerText.className = 'section-name';
            headerText.addEventListener('dblclick', (e) => {
                e.stopPropagation();
                window.handleSectionRename(e);
            });
            header.appendChild(headerText);
            currentSectionDiv.appendChild(header);
            // Lyrics editor
            const editorDiv = document.createElement('div');
            editorDiv.className = 'lyrics-editor';
            editorDiv.contentEditable = true;
            editorDiv.spellcheck = false;
            currentSectionDiv.appendChild(editorDiv);
            songContainer.appendChild(currentSectionDiv);
        } else if (trimmedLine.match(/^\{end_of_/)) {
            // Skip rendering end_of_* directives as lyrics
        } else {
            // Only process non-empty, non-metadata lines
            if (trimmedLine === '') return; // skip blank lines
            if (trimmedLine.match(/^\{(title|artist|copyright|t|st):/i)) return; // skip metadata
            if (trimmedLine.match(/^\{(start_of_|end_of_|new_page)/i)) return; // skip section/page directives
            
            // Check if this line contains only chords (no lyrics between chords)
            const chordOnlyRegex = /^\s*(\[[^\]]+\]\s*)+$/;
            const isChordOnlyLine = chordOnlyRegex.test(trimmedLine);
            
            if (isChordOnlyLine) {
                // Extract chords from the line
                const chords = [];
                const chordMatches = trimmedLine.matchAll(/\[([^\]]+)\]/g);
                for (const match of chordMatches) {
                    chords.push(match[1]);
                }
                
                // Create instrumental table
                const table = document.createElement('table');
                table.className = 'instrumental-table';
                const tr = document.createElement('tr');
                
                // Create cells: minimum 8, or chords + 1 (for next chord), up to maximum 16
                const cellCount = Math.min(16, Math.max(8, chords.length + 1));
                for (let i = 0; i < cellCount; i++) {
                    const td = document.createElement('td');
                    td.className = 'instrumental-cell';
                    td.style.textAlign = 'center';
                    td.style.verticalAlign = 'middle';
                    td.style.height = '20px';
                    td.style.width = '48px';
                    td.style.cursor = 'pointer';
                    
                    // If we have a chord for this position, add it
                    if (i < chords.length) {
                        const chordText = chords[i];
                        // Support [Chord;Beats] format
                        const chordParts = chordText.split(';');
                        const originalChord = chordParts[0];
                        const beats = chordParts.length > 1 ? chordParts[1] : null;
                        
                        const charSpan = document.createElement('span');
                        charSpan.className = 'char has-chord-display';
                        charSpan.textContent = '\u00A0';
                        charSpan.setAttribute('data-chord', originalChord);
                        
                        // Create chord-display element for visual display with HTML entities
                        const chordDisplayEl = document.createElement('span');
                        chordDisplayEl.className = 'chord-display';
                        chordDisplayEl.innerHTML = displayChordName(originalChord);
                        charSpan.appendChild(chordDisplayEl);
                        
                        if (beats) {
                            charSpan.setAttribute('data-beats', beats);
                        }
                        
                        // Set lookup name for playback
                        const normalizedSharp = convertToSharp(normalizeChordName(originalChord));
                        const asciiSharp = normalizedSharp.replace(/♭/g, 'b').replace(/♯/g, '#');
                        charSpan.dataset.lookupName = asciiSharp;
                        
                        if (window.attachChordHoverActions) window.attachChordHoverActions(charSpan);
                        
                        td.setAttribute('data-chord', originalChord);
                        td.appendChild(charSpan);
                    } else {
                        td.setAttribute('data-chord', '');
                    }
                    
                    // Allow dropping a chord from the toolbar
                    td.addEventListener('dragover', function(e) { e.preventDefault(); });
                    td.addEventListener('drop', function(e) {
                        e.preventDefault();
                        let data = e.dataTransfer.getData('application/json');
                        if (!data) return;
                        let chordObj;
                        try { chordObj = JSON.parse(data); } catch {}
                        if (!chordObj || !chordObj.display) return;
                        td.innerHTML = '';
                        // Render chord as .char[data-chord] for instrumental using dual-attribute system
                        const charSpan = document.createElement('span');
                        charSpan.className = 'char has-chord-display';
                        charSpan.textContent = '\u00A0';
                        charSpan.setAttribute('data-chord', chordObj.display);
                        // Create chord-display element for visual display with HTML entities
                        const chordDisplayEl = document.createElement('span');
                        chordDisplayEl.className = 'chord-display';
                        chordDisplayEl.innerHTML = displayChordName(chordObj.display);
                        charSpan.appendChild(chordDisplayEl);
                        // Optionally set beats if available
                        if (chordObj.beats) {
                            charSpan.setAttribute('data-beats', chordObj.beats);
                        }
                        // Set lookup name for playback (ensure ASCII only)
                        const toAscii = (name) => name.replace(/♭/g, 'b').replace(/♯/g, '#').replace(/&#9837;/g, 'b').replace(/&#9839;/g, '#');
                        charSpan.dataset.lookupName = chordObj.lookup || toAscii(chordObj.display);
                        // Pass true flag to indicate this is from a drop operation
                        if (window.attachChordHoverActions) window.attachChordHoverActions(charSpan, true);
                        td.setAttribute('data-chord', chordObj.display);
                        td.appendChild(charSpan);
                        
                        // Check if all cells are filled and add new cell if needed (up to max 16)
                        const table = td.closest('table');
                        const row = td.parentElement;
                        const allCells = Array.from(row.querySelectorAll('td'));
                        const filledCells = allCells.filter(cell => cell.getAttribute('data-chord') && cell.getAttribute('data-chord') !== '');
                        
                        // If all cells are filled and we haven't reached the maximum of 16 cells
                        if (filledCells.length === allCells.length && allCells.length < 16) {
                            if (window.addNewInstrumentalCell) window.addNewInstrumentalCell(row);
                        }
                    });
                    
                    tr.appendChild(td);
                }
                
                table.appendChild(tr);
                
                // Always create a separate instrumental section for each chord-only line
                const instrumentalDiv = document.createElement('div');
                instrumentalDiv.className = 'song-section instrumental-section';
                instrumentalDiv.id = generateId();
                
                // Determine section type based on context
                if (currentSectionDiv) {
                    instrumentalDiv.dataset.type = 'Instrumental Inline';
                } else {
                    instrumentalDiv.dataset.type = 'Instrumental';
                }
                
                instrumentalDiv.appendChild(table);
                songContainer.appendChild(instrumentalDiv);
            } else {
                // Regular lyric line - process as before
                // If no section has been started, create a default section
                if (!currentSectionDiv) {
                    currentSectionDiv = createSectionDiv('default');
                    songContainer.appendChild(currentSectionDiv);
                }
                
                // Find or create a lyrics editor for this lyric line
                // We'll create a new lyrics block if the last element is an instrumental table
                let editorDiv = currentSectionDiv.querySelector('.lyrics-editor:last-of-type');
                const lastChild = currentSectionDiv.lastElementChild;
                
                // If the last element is not a lyrics editor, create a new one
                if (!editorDiv || (lastChild && lastChild.classList.contains('instrumental-table'))) {
                    editorDiv = document.createElement('div');
                    editorDiv.className = 'lyrics-editor';
                    editorDiv.contentEditable = true;
                    editorDiv.spellcheck = false;
                    currentSectionDiv.appendChild(editorDiv);
                }
                
                if (editorDiv) {
                    // Render ChordPro line to HTML
                    const html = parseChordPro(line);
                    // Always wrap each line in a div for drag-and-drop support
                    const lineDiv = document.createElement('div');
                    lineDiv.innerHTML = html;
                    // For each chord span, set data-lookup-name and data-beats if present
                    lineDiv.querySelectorAll('.chord').forEach(chordSpan => {
                        const chordText = chordSpan.dataset.chord || chordSpan.textContent;
                        // Always normalize to sharp ASCII for lookup
                        const normalizedSharp = convertToSharp(normalizeChordName(chordText));
                        const asciiSharp = normalizedSharp.replace(/♭/g, 'b').replace(/♯/g, '#');
                        chordSpan.dataset.lookupName = asciiSharp;
                        // If the chord annotation was [Chord;Beats], set data-beats from annotation
                        const beatsMatch = chordSpan.outerHTML.match(/data-beats="(\d+)"/);
                        if (beatsMatch) {
                            chordSpan.dataset.beats = beatsMatch[1];
                        } else {
                            chordSpan.removeAttribute('data-beats');
                        }
                        if (window.attachDragHandlerToChord) {
                            window.attachDragHandlerToChord(chordSpan);
                        }
                    });

                    // Ensure all lyrics-editors have event listeners attached
                    setTimeout(() => {
                        document.querySelectorAll('.lyrics-editor').forEach((editorDiv) => {
                            if (window.attachEditorListeners) {
                                console.log('importFromChordPro: calling attachEditorListeners', { editorDiv, sectionId: editorDiv.closest('.song-section')?.id });
                                window.attachEditorListeners(editorDiv, editorDiv.closest('.song-section')?.id);
                            }
                        });
                    }, 0);
                    
                    editorDiv.appendChild(lineDiv);
                    // Ensure all text nodes are wrapped in .char spans after import
                    if (window.ensureCharSpansInLyricsEditor) window.ensureCharSpansInLyricsEditor(editorDiv);
                    // Attach dragover/drop listeners to all .char spans after import
                    /*if (window.attachCharDropListeners) window.attachCharDropListeners(editorDiv);*/
                }
            }
// Patch paste and input events to ensure .char spans
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.lyrics-editor').forEach(editor => {
        editor.addEventListener('paste', (e) => {
            setTimeout(() => {
                if (window.ensureCharSpansInLyricsEditor) window.ensureCharSpansInLyricsEditor(editor);
            }, 0);
        });
        editor.addEventListener('input', (e) => {
            setTimeout(() => {
                if (window.ensureCharSpansInLyricsEditor) window.ensureCharSpansInLyricsEditor(editor);
            }, 0);
        });
    });
});
        }
    });
    // After parsing, set currentChordsMap for toolbar
    window.currentChordsMap = new Map();
    uniqueChordsMap.forEach((original, sharpName) => {
        window.currentChordsMap.set(sharpName, original);
    });
    // Optionally update toolbar and chord cache if needed
    if (typeof window.updateChordDisplayForPreferFlats === 'function') {
        window.updateChordDisplayForPreferFlats();
    }
    // Update sidebar section list after import
    if (typeof window.renderSidePanel === 'function') {
        window.renderSidePanel();
    }
};

function createSectionDiv(type) {
    const sectionDiv = document.createElement('div');
    sectionDiv.className = 'song-section';
    sectionDiv.dataset.type = type;
    // Section header (hide for default sections)
    const headerDiv = document.createElement('div');
    headerDiv.className = 'section-header';
    const span = document.createElement('span');
    span.textContent = type.charAt(0).toUpperCase() + type.slice(1);
    headerDiv.appendChild(span);
    
    // Hide header for default sections
    if (type.toLowerCase() === 'default') {
        headerDiv.style.display = 'none';
    }
    
    sectionDiv.appendChild(headerDiv);
    
    // Only add lyrics editor for sections that should be editable
    if (type.toLowerCase() !== 'repeat chorus') {
        // Lyrics editor
        const lyricsDiv = document.createElement('div');
        lyricsDiv.className = 'lyrics-editor';
        lyricsDiv.contentEditable = true;
        lyricsDiv.spellcheck = false;
        sectionDiv.appendChild(lyricsDiv);
        // Attach input event handlers after creating lyrics editor
        if (window.attachEditorListeners) {
            console.log('chordpro import: calling attachEditorListeners', { lyricsDiv, sectionId: sectionDiv.id });
            window.attachEditorListeners(lyricsDiv, sectionDiv.id);
        }
    }
    return sectionDiv;
};
