import * as dom from './dom.js';
import * as state from './state.js';
import { generateId, deleteSection, displayChordName } from './editor.js';
import { setChordApiData } from './state.js';
import { searchChordByName } from '../my-chords.js';

// Helper function to add a new cell to an instrumental table row
function addNewInstrumentalCell(row) {
    const td = document.createElement('td');
    td.className = 'instrumental-cell';
    td.setAttribute('data-chord', '');
    td.style.textAlign = 'center';
    td.style.verticalAlign = 'middle';
    td.style.height = '20px';
    td.style.width = '48px';
    td.style.cursor = 'pointer';
    
    // 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) {
            addNewInstrumentalCell(row);
        }
    });
    
    row.appendChild(td);
}

// Expose the function globally so it can be used by chordpro.js
window.addNewInstrumentalCell = addNewInstrumentalCell;

// --- Modal Management ---
export const openModal = (modal) => {
    modal.classList.remove('hidden');
    if (modal === dom.chordSearchModal) {
        dom.chordSearchResults.innerHTML = '';
        dom.chordSearchInput.value = '';
        // Ensure Enter key triggers search every time modal is opened
        dom.chordSearchInput.onkeydown = function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                dom.chordSearchBtn.click();
            }
        };
        // Focus the input for productivity
        setTimeout(() => dom.chordSearchInput.focus(), 0);
    }
};
export const closeModal = (modal) => {
    modal.classList.add('hidden');
    if (modal === dom.chordSearchModal) {
        dom.chordSearchResults.innerHTML = '';
    }
};

// --- Chord Toolbar and Search ---
// CHANGED: The function now accepts an optional displayName.
export const createChordElement = (chordData, displayName) => {
    const display = displayName || chordData.chordName || chordData.name;
    const lookup = chordData.chordName || chordData.name;

    const newWrapper = document.createElement('div');
    newWrapper.className = 'chord-wrapper';
    const newPlaceholder = document.createElement('div');
    newPlaceholder.className = 'chord-placeholder';
    newPlaceholder.draggable = true;
    if (chordData.uuid) {
        newPlaceholder.setAttribute('data-chord-uuid', chordData.uuid);
    }

    newWrapper.appendChild(newPlaceholder);

    const span = document.createElement('span');
    span.innerText = display; // Show ASCII chord name (b/#)
    newWrapper.appendChild(span);

    // Floating delete button (now inside chord-placeholder)
    const deleteBtn = document.createElement('span');
    deleteBtn.className = 'chord-toolbar-delete-btn';
    deleteBtn.style.display = 'none';
    deleteBtn.innerHTML = '<i class="fas fa-trash"></i>';
    deleteBtn.title = 'Delete chord';
    newPlaceholder.appendChild(deleteBtn);

    newWrapper.addEventListener('mouseenter', () => {
        deleteBtn.style.display = 'block';
    });
    newWrapper.addEventListener('mouseleave', () => {
        deleteBtn.style.display = 'none';
    });

    deleteBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        // Check if chord is referenced in any lyrics-editor
        const lookupName = lookup;
        const referenced = Array.from(document.querySelectorAll('.lyrics-editor .chord')).some(
            chordSpan => chordSpan.dataset.lookupName === lookupName
        );
        if (referenced) {
            // Show tooltip or alert
            deleteBtn.title = 'Cannot delete: chord is used in lyrics';
            deleteBtn.style.color = '#d33';
            setTimeout(() => {
                deleteBtn.title = 'Delete chord';
                deleteBtn.style.color = '#888';
            }, 1500);
            return;
        }
        // Remove chord from toolbar
        newWrapper.remove();
        // Optionally remove from chordApiData and toolbarChordsSet
        if (window.toolbarChordsSet) window.toolbarChordsSet.delete(lookupName);
        if (state.chordApiData) {
            state.setChordApiData(state.chordApiData.filter(c => c.chordName !== lookupName));
        }
    });

    newPlaceholder.setAttribute('svguitar-chord', display); // The diagram title should be the display name
    newPlaceholder.setAttribute('svguitar-fingers', chordData.fingers);
    newPlaceholder.setAttribute('svguitar-barres', chordData.barres);
    newPlaceholder.setAttribute('svguitar-position', chordData.position);

    renderSvgChord(newPlaceholder);

    newPlaceholder.addEventListener('dragstart', (e) => {
        state.setDraggedChordSourceElement(null);
        // Transfer both the display and lookup names for the drop handler
        const data = JSON.stringify({
            display: display,
            lookup: lookup
        });
        e.dataTransfer.setData('application/json', data);
    });

    // Only add .chord span for lyrics, not for toolbar
    // If you need playback in lyrics, add the span elsewhere

    return newWrapper;
};

