import { formatCurrency } from './utils.js'; document.addEventListener('DOMContentLoaded', function() { const booksContainer = document.getElementById('books-container'); const searchInput = document.getElementById('searchInput'); const sortSelect = document.getElementById('sortSelect'); // Załaduj książki przy starcie loadBooks(); // Dodaj event listeners if (searchInput) { searchInput.addEventListener('input', debounce(loadBooks, 300)); } if (sortSelect) { sortSelect.addEventListener('change', loadBooks); } }); async function loadBooks() { const booksContainer = document.getElementById('books-container'); const searchInput = document.getElementById('searchInput'); const sortSelect = document.getElementById('sortSelect'); if (!booksContainer) return; booksContainer.innerHTML = `
Ładowanie...
`; try { const searchTerm = searchInput ? searchInput.value : ''; const sortBy = sortSelect ? sortSelect.value : 'default'; const response = await fetch(`/api/ksiazki?search=${encodeURIComponent(searchTerm)}&sort=${sortBy}`, { credentials: 'include' }); if (!response.ok) { throw new Error('Błąd ładowania książek'); } const books = await response.json(); displayBooks(books); } catch (error) { console.error('Błąd:', error); booksContainer.innerHTML = `
Wystąpił błąd podczas ładowania książek
`; } } function displayBooks(books) { const booksContainer = document.getElementById('books-container'); if (!booksContainer) return; if (books.length === 0) { booksContainer.innerHTML = `

Brak książek spełniających kryteria wyszukiwania

`; return; } booksContainer.innerHTML = ''; books.forEach(book => { const price = formatCurrency(book.cena); const bookCard = `
${book.tytul}
${book.tytul}

${book.autor}

${price}

`; booksContainer.innerHTML += bookCard; }); // Dodajemy nasłuchiwanie na przyciskach dodania do koszyka document.querySelectorAll('.add-to-cart-btn').forEach(button => { button.addEventListener('click', function() { const bookId = this.dataset.bookId; addToCart(bookId); }); }); } async function addToCart(bookId) { const response = await fetch('/api/check-auth'); const data = await response.json(); if (!data.authenticated) { window.location.href = '/login.html'; return; } try { const response = await fetch('/api/add-to-cart', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ book_id: parseInt(bookId), quantity: 1 }), credentials: 'include' }); if (response.ok) { alert('Książka została dodana do koszyka!'); } else { const errorData = await response.json(); alert(`Błąd: ${errorData.message || 'Nie udało się dodać do koszyka'}`); } } catch (error) { console.error('Błąd:', error); alert('Wystąpił błąd podczas dodawania do koszyka'); } } function debounce(func, wait) { let timeout; return function(...args) { clearTimeout(timeout); timeout = setTimeout(() => func.apply(this, args), wait); }; }