(() => {
    // Sprawdź czy jesteśmy na stronie głównej
    const booksContainer = document.getElementById('books-container');
    const searchInput = document.getElementById('searchInput');
    const sortSelect = document.getElementById('sortSelect');
    
    if (!booksContainer || !searchInput || !sortSelect) return;
    // Funkcje specyficzne dla strony głównej
    const createBookCard = (book) => `
        <div class="col">
            <div class="book-card h-100">
                <div class="cover-container">
                    <img src="${book.obraz_url}" class="book-cover" alt="${book.tytul}">
                </div>
                <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>
    `;

    const renderBooks = (books) => {
        booksContainer.innerHTML = books.length > 0 
            ? books.map(book => createBookCard(book)).join('')
            : `<div class="col-12 text-center"><p class="text-muted">Brak wyników wyszukiwania</p></div>`;
    };

    const loadBooks = async () => {
        const searchTerm = searchInput.value;
        const sortBy = sortSelect.value;
        
        try {
            const response = await fetch(`/api/ksiazki?search=${encodeURIComponent(searchTerm)}&sort=${sortBy}`);
            const books = await response.json();
            renderBooks(books);
        } catch (error) {
            console.error('Błąd ładowania książek:', error);
        }
    };

    // Event listeners tylko dla strony głównej
    searchInput.addEventListener('input', loadBooks);
    sortSelect.addEventListener('change', loadBooks);

    // Inicjalizacja
    document.addEventListener('DOMContentLoaded', loadBooks);
})();

async function updateAuthUI() {
    const token = localStorage.getItem('token');
    const authContainers = document.querySelectorAll('.auth-links');

    try {
        const response = await fetch('/api/check-auth', {
            headers: token ? { 'Authorization': `Bearer ${token}` } : {}
        });
        
        const data = await response.json();
        
        authContainers.forEach(container => {
            const anonymous = container.querySelector('.anonymous-links');
            const user = container.querySelector('.user-links');
            const cart = container.querySelector('a[href="/cart.html"]');

            if (data.authenticated) {
                anonymous?.classList.remove('visible');
                user?.classList.add('visible');
                cart?.classList.add('visible');
            } else {
                anonymous?.classList.add('visible');
                user?.classList.remove('visible');
                cart?.classList.remove('visible');
                localStorage.removeItem('token');
            }
        });
    } catch (error) {
        console.error('Błąd autentykacji:', error);
    }
}

// Obsługa wylogowania
function setupLogout() {
    document.getElementById('logoutLink')?.addEventListener('click', async (e) => {
        e.preventDefault();
        localStorage.removeItem('token');
        window.location.href = '/';
    });
}

// Inicjalizacja na każdej stronie
document.addEventListener('DOMContentLoaded', () => {
    updateAuthUI();
    setupLogout();
});

document.addEventListener('DOMContentLoaded', () => {
    updateNavVisibility();
    checkAuthStatus();
});

function updateNavVisibility() {
    const token = localStorage.getItem('token');
    document.querySelectorAll('.anonymous-links, .user-links').forEach(el => {
        el.style.display = 'none';
    });

    if (token) {
        document.querySelector('.user-links').style.display = 'flex';
    } else {
        document.querySelector('.anonymous-links').style.display = 'flex';
    }
}

async function checkAuthStatus() {
    try {
        const response = await fetch('/api/check-auth');
        const data = await response.json();

        if (data.authenticated) {
            localStorage.setItem('token', data.token);
            localStorage.setItem('imie', data.user.imie);
            updateNavVisibility();
        }
    } catch (error) {
        console.error('Błąd sprawdzania autentykacji:', error);
    }
}

document.getElementById('logoutLink')?.addEventListener('click', (e) => {
    e.preventDefault();
    localStorage.removeItem('token');
    localStorage.removeItem('imie');
    updateNavVisibility();
    window.location.href = '/';
});