export const renderSvgChord = (chordEl) => {
    try {
        var chart = new svguitar.SVGuitarChord(chordEl);
        chart
          .configure({
                    color: '#000000', strings: 6, frets: 4, position: 1,
                    nutSize: 0, fingerSize: 0.85, strokeWidth: 4, style: 'normal',
                    orientation: 'vertical', fixedDiagramPosition: true, titleFontSize: 24
                })
          .chord({
                  title: chordEl.getAttribute('svguitar-chord'),
                    fingers: JSON.parse(chordEl.getAttribute('svguitar-fingers')),
                    barres: JSON.parse(chordEl.getAttribute('svguitar-barres')),
                    position: chordEl.getAttribute('svguitar-position')
          })
          .draw();
    } catch (error) {
        console.error("Could not render SVG chord for:", chordEl, error);
    }
};

export async function handleChordSearch() {
    dom.chordSearchResults.innerHTML = '';
    const query = dom.chordSearchInput.value.trim();
    if (!query) return;
    dom.chordSearchBtn.disabled = true;
    const originalBtnHtml = dom.chordSearchBtn.innerHTML;
    dom.chordSearchBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Searching';
    try {
        const chordResults = await searchChordByName(query);
        const autoSelect = document.getElementById('auto-select-first-chord')?.checked;
        if (chordResults && chordResults.length > 0) {
            let firstChordAdded = false;
            chordResults.forEach((chordData, idx) => {
                const display = displayChordName(chordData.chordName);
                const lookup = chordData.chordName;
                const resultItem = createChordElement({
                    ...chordData,
                    chordName: lookup,
                    uuid: chordData.uuid
                }, display);
                resultItem.classList.add('search-result-item');
                resultItem.setAttribute('data-chord-uuid', chordData.uuid);
                // Unified handler for both click and auto-select
                const selectChord = () => {
                    const newChordForToolbar = createChordElement({
                        ...chordData,
                        chordName: lookup,
                        uuid: chordData.uuid
                    }, display);
                    newChordForToolbar.setAttribute('data-chord-uuid', chordData.uuid);
                    dom.addNewChordBtn.parentElement.before(newChordForToolbar);
                    if (!state.chordApiData.some(c => c.chordName === lookup)) {
                        setChordApiData([...state.chordApiData, chordData]);
                    }
                    // Persist chord for toolbar regardless of song sections
                    if (!window.toolbarChordsSet) window.toolbarChordsSet = new Set();
                    window.toolbarChordsSet.add(lookup);
                    dom.chordSearchInput.value = '';
                    dom.chordSearchResults.innerHTML = '';
                    closeModal(dom.chordSearchModal);
                };
                resultItem.addEventListener('click', selectChord);
                dom.chordSearchResults.appendChild(resultItem);
                // Auto-select first chord if switch is on
                if (autoSelect && !firstChordAdded && idx === 0) {
                    selectChord();
                    firstChordAdded = true;
                }
            });
        } else {
            dom.chordSearchResults.innerHTML = '<div>No chord found.</div>';
        }
    } catch (err) {
        dom.chordSearchResults.innerHTML = '<div>Error searching for chord.</div>';
    } finally {
        dom.chordSearchBtn.innerHTML = originalBtnHtml;
        dom.chordSearchBtn.disabled = false;
    }
// Trigger search on Enter key in chord search input
document.getElementById('chord-search-input').addEventListener('keydown', function(e) {
    if (e.key === 'Enter') {
        e.preventDefault();
        document.getElementById('chord-search-btn').click();
    }
});
}

