// ...existing imports...
// Show/hide copyright label based on input value
const copyrightInput = document.getElementById('song-copyright');
const copyrightLabel = document.getElementById('copyright-label');
function updateCopyrightLabel() {
    if (copyrightInput.value.trim() !== '') {
        copyrightLabel.style.display = '';
    } else {
        copyrightLabel.style.display = 'none';
    }
}
copyrightInput.addEventListener('input', updateCopyrightLabel);
updateCopyrightLabel();

// Update display of chord names in songSections to match preferFlat state
function updateStoredChordNamesForPreferFlats() {
    for (const section of state.songSections) {
        if (!section.content) continue;
        section.content = section.content.replace(/<span class="chord" data-lookup-name="([^"]+)">([^<]+)<\/span>/g,
            (m, lookupName, displayName) => {
                // lookupName is always ASCII
                return `<span class="chord" data-lookup-name="${lookupName}">${displayChordName(lookupName, window.preferFlats)}</span>`;
            }
        );
    }
}
import { transposeAllChords, displayChordName, convertToFlat, convertToSharp, transposeAllChordsDOM } from './editor.js';
import { renderChordsInToolbar } from './chords.js';
import * as dom from './dom.js';
import * as state from './state.js';
import { initializeChordData } from './chords.js';
window.initializeChordData = initializeChordData;
import { initAudio, loadInstrument, startPlayback } from './audio.js';
import { renderSong, deleteSection } from './editor.js';
import {
    openModal,
    closeModal,
    addSection,
    handleSectionRename,
    handleSectionDrop,
    handleChordSearch
} from './ui.js';
import { generateChordPro, importFromChordPro } from './chordpro.js';
    // Flat/Sharp toggle
    const flatSharpToggle = document.getElementById('flat-sharp-toggle');
    const flatSharpLabel = document.getElementById('flat-sharp-label');
    flatSharpToggle.addEventListener('change', () => {
        window.preferFlats = flatSharpToggle.checked;
        flatSharpLabel.innerHTML = flatSharpToggle.checked ? '&#9837;' : '&#9839;';
        flatSharpLabel.style.color = flatSharpToggle.checked ? '#007bff' : '#222';
        updateChordDisplayForPreferFlats();
    });

    window.updateChordDisplayForPreferFlats = async function updateChordDisplayForPreferFlats() {
        // Update lyrics chords
        document.querySelectorAll('.lyrics-editor .chord').forEach(chordSpan => {
            // Always use ASCII value from data-lookup-name
            const asciiName = chordSpan.dataset.lookupName
                .replace(/♭/g, 'b').replace(/♯/g, '#')
                .replace(/&#9837;/g, 'b').replace(/&#9839;/g, '#');
            chordSpan.innerHTML = window.preferFlats
                ? displayChordName(convertToFlat(asciiName))
                : displayChordName(convertToSharp(asciiName));
        });

        // Update chords in lyric sections (.char[data-chord] in .lyrics-editor)
        document.querySelectorAll('.lyrics-editor .char[data-chord]').forEach(charSpan => {
            const asciiName = charSpan.dataset.chord
                .replace(/♭/g, 'b').replace(/♯/g, '#')
                .replace(/&#9837;/g, 'b').replace(/&#9839;/g, '#');
            // Store ASCII chord name in dataset for future transpositions
            const asciiResult = window.preferFlats
                ? convertToFlat(asciiName)
                : convertToSharp(asciiName);
            charSpan.dataset.chord = asciiResult;
            // Update lookupName for chord playback
            charSpan.dataset.lookupName = asciiResult;
            // Update chord display element if it exists
            const chordDisplayEl = charSpan.querySelector('.chord-display');
            if (chordDisplayEl) {
                chordDisplayEl.innerHTML = displayChordName(asciiResult);
            }
        });

        // Update chords in instrumental sections (.char[data-chord] in .instrumental-cell)
        document.querySelectorAll('.instrumental-cell .char[data-chord]').forEach(charSpan => {
            const asciiName = charSpan.dataset.chord
                .replace(/♭/g, 'b').replace(/♯/g, '#')
                .replace(/&#9837;/g, 'b').replace(/&#9839;/g, '#');
            // Store ASCII chord name in dataset for future transpositions
            const asciiResult = window.preferFlats
                ? convertToFlat(asciiName)
                : convertToSharp(asciiName);
            charSpan.dataset.chord = asciiResult;
            // Update lookupName for chord playback
            charSpan.dataset.lookupName = asciiResult;
            // Update chord display element if it exists
            const displayName = displayChordName(asciiResult);
            const chordDisplayEl = charSpan.querySelector('.chord-display');
            if (chordDisplayEl) {
                chordDisplayEl.innerHTML = displayName;
            } else {
                // Update visual display for instrumental sections without chord-display element
                charSpan.innerHTML = displayName;
            }
        });

        // Build chord set from window.currentChordsMap
        const chordNames = Array.from(window.currentChordsMap.keys());
        let apiChords = [];
        if (typeof window.initializeChordData === 'function') {
            apiChords = await window.initializeChordData(chordNames);
        }
        // Build toolbar map using display names
        const toolbarMap = new Map();
        function toAscii(name) { 
            return name.replace(/♭/g, 'b').replace(/♯/g, '#')
                      .replace(/&#9837;/g, 'b').replace(/&#9839;/g, '#'); 
        }
        for (const normalizedName of chordNames) {
            const normAscii = toAscii(normalizedName);
            // Use ASCII for SVG titles to avoid UTF-8 encoding issues, visual symbols handled by CSS
            const displayName = window.preferFlats ? convertToFlat(normAscii) : convertToSharp(normAscii);
            const chordData = apiChords.find(c => toAscii(c.chordName) === normAscii);
            if (chordData) {
                toolbarMap.set(chordData.chordName, displayName);
            }
        }
        if (typeof renderChordsInToolbar === 'function') {
            renderChordsInToolbar(toolbarMap);
        }
        // Update stored chord names in songSections
        updateStoredChordNamesForPreferFlats();
    }

    // Convert ASCII chord name to sharp
    // Convert ASCII chord name to flat
        // ...existing code...

    // Update all chord names in songSections to match preferFlat state
    // ...existing code...
    // Save button logic is handled by app.js

// --- Event Listener Setup ---
function setupEventListeners() {
    dom.transposeUpBtn.addEventListener('click', async () => {
        transposeAllChordsDOM(1, window.preferFlats);
        // Rebuild currentChordsMap from DOM
        window.currentChordsMap = new Map();
        document.querySelectorAll('.lyrics-editor .chord').forEach(chordSpan => {
            const lookupName = chordSpan.dataset.lookupName;
            if (lookupName) window.currentChordsMap.set(lookupName, lookupName);
        });
        // Rebuild toolbar using updated lyrics chords
        const chordNames = Array.from(window.currentChordsMap.keys());
        let apiChords = [];
        if (typeof window.initializeChordData === 'function') {
            apiChords = await window.initializeChordData(chordNames);
        }
        const toolbarMap = new Map();
        for (const chordName of chordNames) {
            // Use ASCII for SVG titles to avoid UTF-8 encoding issues, visual symbols handled by CSS
            const displayName = window.preferFlats ? convertToFlat(chordName) : convertToSharp(chordName);
            const chordData = apiChords.find(c => c.chordName === chordName);
            if (chordData) {
                toolbarMap.set(chordData.chordName, displayName);
            }
        }
        if (typeof renderChordsInToolbar === 'function') {
            renderChordsInToolbar(toolbarMap);
        }
    });
    dom.transposeDownBtn.addEventListener('click', async () => {
        transposeAllChordsDOM(-1, window.preferFlats);
        // Rebuild currentChordsMap from DOM
        window.currentChordsMap = new Map();
        document.querySelectorAll('.lyrics-editor .chord').forEach(chordSpan => {
            const lookupName = chordSpan.dataset.lookupName;
            if (lookupName) window.currentChordsMap.set(lookupName, lookupName);
        });
        // Rebuild toolbar using updated lyrics chords
        const chordNames = Array.from(window.currentChordsMap.keys());
        let apiChords = [];
        if (typeof window.initializeChordData === 'function') {
            apiChords = await window.initializeChordData(chordNames);
        }
        const toolbarMap = new Map();
        for (const chordName of chordNames) {
            // Use ASCII for SVG titles to avoid UTF-8 encoding issues, visual symbols handled by CSS
            const displayName = window.preferFlats ? convertToFlat(chordName) : convertToSharp(chordName);
            const chordData = apiChords.find(c => c.chordName === chordName);
            if (chordData) {
                toolbarMap.set(chordData.chordName, displayName);
            }
        }
        if (typeof renderChordsInToolbar === 'function') {
            renderChordsInToolbar(toolbarMap);
        }
    });
    // Side Panel Toggle
    dom.togglePanelBtn.addEventListener('click', () => {
        const isOpen = dom.sidePanel.classList.toggle('open');
        dom.mainContent.classList.toggle('panel-open');
        const icon = dom.togglePanelBtn.querySelector('i');
        if (isOpen) {
            icon.classList.replace('fa-angles-left', 'fa-angles-right');
            dom.togglePanelBtn.style.right = `calc(var(--panel-width) + 10px)`;
        } else {
            icon.classList.replace('fa-angles-right', 'fa-angles-left');
            dom.togglePanelBtn.style.right = '10px';
        }
    });

    // Audio Controls (only if not in print mode)
    if (document.body.dataset.print !== "true") {
        dom.instrumentSelect.addEventListener('change', (e) => loadInstrument(e.target.value));
        dom.tempoInput.addEventListener('input', e => {
            const bpm = parseInt(e.target.value, 10);
            if (bpm >= 40 && bpm <= 240) Tone.Transport.bpm.value = bpm;
        });
        dom.playStopBtn.addEventListener('click', startPlayback);
    }

    // Section Management
    dom.addSectionBtn.addEventListener('click', addSection);
    dom.sectionList.addEventListener('click', (e) => {
        const targetLi = e.target.closest('li');
        if (!targetLi) return;
        const sectionId = targetLi.dataset.id;
        if (e.target.classList.contains('delete-section-btn-panel')) {
            deleteSection(sectionId);
        } else {
            document.getElementById(sectionId)?.scrollIntoView();
        }
    });
    dom.sectionList.addEventListener('dblclick', handleSectionRename);

    // Section Drag and Drop
    dom.sectionList.addEventListener('dragstart', (e) => {
        const targetLi = e.target.closest('li');
        if (targetLi) {
            state.setDraggedSectionId(targetLi.dataset.id);
            e.dataTransfer.effectAllowed = 'move';
        }
    });
    dom.sectionList.addEventListener('dragover', (e) => {
        e.preventDefault();
        const targetLi = e.target.closest('li');
        if (targetLi && targetLi.dataset.id !== state.draggedSectionId) {
            dom.sectionList.querySelectorAll('.drag-over').forEach(el => el.classList.remove('drag-over'));
            targetLi.classList.add('drag-over');
        }
    });
    dom.sectionList.addEventListener('dragleave', (e) => {
         const targetLi = e.target.closest('li');
         if(targetLi) targetLi.classList.remove('drag-over');
    });
    dom.sectionList.addEventListener('drop', handleSectionDrop);
    document.addEventListener('dragend', () => { state.setDraggedChordSourceElement(null); });


    // Modal Controls
    dom.addNewChordBtn.addEventListener('click', () => openModal(dom.chordSearchModal));
    dom.chordSearchModal.querySelector('.modal-close-btn').addEventListener('click', () => closeModal(dom.chordSearchModal));
    dom.chordSearchModal.addEventListener('click', (e) => e.target === dom.chordSearchModal && closeModal(dom.chordSearchModal));
    dom.chordSearchBtn.addEventListener('click', handleChordSearch);

    dom.exportBtn.addEventListener('click', () => {
        dom.exportTextarea.value = generateChordPro();
        openModal(dom.exportModal);
    });
    dom.exportModal.querySelector('.modal-close-btn').addEventListener('click', () => closeModal(dom.exportModal));
    dom.exportModal.addEventListener('click', (e) => e.target === dom.exportModal && closeModal(dom.exportModal));

    dom.importBtn.addEventListener('click', () => openModal(dom.importModal));
    dom.importModal.querySelector('.modal-close-btn').addEventListener('click', () => closeModal(dom.importModal));
    dom.importModal.addEventListener('click', (e) => e.target === dom.importModal && closeModal(dom.importModal));
    dom.importConfirmBtn.addEventListener('click', () => {
        importFromChordPro(dom.importTextarea.value);
        closeModal(dom.importModal);
    });

    // Mode toggle buttons
    const deleteModeToggle = document.getElementById('delete-mode-toggle');
    const beatModeToggle = document.getElementById('beat-mode-toggle');
    
    console.log('Looking for toggle buttons...');
    console.log('Delete toggle:', deleteModeToggle);
    console.log('Beat toggle:', beatModeToggle);
    
    if (deleteModeToggle) {
        console.log('Delete mode toggle found, adding listener');
        deleteModeToggle.addEventListener('click', (e) => {
            e.preventDefault();
            console.log('Delete mode toggle clicked');
            alert('Delete mode clicked!'); // Simple test
            const isActive = deleteModeToggle.classList.toggle('active');
            console.log('Delete mode is now', isActive ? 'active' : 'inactive');
            if (isActive) {
                // Deactivate beat mode if it's active
                if (beatModeToggle && beatModeToggle.classList.contains('active')) {
                    beatModeToggle.classList.remove('active');
                    document.body.dataset.beatMode = 'false';
                    if (typeof hideInlineBeatBadges === 'function') hideInlineBeatBadges();
                }
                // Activate delete mode - show delete buttons inline
                document.body.dataset.deleteMode = 'true';
                if (typeof showInlineDeleteButtons === 'function') showInlineDeleteButtons();
            } else {
                // Deactivate delete mode - hide delete buttons
                document.body.dataset.deleteMode = 'false';
                if (typeof hideInlineDeleteButtons === 'function') hideInlineDeleteButtons();
            }
        });
    } else {
        console.log('Delete mode toggle not found');
    }
    
    if (beatModeToggle) {
        console.log('Beat mode toggle found, adding listener');
        beatModeToggle.addEventListener('click', (e) => {
            e.preventDefault();
            console.log('Beat mode toggle clicked');
            alert('Beat mode clicked!'); // Simple test
            const isActive = beatModeToggle.classList.toggle('active');
            if (isActive) {
                // Deactivate delete mode if it's active
                if (deleteModeToggle && deleteModeToggle.classList.contains('active')) {
                    deleteModeToggle.classList.remove('active');
                    document.body.dataset.deleteMode = 'false';
                    if (typeof hideInlineDeleteButtons === 'function') hideInlineDeleteButtons();
                }
                // Activate beat mode - show beat badges inline
                document.body.dataset.beatMode = 'true';
                if (typeof showInlineBeatBadges === 'function') showInlineBeatBadges();
            } else {
                // Deactivate beat mode - hide beat badges
                document.body.dataset.beatMode = 'false';
                if (typeof hideInlineBeatBadges === 'function') hideInlineBeatBadges();
            }
        });
    } else {
        console.log('Beat mode toggle not found');
    }

    // Clear Song button
    const clearSongBtn = document.getElementById('clear-song-btn');
    if (clearSongBtn) {
        clearSongBtn.addEventListener('click', () => {
            document.getElementById('song').innerHTML = '';
            document.getElementById('song-container').innerHTML = '';
            document.getElementById('song-title').value = '';
            document.getElementById('song-artist').value = '';
            document.getElementById('song-copyright').value = '';
            // Clear sidebar section list
            if (window.dom && window.dom.sectionList) {
                window.dom.sectionList.innerHTML = '';
            } else {
                const sectionList = document.getElementById('section-list');
                if (sectionList) sectionList.innerHTML = '';
            }
            if (typeof window.updateChordDisplayForPreferFlats === 'function') {
                window.currentChordsMap = new Map();
                window.updateChordDisplayForPreferFlats();
            }
        });
    }
}

// Helper functions for mode toggles
function showInlineDeleteButtons() {
    console.log('showInlineDeleteButtons called');
    const chordChars = document.querySelectorAll('.char[data-chord]');
    const toolbarChords = document.querySelectorAll('.chord-placeholder .chord-diagram');
    console.log('Found', chordChars.length, 'chord characters and', toolbarChords.length, 'toolbar chords');
    
    // First hide any existing hover buttons
    document.querySelectorAll('.chord-lyrics-delete-btn, .chord-beat-badge').forEach(btn => {
        btn.style.display = 'none';
    });
    
    // Add inline buttons to lyrics chords
    chordChars.forEach(charElement => {
        if (!charElement._inlineDeleteBtn) {
            const deleteBtn = document.createElement('span');
            deleteBtn.className = 'inline-delete-btn';
            deleteBtn.innerHTML = '<i class="fas fa-trash"></i>';
            deleteBtn.title = 'Delete chord';
            deleteBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                charElement.removeAttribute('data-chord');
                charElement.removeAttribute('data-beats');
                charElement.removeAttribute('data-lookup-name');
                
                // Check if this is an instrumental cell chord and clear the cell content
                const instrumentalCell = charElement.closest('.instrumental-cell');
                if (instrumentalCell) {
                    instrumentalCell.innerHTML = ''; // Clear the cell completely
                    instrumentalCell.setAttribute('data-chord', ''); // Reset the cell's chord attribute
                }
                
                // Enable save button when chord is deleted
                if (window.enableSave) window.enableSave();
                
                // Remove the inline button
                if (charElement._inlineDeleteBtn) {
                    charElement._inlineDeleteBtn.remove();
                    charElement._inlineDeleteBtn = null;
                }
                // Re-render to clean up
                if (typeof window.renderSong === 'function') {
                    window.renderSong();
                }
            });
            charElement.appendChild(deleteBtn);
            charElement._inlineDeleteBtn = deleteBtn;
        }
        charElement._inlineDeleteBtn.style.display = 'flex';
    });
    
    // Add inline buttons to toolbar chords  
    toolbarChords.forEach(chordElement => {
        const chordContainer = chordElement.closest('.chord-placeholder');
        if (chordContainer && !chordContainer._inlineDeleteBtn) {
            const deleteBtn = document.createElement('span');
            deleteBtn.className = 'inline-delete-btn';
            deleteBtn.innerHTML = '<i class="fas fa-trash"></i>';
            deleteBtn.title = 'Delete chord from toolbar';
            deleteBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                chordContainer.remove();
            });
            chordContainer.appendChild(deleteBtn);
            chordContainer._inlineDeleteBtn = deleteBtn;
        }
        if (chordContainer && chordContainer._inlineDeleteBtn) {
            chordContainer._inlineDeleteBtn.style.display = 'flex';
        }
    });
}

