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 = `
        <div class="col-12 text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Ładowanie...</span>
            </div>
        </div>
    `;
    
    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 = `
            <div class="col-12 text-center py-5">
                <div class="alert alert-danger">Wystąpił błąd podczas ładowania książek</div>
            </div>
        `;
    }
}

function displayBooks(books) {
    const booksContainer = document.getElementById('books-container');
    
    if (!booksContainer) return;
    
    if (books.length === 0) {
        booksContainer.innerHTML = `
            <div class="col-12 text-center py-5">
                <p>Brak książek spełniających kryteria wyszukiwania</p>
            </div>
        `;
        return;
    }
    
    booksContainer.innerHTML = '';
    
    books.forEach(book => {
        const price = formatCurrency(book.cena);

        const bookCard = `
            <div class="book-card">
                <a href="/book.html?id=${book.id}" class="book-cover-link">
                    <div class="book-cover-container">
                        <img src="${book.obraz_url}" class="book-cover" alt="${book.tytul}">
                        <div class="book-overlay">
                            <h5>${book.tytul}</h5>
                            <p>${book.autor}</p>
                            <p class="price">${price}</p>
                        </div>
                    </div>
                </a>
                <button class="btn btn-sm btn-outline-primary w-100 mt-2 add-to-cart-btn" data-book-id="${book.id}">
                    <i class="bi bi-cart-plus me-1"></i> Dodaj do koszyka
                </button>
            </div>
        `;
        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);
    };
}