document.getElementById('loginForm')?.addEventListener('submit', async (e) => {
    e.preventDefault();
    
    try {
        const response = await fetch('/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                email: document.getElementById('loginEmail').value,
                haslo: document.getElementById('loginPassword').value
            })
        });

        if (response.ok) {
            const { token } = await response.json();
            localStorage.setItem('token', token);
            window.location.href = '/';
        } else {
            alert('Błąd logowania!');
        }
    } catch (error) {
        console.error('Błąd:', error);
    }
});

document.getElementById('registerForm')?.addEventListener('submit', async (e) => {
    e.preventDefault();
    const name = document.getElementById('registerName').value;
    const email = document.getElementById('registerEmail').value;
    const password = document.getElementById('registerPassword').value;
    const confirmPassword = document.getElementById('registerConfirmPassword').value;

    if (password !== confirmPassword) {
        alert('Hasła nie są identyczne');
        return;
    }

    try {
        const response = await fetch('/rejestracja', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ imie: name, email, haslo: password, confirmPassword }),
        });

        if (response.ok) {
            alert('Rejestracja udana');
            window.location.href = '/login.html';
        } else {
            const data = await response.text();
            alert(data || 'Rejestracja nieudana');
        }
    } catch (error) {
        console.error('Błąd rejestracji:', error);
        alert('Wystąpił błąd podczas rejestracji');
    }
});

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}`);
        const books = await response.json();
        renderBooks(books);
    } catch (error) {
        console.error('Błąd ładowania książek:', error);
        showError('Wystąpił błąd podczas ładowania książek');
    }
}

function renderBooks(books) {
    const container = document.getElementById('books-container');
    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="https://athenaeum.sykorax.eu/book.html?id=${book.id}">
			<div class="cover-container">
			    <img src="${book.obraz_url}" class="book-cover" alt="${book.tytul}">
			</div>
		    </a>
		    </div>
		</div>
    `).join('');

    // Dodaj obsługę przycisków "Dodaj do koszyka"
    document.querySelectorAll('.add-to-cart').forEach(button => {
        button.addEventListener('click', async (e) => {
            e.preventDefault();
            const token = localStorage.getItem('token');
            if (!token) {
                alert('Musisz być zalogowany, aby dodać książkę do koszyka');
                window.location.href = '/login.html';
                return;
            }

            const bookId = e.target.getAttribute('data-book-id');

            try {
                const response = await fetch('/api/add-to-cart', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({
                        book_id: parseInt(bookId),
                        quantity: 1
                    })
                });

                if (response.ok) {
                    alert('Dodano do koszyka!');
                } else {
                    const error = await response.json();
                    alert(error.error || 'Wystąpił błąd');
                }
            } catch (error) {
                console.error('Błąd:', error);
                alert('Wystąpił błąd podczas dodawania do koszyka');
            }
        });
    });
}

function showError(message) {
    const container = document.getElementById('books-container');
    if (!container) return;

    container.innerHTML = `
        <div class="col-12 text-center py-5">
            <div class="alert alert-danger">
                ${message}<br>
                <button class="btn btn-gothic mt-3" onclick="location.reload()">
                    Spróbuj ponownie
                </button>
            </div>
        </div>
    `;
}

// Inicjalizacja przy pierwszym załadowaniu
document.addEventListener('DOMContentLoaded', () => {
    if (document.getElementById('books-container')) {
        loadBooks();
    }

    // Nasłuchiwanie wyszukiwania
    document.getElementById('searchInput')?.addEventListener('input', (e) => {
        loadBooks(e.target.value, document.getElementById('sortSelect')?.value || 'default');
    });

    // Nasłuchiwanie zmiany sortowania
    document.getElementById('sortSelect')?.addEventListener('change', (e) => {
        loadBooks(document.getElementById('searchInput')?.value || '', e.target.value);
    });
});

function getAuthHeaders() {
    const token = localStorage.getItem('token');
    return {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : ''
    };
}


localStorage.setItem('token', response.token);