// --- Side Panel Management ---
export const addSection = () => {
    let type = dom.sectionTypeSelect.value;
    // Map UI dropdown values to ChordPro comment types
    if (type === 'Comment') type = 'comment';
    if (type === 'Comment Italic') type = 'comment_italic';
    if (type === 'Comment Box') type = 'comment_box';
    const songContainer = document.getElementById('song-container');
    // Count existing sections of this type in the DOM, ignoring case and whitespace
    const normalizedType = type.trim().toLowerCase();
    const typeCount = Array.from(songContainer.querySelectorAll('.song-section'))
        .filter(s => (s.dataset.type || '').trim().toLowerCase() === normalizedType).length + 1;
    const name = `${type} ${typeCount}`;
    // Create new section DOM
    if (type === 'Repeat Chorus') {
        const repeatDiv = document.createElement('div');
        repeatDiv.className = 'song-section';
        repeatDiv.id = generateId();
        repeatDiv.dataset.type = 'Repeat Chorus';
        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);
        repeatDiv.appendChild(header);
        songContainer.appendChild(repeatDiv);
        repeatDiv.scrollIntoView();
    } else if (type === 'comment' || type === 'comment_italic' || type === 'comment_box') {
        const commentDiv = document.createElement('div');
        commentDiv.className = 'song-section comment-section';
        commentDiv.id = generateId();
        commentDiv.dataset.type = type;
        const editorDiv = document.createElement('div');
        editorDiv.className = 'comment-editor';
        editorDiv.contentEditable = true;
        editorDiv.spellcheck = false;
    editorDiv.innerHTML = `<span class="char">comment...</span>`;
        // Prevent Enter/Return key from inserting new lines
        editorDiv.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
            }
        });
        // Sanitize pasted content to remove line breaks
        editorDiv.addEventListener('paste', function(e) {
            e.preventDefault();
            const text = (e.clipboardData || window.clipboardData).getData('text');
            document.execCommand('insertText', false, text.replace(/\r?\n|\r/g, ' '));
        });
        // Style according to type
        if (type === 'comment') {
            editorDiv.style.background = '#e0e0e0';
        } else if (type === 'comment_italic') {
            editorDiv.style.fontStyle = 'italic';
        } else if (type === 'comment_box') {
            editorDiv.style.border = '2px solid #888';
            editorDiv.style.padding = '8px';
            editorDiv.style.borderRadius = '6px';
        }
        commentDiv.appendChild(editorDiv);
        songContainer.appendChild(commentDiv);
        commentDiv.scrollIntoView();
    } else if (type === 'Instrumental') {
        const sectionDiv = document.createElement('div');
        sectionDiv.className = 'song-section instrumental-section';
        sectionDiv.id = generateId();
        sectionDiv.dataset.type = type;
        // Instrumental table: 1 row, 8 columns
        const table = document.createElement('table');
        table.className = 'instrumental-table';
        const tr = document.createElement('tr');
        for (let i = 0; i < 8; i++) {
            const td = document.createElement('td');
            td.className = 'instrumental-cell';
            td.setAttribute('data-chord', '');
            td.style.textAlign = 'center';
            td.style.verticalAlign = 'middle';
            td.style.height = '20px';
            td.style.width = '48px';
            td.style.cursor = 'pointer';
            // 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) {
                    addNewInstrumentalCell(row);
                }
            });
            tr.appendChild(td);
        }
        table.appendChild(tr);
        sectionDiv.appendChild(table);
        songContainer.appendChild(sectionDiv);
        sectionDiv.scrollIntoView();
    } else if (type === 'Instrumental Inline') {
        // Add instrumental table to the last existing section or create a default section if none exists
        const existingSections = songContainer.querySelectorAll('.song-section:not(.instrumental-section)');
        let targetSection = existingSections.length > 0 ? existingSections[existingSections.length - 1] : null;
        
        // If no suitable section exists, create a default section first
        if (!targetSection) {
            targetSection = document.createElement('div');
            targetSection.className = 'song-section';
            targetSection.id = generateId();
            targetSection.dataset.type = 'default';
            // Section header (hidden for default sections)
            const header = document.createElement('div');
            header.className = 'section-header';
            header.style.display = 'none';
            const headerText = document.createElement('span');
            headerText.textContent = 'Default';
            headerText.className = 'section-name';
            header.appendChild(headerText);
            targetSection.appendChild(header);
            // Lyrics editor
            const editorDiv = document.createElement('div');
            editorDiv.className = 'lyrics-editor';
            editorDiv.contentEditable = true;
            editorDiv.spellcheck = false;
            targetSection.appendChild(editorDiv);
            songContainer.appendChild(targetSection);
        }
        
        // Create instrumental table (same as standalone instrumental)
        const table = document.createElement('table');
        table.className = 'instrumental-table';
        const tr = document.createElement('tr');
        for (let i = 0; i < 8; i++) {
            const td = document.createElement('td');
            td.className = 'instrumental-cell';
            td.setAttribute('data-chord', '');
            td.style.textAlign = 'center';
            td.style.verticalAlign = 'middle';
            td.style.height = '20px';
            td.style.width = '48px';
            td.style.cursor = 'pointer';
            // 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) {
                    addNewInstrumentalCell(row);
                }
            });
            tr.appendChild(td);
        }
        table.appendChild(tr);
        
        // Add the table to the target section
        targetSection.appendChild(table);
        
        // Create a new lyrics editor after the instrumental table for continued editing
        const newEditorDiv = document.createElement('div');
        newEditorDiv.className = 'lyrics-editor';
        newEditorDiv.contentEditable = true;
        newEditorDiv.spellcheck = false;
        targetSection.appendChild(newEditorDiv);
        
        // Attach event listeners to the new editor (blur, input, drag/drop)
        if (window.attachEditorListeners) {
            window.attachEditorListeners(newEditorDiv, targetSection.id);
        }
        
        // Focus the new editor and scroll it into view
        newEditorDiv.focus();
        newEditorDiv.scrollIntoView();
    } else {
        const sectionDiv = document.createElement('div');
        sectionDiv.className = 'song-section';
        sectionDiv.id = generateId();
        sectionDiv.dataset.type = type;
        
        // Handle Page Break sections differently (no header, just indicator)
        if (type === 'Page Break') {
            sectionDiv.style.border = 'none';
            sectionDiv.style.background = 'none';
            const indicator = document.createElement('div');
            indicator.className = 'page-break-indicator';
            indicator.textContent = 'Page Break';  // Always just "Page Break", not numbered
            sectionDiv.appendChild(indicator);
        } else {
            // Section header for non-page-break sections
            const header = document.createElement('div');
            header.className = 'section-header';
            const headerText = document.createElement('span');
            headerText.textContent = name;
            header.appendChild(headerText);
            
            // Hide header for default sections
            if (type.toLowerCase() === 'default') {
                header.style.display = 'none';
            }
            
            sectionDiv.appendChild(header);
            
            // Lyrics editor
            const editorDiv = document.createElement('div');
            editorDiv.className = 'lyrics-editor';
            editorDiv.contentEditable = true;
            editorDiv.spellcheck = false;
            editorDiv.innerHTML = `<span class="char">\u200B</span>`;
            sectionDiv.appendChild(editorDiv);
            // Attach input/char span listeners
            console.log('addSection: calling attachEditorListeners', { editorDiv, sectionId: sectionDiv.id });
            if (window.attachEditorListeners) window.attachEditorListeners(editorDiv, sectionDiv.id);
        }
        songContainer.appendChild(sectionDiv);
        sectionDiv.scrollIntoView();
    }
    renderSidePanel();
};

