document.getElementById('searchForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const searchTerm = document.getElementById('searchInput').value;
    await loadResults(searchTerm);
});

async function loadResults(searchTerm) {
    const searchTerm = document.getElementById('searchInput').value;
    const sortBy = document.getElementById('sortSelect').value;

    try {
        const response = await fetch(`/api/ksiazki?search=${encodeURIComponent(searchTerm)}&sort=${sortBy}`);
        const books = await response.json();
        renderResults(books);
    } catch (error) {
        console.error('Błąd wyszukiwania:', error);
    }
}

['input', 'change'].forEach(event => {
    document.getElementById('searchInput').addEventListener(event, loadBooks);
    document.getElementById('sortSelect').addEventListener(event, loadBooks);
});

function renderResults(books) {
    const container = document.getElementById('search-results');
    container.innerHTML = books.map(book => `
        <div class="col-md-4">
            <div class="card dark-card h-100">
                <img src="${book.obraz_url}" class="card-img-top" alt="${book.tytul}">
                <div class="card-body">
                    <h5 class="card-title lobster-font">${book.tytul}</h5>
                    <p class="card-text inter-font">${book.autor}</p>
                    <a href="/book.html?id=${book.id}" class="btn btn-gothic">Szczegóły</a>
                </div>
            </div>
        </div>
    `).join('');
}
