// Generate plain text lyrics by section, omitting chords
window.getPlainLyricsText = function() {
    const songContainer = document.getElementById('song-container');
    if (!songContainer) return '';
    let output = '';
    songContainer.querySelectorAll('.song-section').forEach(sectionDiv => {
        // Get section name
        let sectionName = '';
        if (sectionDiv.dataset.type === 'Page Break') return;
        if (sectionDiv.dataset.type === 'Instrumental') return;
        if (sectionDiv.dataset.type === 'Repeat Chorus') {
            sectionName = 'Repeat Chorus';
        } else {
            sectionName = sectionDiv.querySelector('.section-header span')?.textContent?.trim() || '';
        }
        if (sectionName) output += sectionName + '\n\n';
        // Get lyrics lines
        const editorDiv = sectionDiv.querySelector('.lyrics-editor');
        if (editorDiv) {
            editorDiv.querySelectorAll('div').forEach(lineDiv => {
                let lineText = '';
                lineDiv.childNodes.forEach(node => {
                    if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains('char')) {
                        lineText += node.textContent;
                    } else if (node.nodeType === Node.TEXT_NODE) {
                        lineText += node.textContent;
                    }
                });
                if (lineText.trim()) output += lineText.trim() + '\n';
            });
            output += '\n';
        }
    });
    return output.trim();
};
// Dummy AI co-writer request handler
window.sendAIRequest = function(userMsg, callback) {
    // Get song UUID from body attribute
    const uuid = document.body.getAttribute('data-uuid');
    const lyrics = window.getPlainLyricsText ? window.getPlainLyricsText() : '';

    // Track last sent lyrics in DOM
    if (!window._lastAIState) {
        window._lastAIState = { lyrics: '' };
    }
    let sendLyrics = '';
    if (window._lastAIState.lyrics !== lyrics) {
        sendLyrics = lyrics;
        window._lastAIState.lyrics = lyrics;
    }
    // Always send parameters, but empty if unchanged
    const payload = {
        requestText: userMsg,
        lyrics: sendLyrics
    };
    // If no uuid, fail gracefully
    if (!uuid) {
        callback('No song UUID found.');
        return;
    }
    fetch(`/app/api/songs/cowrite/${uuid}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams(payload)
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            callback(data.message || 'AI response received.');
        } else {
            showSaveAlert(false, data.message || 'Unknown error.');
            // Still call callback with error message so UI can reset
            callback('Sorry, I encountered an error processing your request. Please try again.');
        }
    })
    .catch(err => {
        showSaveAlert(false, 'AI request failed: ' + err.message);
        // Still call callback with error message so UI can reset
        callback('Sorry, I\'m having trouble connecting right now. Please check your connection and try again.');
    });
};
export async function searchChordByName(chordName) {
  const url = `https://api.chordpro.io/app/api/chords/search/${encodeURIComponent(chordName)}`;
  const response = await fetch(url);
  if (!response.ok) throw new Error('API request failed');
  const results = await response.json();
  // Map to your internal format if needed, or just return the array
  return results;
}

window.onChordProSave = async function(chordProText) {
    const uuid = document.body.getAttribute('data-uuid');
    if (!uuid) {
        showSaveAlert(false, 'No song UUID found.');
        throw new Error('No song UUID found.');
    }

    try {
        const response = await fetch(`/app/api/songs/save/${uuid}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({ chordProText, uuid }),
        });
        const result = await response.json();
        
        if (result.success) {
            showSaveAlert(true, result.message || 'Saved successfully.');
        } else {
            showSaveAlert(false, result.message || 'Save failed.');
            throw new Error(result.message || 'Save failed.');
        }
    } catch (err) {
        showSaveAlert(false, 'Network error: ' + err.message);
        throw err; // Re-throw to allow save button to handle the error
    }
};

function showSaveAlert(success, message) {
    let alertDiv = document.getElementById('save-alert');
    if (!alertDiv) {
        alertDiv = document.createElement('div');
        alertDiv.id = 'save-alert';
        alertDiv.style.position = 'fixed';
        alertDiv.style.top = '0';
        alertDiv.style.left = '0';
        alertDiv.style.width = '100%';
        alertDiv.style.zIndex = '9999';
        alertDiv.style.fontSize = '1.2em';
        alertDiv.style.fontWeight = 'bold';
        alertDiv.style.textAlign = 'center';
        alertDiv.style.padding = '16px 0';
        alertDiv.style.transition = 'opacity 0.3s';
        document.body.prepend(alertDiv);
    }
    alertDiv.textContent = message;
    alertDiv.style.background = success ? '#28a745' : '#dc3545';
    alertDiv.style.color = '#fff';
    alertDiv.style.opacity = '1';
    setTimeout(() => {
        alertDiv.style.opacity = '0';
    }, 3500);
}

// Expose to window for global access
window.searchChordByName = searchChordByName;