document.addEventListener('DOMContentLoaded', () => {
    const input = document.getElementById('search-input');
    const results = document.getElementById('search-results');
    let indexData = null;

    if (!input) return;

    // Index laden
    fetch(searchSettings.indexUrl)
        .then(res => res.json())
        .then(data => {
            indexData = data;
            console.log("Suchindex geladen.");
        })
        .catch(err => console.error("Index konnte nicht geladen werden:", err));

    input.addEventListener('input', () => {
        const query = input.value.toLowerCase().trim();
        results.innerHTML = '';

        if (query.length < 3 || !indexData) {
            results.style.display = 'none';
            return;
        }

        let foundLinks = new Set();
        // Suche in den Keys (Wörtern) des Index
        Object.keys(indexData).forEach(word => {
            if (word.startsWith(query)) { // Findet Wörter, die so beginnen
                indexData[word].forEach(link => foundLinks.add(link));
            }
        });

        if (foundLinks.size > 0) {
            results.style.display = 'block';
            foundLinks.forEach(link => {
                const div = document.createElement('div');
                div.className = 'result-item';
                // URL verschönern (letztes Segment nehmen)
                const parts = link.split('/').filter(Boolean);
                const title = parts.length > 0 ? parts.pop().replace('.html', '').replace(/-/g, ' ') : link;
                div.innerHTML = `<li><a href="${link}">${title}</a></li>`;
                results.appendChild(div);
            });
        } else {
            results.style.display = 'block';
            results.innerHTML = '<div class="result-item">Nichts gefunden.</div>';
        }
    });

    // Schließen bei Klick außerhalb
    document.addEventListener('click', (e) => {
        if (!input.contains(e.target) && !results.contains(e.target)) {
            results.style.display = 'none';
        }
    });
});
