import { setChordApiData, chordApiData } from './state.js';
import { displayChordName } from './editor.js';
import { addNewChordBtn } from './dom.js';
import { createChordElement } from './ui.js';

// --- Chord Data Handling ---

// Fallback chords removed. All chord data must come from the API.

export async function initializeChordData(chordNames = []) {
    // If chordNames is provided, fetch only those chords from the API
    if (chordNames.length > 0 && typeof window.searchChordByName === 'function') {
        const allChords = [];
        for (const name of chordNames) {
            try {
                const results = await window.searchChordByName(name);
                if (Array.isArray(results) && results.length > 0) {
                    // Use the first result for now, or merge if needed
                    allChords.push(results[0]);
                }
            } catch (error) {
                console.error(`Chord API search failed for ${name}:`, error);
            }
        }
        setChordApiData(allChords);
        return allChords;
    }
    // If no chordNames, just clear the cache
    setChordApiData([]);
    return [];
}

// CHANGED: The function now accepts a Map of (normalizedName -> originalName).
export function renderChordsInToolbar(chordsMap = new Map()) {
    // Clear any existing chords except the 'add' button
    let toolbar = null;
    if (addNewChordBtn && addNewChordBtn.parentElement) {
        toolbar = addNewChordBtn.parentElement.parentElement;
    } else {
        toolbar = document.getElementById('chord-toolbar');
    }
    if (!toolbar) return Promise.resolve();
    toolbar.querySelectorAll('.chord-wrapper').forEach(wrapper => wrapper.remove());

    function toAscii(name) {
        return name.replace(/♭/g, 'b').replace(/♯/g, '#');
    }
    for (const [normalizedName, displayName] of chordsMap.entries()) {
        const normAscii = toAscii(normalizedName);
        const chordData = chordApiData.find(chord => toAscii(chord.chordName) === normAscii);
        if (chordData) {
            const newChord = createChordElement(chordData, displayName);
            if (addNewChordBtn && addNewChordBtn.parentElement) {
                addNewChordBtn.parentElement.before(newChord);
            } else {
                toolbar.appendChild(newChord);
            }
        }
    }
    // Wait for browser to paint SVGs before resolving
    return new Promise(resolve => {
        requestAnimationFrame(() => {
            resolve();
        });
    });
}