function hideInlineDeleteButtons() {
    document.querySelectorAll('.inline-delete-btn').forEach(btn => {
        btn.style.display = 'none';
    });
    // Also show hover buttons again
    document.querySelectorAll('.chord-lyrics-delete-btn, .chord-beat-badge').forEach(btn => {
        // Don't automatically show them, let hover handle it
        btn.style.display = 'none';
    });
}

function showInlineBeatBadges() {
    console.log('showInlineBeatBadges called');
    const chordChars = document.querySelectorAll('.char[data-chord]');
    const toolbarChords = document.querySelectorAll('.chord-placeholder .chord-diagram');
    console.log('Found', chordChars.length, 'chord characters and', toolbarChords.length, 'toolbar chords');
    
    // First hide any existing hover buttons
    document.querySelectorAll('.chord-lyrics-delete-btn, .chord-beat-badge').forEach(btn => {
        btn.style.display = 'none';
    });
    
    // Add inline badges to lyrics chords
    chordChars.forEach(charElement => {
        const beats = charElement.dataset.beats ? parseInt(charElement.dataset.beats, 10) : 4;
        if (!charElement._inlineBeatBadge) {
            const beatBadge = document.createElement('span');
            beatBadge.className = 'inline-beat-badge';
            beatBadge.textContent = beats;
            beatBadge.title = 'Left-click: +1 beat, Right-click: -1 beat';
            beatBadge.addEventListener('click', (e) => {
                e.stopPropagation();
                let currentBeats = parseInt(charElement.dataset.beats || '4', 10);
                currentBeats = currentBeats >= 8 ? 1 : currentBeats + 1;
                charElement.setAttribute('data-beats', currentBeats.toString());
                beatBadge.textContent = currentBeats;
                // Enable save button when beats change
                if (window.enableSave) window.enableSave();
            });
            beatBadge.addEventListener('contextmenu', (e) => {
                e.preventDefault();
                e.stopPropagation();
                let currentBeats = parseInt(charElement.dataset.beats || '4', 10);
                currentBeats = currentBeats <= 1 ? 8 : currentBeats - 1;
                charElement.setAttribute('data-beats', currentBeats.toString());
                beatBadge.textContent = currentBeats;
                // Enable save button when beats change
                if (window.enableSave) window.enableSave();
            });
            charElement.appendChild(beatBadge);
            charElement._inlineBeatBadge = beatBadge;
        }
        charElement._inlineBeatBadge.style.display = 'flex';
        charElement._inlineBeatBadge.textContent = beats;
    });
    
    // Add inline badges to toolbar chords
    toolbarChords.forEach(chordElement => {
        const chordContainer = chordElement.closest('.chord-placeholder');
        if (chordContainer) {
            const beats = chordElement.dataset.beats ? parseInt(chordElement.dataset.beats, 10) : 4;
            if (!chordContainer._inlineBeatBadge) {
                const beatBadge = document.createElement('span');
                beatBadge.className = 'inline-beat-badge';
                beatBadge.textContent = beats;
                beatBadge.title = 'Left-click: +1 beat, Right-click: -1 beat';
                beatBadge.addEventListener('click', (e) => {
                    e.stopPropagation();
                    let currentBeats = parseInt(chordElement.dataset.beats || '4', 10);
                    currentBeats = currentBeats >= 8 ? 1 : currentBeats + 1;
                    chordElement.setAttribute('data-beats', currentBeats.toString());
                    beatBadge.textContent = currentBeats;
                    // Enable save button when beats change
                    if (window.enableSave) window.enableSave();
                });
                beatBadge.addEventListener('contextmenu', (e) => {
                    e.preventDefault();
                    e.stopPropagation();
                    let currentBeats = parseInt(chordElement.dataset.beats || '4', 10);
                    currentBeats = currentBeats <= 1 ? 8 : currentBeats - 1;
                    chordElement.setAttribute('data-beats', currentBeats.toString());
                    beatBadge.textContent = currentBeats;
                    // Enable save button when beats change
                    if (window.enableSave) window.enableSave();
                });
                chordContainer.appendChild(beatBadge);
                chordContainer._inlineBeatBadge = beatBadge;
            }
            chordContainer._inlineBeatBadge.style.display = 'flex';
            chordContainer._inlineBeatBadge.textContent = beats;
        }
    });
}

