// ==================== Utility Functions ====================

function showMessage(text, type = 'success') {
    const messageEl = document.getElementById('message');
    if (!messageEl) return;

    messageEl.textContent = text;
    messageEl.className = `message ${type}`;

    setTimeout(() => {
        messageEl.className = 'message hidden';
    }, 5000);
}

async function handleApiError(response) {
    if (response.status === 401) {
        // Unauthorized - redirect to login
        window.location.href = '/login';
        return true;
    }
    return false;
}


// ==================== Authentication Functions ====================

async function handleLogin(event) {
    // Let the form submit naturally - server will handle redirect
    // No need to prevent default or use fetch
}

async function handleRegister(event) {
    // Let the form submit naturally - server will handle redirect
    // No need to prevent default or use fetch
}

async function logout() {
    try {
        const response = await fetch('/api/auth/logout', {
            method: 'POST'
        });

        const data = await response.json();

        if (data.status === 'success') {
            window.location.href = '/';
        }
    } catch (error) {
        console.error('Logout error:', error);
        window.location.href = '/';
    }
}


// ==================== Dashboard Functions ====================

async function syncLibrary() {
    showMessage('Syncing with Audiobookshelf...', 'success');

    try {
        const response = await fetch('/api/sync');

        if (await handleApiError(response)) return;

        const data = await response.json();

        if (data.status === 'success') {
            showMessage(data.message, 'success');
            setTimeout(() => window.location.reload(), 1500);
        } else {
            showMessage(data.message || 'Sync failed', 'error');
        }
    } catch (error) {
        showMessage('Error syncing with Audiobookshelf: ' + error.message, 'error');
    }
}

async function generateRecommendations() {
    showMessage('Generating AI recommendations...', 'success');

    try {
        const response = await fetch('/api/recommendations/generate');

        if (await handleApiError(response)) return;

        const data = await response.json();

        if (data.status === 'success') {
            showMessage(`Generated ${data.count} new recommendations!`, 'success');
            setTimeout(() => window.location.reload(), 1500);
        } else {
            showMessage(data.message || 'Failed to generate recommendations', 'error');
        }
    } catch (error) {
        showMessage('Error generating recommendations: ' + error.message, 'error');
    }
}
