// static/js/books.js

import { getAuthHeaders, handleApiError } from './utils.js';

export async function loadBooks(searchTerm = '', sortBy = 'default') {
    try {
        const response = await fetch(`/api/ksiazki?search=${encodeURIComponent(searchTerm)}&sort=${sortBy}`);
        if (!response.ok) throw new Error(`Błąd HTTP: ${response.status}`);
        return await response.json();
    } catch (error) {
        handleApiError(error, 'Wystąpił błąd podczas ładowania książek');
        return [];
    }
}

export function renderBooks(books, containerId) {
    const container = document.getElementById(containerId);
    if (!container) return;

    if (books.length === 0) {
        container.innerHTML = '<div class="col-12 text-center py-5"><h3>Nie znaleziono książek</h3></div>';
        return;
    }

    container.innerHTML = books.map(book => `
        <div class="col">
            <div class="book-card h-100">
                <a href="/book.html?id=${book.id}">
                    <div class="cover-container">
                        <img src="${book.obraz_url}" class="book-cover" alt="${book.tytul}">
                    </div>
                </a>
                <div class="book-body p-3">
                    <h5 class="book-title">${book.tytul}</h5>
                    <div class="mt-auto">
                        <p class="book-author mb-1">${book.autor}</p>
                        <p class="book-price mb-0">${book.cena} PLN</p>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

// Inicjalizacja na stronie głównej
document.addEventListener('DOMContentLoaded', async () => {
    if (!document.getElementById('books-container')) return;
    
    const books = await loadBooks();
    renderBooks(books, 'books-container');

    // Obsługa wyszukiwania i sortowania
    const searchInput = document.getElementById('searchInput');
    const sortSelect = document.getElementById('sortSelect');
    
    const reloadBooks = async () => {
        const books = await loadBooks(
            searchInput?.value || '',
            sortSelect?.value || 'default'
        );
        renderBooks(books, 'books-container');
    };

    searchInput?.addEventListener('input', reloadBooks);
    sortSelect?.addEventListener('change', reloadBooks);
});
