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

export function handleApiError(error, fallbackMsg = 'Wystąpił błąd') {
    console.error('Error:', error);
    alert(error.message || fallbackMsg);
}

async function updateAuthUI() {
    try {
        const response = await fetch('/api/check-auth', {
            credentials: 'include'
        });
        
        if (!response.ok) return;
        
        const data = await response.json();
        const authContainers = document.querySelectorAll('.auth-links');
        
        authContainers.forEach(container => {
            const anonymousLinks = container.querySelector('.anonymous-links');
            const userLinks = container.querySelector('.user-links');
            
            if (data.authenticated) {
                if (anonymousLinks) anonymousLinks.style.display = 'none';
                if (userLinks) userLinks.style.display = 'flex';
            } else {
                if (anonymousLinks) anonymousLinks.style.display = 'flex';
                if (userLinks) userLinks.style.display = 'none';
            }
        });
    } catch (error) {
        console.error('Błąd aktualizacji UI:', error);
    }
}

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

document.addEventListener('DOMContentLoaded', updateAuthUI);
