// ============================================
// AniCineHub - Favorites Management
// ============================================

// Add to Favorites
async function addToFavorites(id, type, title, posterPath, rating) {
    try {
        const formData = new FormData();
        formData.append('action', 'add');
        formData.append('id', id);
        formData.append('type', type);
        formData.append('title', title);
        formData.append('poster_path', posterPath);
        formData.append('rating', rating);

        const response = await fetch('api/favorites.php', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();

        if (data.success) {
            showNotification('Added to favorites!', 'success');
            updateFavoriteButton(id, true);
            updateFavoritesCount();
        } else {
            showNotification(data.message || 'Error adding to favorites', 'error');
        }
    } catch (error) {
        console.error('Error:', error);
        showNotification('Error adding to favorites', 'error');
    }
}

// Remove from Favorites
async function removeFromFavorites(id) {
    try {
        const formData = new FormData();
        formData.append('action', 'remove');
        formData.append('id', id);

        const response = await fetch('api/favorites.php', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();

        if (data.success) {
            showNotification('Removed from favorites', 'success');
            updateFavoriteButton(id, false);
            updateFavoritesCount();

            // If on favorites page, remove the card
            const card = document.querySelector(`[data-favorite-id="${id}"]`);
            if (card) {
                card.style.animation = 'fadeOut 0.3s ease-out';
                setTimeout(() => card.remove(), 300);
            }
        } else {
            showNotification(data.message || 'Error removing from favorites', 'error');
        }
    } catch (error) {
        console.error('Error:', error);
        showNotification('Error removing from favorites', 'error');
    }
}

// Check if Item is in Favorites
async function checkFavoriteStatus(id) {
    try {
        const response = await fetch(`api/favorites.php?action=check&id=${id}`);
        const data = await response.json();
        return data.isFavorite || false;
    } catch (error) {
        console.error('Error checking favorite status:', error);
        return false;
    }
}

// Update Favorite Button
function updateFavoriteButton(id, isFavorite) {
    const button = document.querySelector(`[data-media-id="${id}"]`);
    if (!button) return;

    if (isFavorite) {
        button.classList.add('active');
        button.innerHTML = '<i class="fas fa-heart"></i> Remove from Favorites';
        button.onclick = () => removeFromFavorites(id);
    } else {
        button.classList.remove('active');
        button.innerHTML = '<i class="far fa-heart"></i> Add to Favorites';
        const mediaData = button.dataset;
        button.onclick = () => addToFavorites(
            id,
            mediaData.type,
            mediaData.title,
            mediaData.poster,
            mediaData.rating
        );
    }
}

// Update Favorites Count Badge
async function updateFavoritesCount() {
    try {
        const response = await fetch('api/favorites.php?action=count');
        const data = await response.json();

        if (data.success) {
            const badge = document.querySelector('.nav-link[href="favorites.php"] .badge');
            if (badge) {
                if (data.count > 0) {
                    badge.textContent = data.count;
                    badge.style.display = 'inline-block';
                } else {
                    badge.style.display = 'none';
                }
            }
        }
    } catch (error) {
        console.error('Error updating favorites count:', error);
    }
}

// Initialize Favorite Buttons
document.addEventListener('DOMContentLoaded', () => {
    // Check status for detail page
    const favoriteBtn = document.querySelector('[data-media-id]');
    if (favoriteBtn) {
        const id = favoriteBtn.dataset.mediaId;
        checkFavoriteStatus(id).then(isFavorite => {
            updateFavoriteButton(id, isFavorite);
        });
    }

    // Update favorites count on page load
    updateFavoritesCount();
});

// Show Notification (defined in main.js, but included here for standalone use)
function showNotification(message, type = 'success') {
    // Create notification element
    const notification = document.createElement('div');
    notification.className = 'notification';
    notification.style.cssText = `
        position: fixed;
        top: 100px;
        right: 20px;
        background: ${type === 'success' ? 'linear-gradient(135deg, #00D4FF, #A259FF)' : '#e74c3c'};
        color: white;
        padding: 1rem 1.5rem;
        border-radius: 12px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
        z-index: 10000;
        display: flex;
        align-items: center;
        gap: 10px;
        animation: slideInNotification 0.3s ease-out;
        max-width: 300px;
    `;

    notification.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
        <span>${message}</span>
    `;

    document.body.appendChild(notification);

    // Remove after 3 seconds
    setTimeout(() => {
        notification.style.animation = 'fadeOut 0.3s ease-out';
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}
