# ChordPro Song Editor - AI Coding Instructions

## Architecture Overview
This is a JavaScript-based ChordPro song editor that renders songs with interactive chord placement, audio playback, and export capabilities. The application consists of two main modes:
- **Editor Mode**: Full-featured song editing with drag-and-drop chords, sections, and playback (`index.html`)
- **Player Mode**: Simplified song player with auto-scrolling and chord diagrams (`player.html`)

## Core Module Structure

### State Management (`js/state.js`)
- **Centralized state**: `songSections[]`, `draggedSectionId`, `draggedChordSourceElement`, `chordApiData[]`
- **Pattern**: Export variables + setter functions (not objects) for ES6 module compatibility
- **Critical**: All state changes must use setter functions to maintain consistency

### Module Dependencies & Data Flow
```
app.js (entry point) → imports from:
├── editor.js (chord operations, transposition)
├── chordpro.js (import/export ChordPro format)
├── audio.js (Tone.js integration, chord playback)
├── ui.js (modals, section management)
├── chords.js (chord data fetching, toolbar rendering)
├── dom.js (element references)
└── state.js (shared state)
```

### ChordPro Format Handling (`js/chordpro.js`)
- **Dual format support**: Import/export with `[Chord;Beats]` syntax for timing annotations
- **DOM-driven export**: Traverses actual DOM elements to reconstruct ChordPro, not stored data structures
- **Chord normalization**: ASCII-only exports (`♭` → `b`, `♯` → `#`) for cross-platform compatibility
- **Instrumental sections**: Chord-only lines become interactive tables with drag-drop chord placement

### Audio Architecture (`js/audio.js`)
- **Tone.js integration**: Requires user gesture to start audio context
- **Chord voicings**: Maps chord names to guitar fret positions → MIDI notes
- **Critical pattern**: Always check `isInstrumentReady()` before audio operations
- **Lookup system**: Uses ASCII chord names for API calls, Unicode for display

## Key Development Patterns

### Chord Data Dual-System
- **Storage**: `data-lookup-name` (ASCII, for API/playback) vs `data-chord` (display, Unicode symbols)
- **Display**: `displayChordName()` converts ASCII to Unicode symbols (`C#` → `C♯`)
- **Transposition**: Always work with ASCII internally, convert for display

### DOM Event Patterns
```javascript
// Standard pattern for mode toggles
document.body.dataset.deleteMode = 'true'; // CSS-driven state
charElement._deleteIcon = deleteIcon; // Store references on DOM elements
attachDragHandlerToChord(chordElement); // Drag/drop setup
```

### Window Global Pattern
Functions exposed on `window` for cross-module communication and external integration:
- `window.generateChordPro` - Export functionality
- `window.onChordProSave` - Save callback (external server integration)
- `window.currentChordsMap` - Chord state management

## Critical Integration Points

### External Dependencies (CDN)
- **Tone.js**: Audio synthesis and timing
- **SVGuitar**: Chord diagram rendering
- **FontAwesome**: UI icons
- **ToneJS-Instruments**: Sampled instruments

### Server Integration (`my-chords.js`)
- **Chord search**: `searchChordByName()` hits `/app/api/chords/search`
- **AI co-writer**: `sendAIRequest()` for lyric/chord suggestions
- **Save endpoint**: `onChordProSave()` posts to `/app/api/songs/save/{uuid}`

## Development Workflows

### Adding New Chord Operations
1. Update `editor.js` for core chord logic (ASCII-based)
2. Extend `chordpro.js` export/import if format changes needed
3. Update `audio.js` if playback integration required
4. Modify `ui.js` for any UI interactions

### Debugging Audio Issues
- Check browser console for "Audio context started" message
- Verify `currentInstrument` is loaded via `isInstrumentReady()`
- Ensure chord names are ASCII for `getNotesFromVoicing()`
- Use `dom.playOnHoverCheckbox.checked` to test chord preview

### Testing ChordPro Compatibility
- Use `test-chordpro.html` for isolated format testing
- Test both `[Chord]lyrics` and `[Chord;Beats]` patterns
- Verify export → re-import preserves all data

## Performance Considerations
- **Lazy audio loading**: Only initialize audio components when not in print mode
- **DOM caching**: Store element references in `dom.js`, don't re-query
- **Drag operation batching**: Use `_mouseenterListener` pattern to prevent event stacking

## Common Pitfalls
- **Mixed Unicode/ASCII**: Always normalize chord names before API calls
- **Missing audio context**: User interaction required before any Tone.js operations
- **State synchronization**: Use state setters, don't modify exported variables directly
- **Print mode**: Many features disabled when `document.body.dataset.print === "true"`

## Testing Entry Points
- **Manual testing**: Load `index.html` with sample data in `#chordproText` textarea
- **Player testing**: Use `player.html?song=base64encodedChordPro` URL parameter
- **API testing**: Use `test-ai-chat.html` for AI integration features