export const renderSidePanel = () => {
    // Remove all child nodes (safe way to clear listeners)
    while (dom.sectionList.firstChild) {
        dom.sectionList.removeChild(dom.sectionList.firstChild);
    }
    // Only set up event delegation once
    if (!dom.sectionList._dblClickListenerAdded) {
        dom.sectionList.addEventListener('dblclick', (e) => {
            const sectionNameSpan = e.target.closest('.section-name');
            if (!sectionNameSpan) return;
            const li = sectionNameSpan.closest('li');
            if (!li) return;
            if (li.classList.contains('page-break-item') || li.classList.contains('instrumental-item')) {
                return;
            }
            e.stopPropagation();
            handleSectionRename(e);
        });
        dom.sectionList._dblClickListenerAdded = true;
    }
    // Iterate over DOM song sections
    const songContainer = document.getElementById('song-container');
    songContainer.querySelectorAll('.song-section').forEach(sectionDiv => {
        const li = document.createElement('li');
        li.dataset.id = sectionDiv.id;
        li.draggable = true;
        let name = '';
        if (sectionDiv.dataset.type === 'Page Break') {
            li.classList.add('page-break-item');
            name = 'Page Break';
        } else if (sectionDiv.dataset.type === 'Instrumental' || sectionDiv.dataset.type === 'Instrumental Inline') {
            li.classList.add('instrumental-item');
            name = sectionDiv.dataset.type === 'Instrumental Inline' ? 'Instrumental Inline' : 'Instrumental';
        } else {
            name = sectionDiv.querySelector('.section-header span')?.textContent || '';
        }
        const sectionName = document.createElement('span');
        sectionName.className = 'section-name';
        sectionName.textContent = name;
        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'delete-section-btn-panel';
        deleteBtn.innerHTML = '&times;';
        li.appendChild(sectionName);
        li.appendChild(deleteBtn);
        dom.sectionList.appendChild(li);
    });
};
// Ensure renderSidePanel is available globally for import logic
window.renderSidePanel = renderSidePanel;