function hideInlineBeatBadges() {
    document.querySelectorAll('.inline-beat-badge').forEach(badge => {
        badge.style.display = 'none';
    });
    // Don't automatically show hover buttons, let hover handle it
    document.querySelectorAll('.chord-lyrics-delete-btn, .chord-beat-badge').forEach(btn => {
        btn.style.display = 'none';
    });
}

// Make functions globally accessible
window.showInlineDeleteButtons = showInlineDeleteButtons;
window.hideInlineDeleteButtons = hideInlineDeleteButtons;
window.showInlineBeatBadges = showInlineBeatBadges;
window.hideInlineBeatBadges = hideInlineBeatBadges;

// --- Start the Application ---
function init() {
    console.log('=== APPLICATION INIT STARTED ===');
    // Show loading spinner
    const loadingOverlay = document.getElementById('loading-overlay');
    const appContent = document.getElementById('app-content');
    if (loadingOverlay) loadingOverlay.style.display = 'flex';
    if (appContent) appContent.style.display = 'none';

    // Only initialize audio if not in print mode
    if (document.body.dataset.print !== "true") {
        initAudio();
    }
    
    initializeChordData().then(() => {
        renderSong();
        // Only load instrument if not in print mode
        if (document.body.dataset.print !== "true") {
            loadInstrument(dom.instrumentSelect.value);
        }
        console.log('=== CALLING setupEventListeners ===');
        setupEventListeners();
        console.log('=== setupEventListeners COMPLETED ===');
        // Import from hidden textarea after empty song is rendered
        const chordproText = document.getElementById('chordproText');
        if (chordproText && chordproText.value.trim()) {
            importFromChordPro(chordproText.value);
            // Wait for import to finish before hiding spinner
            setTimeout(() => {
                if (loadingOverlay) loadingOverlay.style.display = 'none';
                if (appContent) appContent.style.display = '';
            }, 400); // allow DOM to update
        } else {
            if (loadingOverlay) loadingOverlay.style.display = 'none';
            if (appContent) appContent.style.display = '';
        }
    });
}

console.log('=== MAIN.JS FILE LOADED ===');
document.addEventListener('DOMContentLoaded', () => {
    console.log('=== DOM CONTENT LOADED, CALLING INIT ===');
    init();
});

// Also add a simple test that runs immediately
console.log('Testing toggle button access...');
setTimeout(() => {
    const deleteBtn = document.getElementById('delete-mode-toggle');
    const beatBtn = document.getElementById('beat-mode-toggle');
    console.log('Delete button:', deleteBtn);
    console.log('Beat button:', beatBtn);
    
    if (deleteBtn) {
        deleteBtn.style.border = '3px solid red';
        console.log('Added red border to delete button');
    }
    if (beatBtn) {
        beatBtn.style.border = '3px solid blue';  
        console.log('Added blue border to beat button');
    }
}, 1000);