window.handleSectionRename = handleSectionRename;
    export function handleSectionRename(e) {
    const sectionNameSpan = e.target.closest('.section-name');
    if (!sectionNameSpan) return;
    const targetLi = sectionNameSpan.closest('li');
    if (!targetLi) return;
    const sectionId = targetLi.dataset.id;
    // Find section in DOM
    const sectionDiv = document.getElementById(sectionId);
    if (!sectionDiv || sectionDiv.dataset.type === 'Page Break') return;

    const headerSpan = sectionDiv.querySelector('.section-header span');
    if (!headerSpan) return;

    const input = document.createElement('input');
    input.type = 'text';
    input.value = headerSpan.textContent;
    input.className = 'section-name-input';

    const save = () => {
        const newName = input.value.trim();
        if (newName) {
            headerSpan.textContent = newName;
            // Only re-render sidebar after name is changed
            renderSidePanel();
        } else {
            // If name is empty, revert to previous name
            renderSidePanel();
        }
    };

    input.addEventListener('blur', () => {
        // Only save if input is not already replaced
        if (document.activeElement !== input) save();
    });
    input.addEventListener('keydown', (ev) => {
        if (ev.key === 'Enter') {
            save();
        } else if (ev.key === 'Escape') {
            renderSidePanel();
        }
    });

    sectionNameSpan.replaceWith(input);
    input.focus();
    input.select();
}
    window.handleSectionRename = handleSectionRename;

export function handleSectionDrop(e) {
    e.preventDefault();
    const targetLi = e.target.closest('li');
    if (targetLi) {
        targetLi.classList.remove('drag-over');
        const droppedOnSectionId = targetLi.dataset.id;
        const draggedSectionId = state.draggedSectionId;
        if (!draggedSectionId || !droppedOnSectionId) return;
        // Reorder DOM nodes in song-container
        const songContainer = document.getElementById('song-container');
        const draggedDiv = document.getElementById(draggedSectionId);
        const droppedOnDiv = document.getElementById(droppedOnSectionId);
        if (draggedDiv && droppedOnDiv && songContainer) {
            songContainer.insertBefore(draggedDiv, droppedOnDiv);
            renderSidePanel();
        }
    }
}
