// Recommendations and Latest Releases module

// Load personalized recommendations
async function loadRecommendations() {
    const container = document.getElementById('recommendationsList');
    const section = document.getElementById('recommendationsSection');

    if (!container) return;

    try {
        container.innerHTML = '<div class="flex justify-center py-8"><span class="loading loading-spinner loading-md"></span><span class="ml-3 text-base-content/60">Analyse de vos téléchargements...</span></div>';

        const response = await fetch(`${API_BASE}/recommendations?limit=12`);
        const data = await response.json();

        console.log('Recommendations response:', data);

        if (data.recommendations && data.recommendations.length > 0) {
            container.innerHTML = `<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">${data.recommendations.map(anime =>
                renderRecommendationCard(anime)
            ).join('')}</div>`;
        } else {
            container.innerHTML = `
                <div class="text-center py-16 text-base-content/50">
                    <i class="fa-solid fa-triangle-exclamation text-3xl mb-3 block"></i>
                    <p>Aucune recommandation disponible pour le moment.</p>
                    <p class="text-xs mt-2 text-base-content/40">
                        Soit l'API MyAnimeList est inaccessible, soit vous n'avez pas encore de téléchargements.
                    </p>
                    <button class="btn btn-secondary btn-sm mt-3" onclick="loadRecommendations()">
                        <i class="fa-solid fa-rotate"></i> Réessayer
                    </button>
                </div>
            `;
        }

        section.style.display = 'block';
    } catch (error) {
        console.error('Error loading recommendations:', error);
        container.innerHTML = `
            <div class="text-center py-16 text-base-content/50">
                <i class="fa-solid fa-xmark text-3xl mb-3 block"></i>
                <p>Erreur lors du chargement des recommandations.</p>
                <p class="text-xs mt-2 text-error">${error.message}</p>
                <button class="btn btn-secondary btn-sm mt-3" onclick="loadRecommendations()">
                    <i class="fa-solid fa-rotate"></i> Réessayer
                </button>
            </div>
        `;
        section.style.display = 'block';
    }
}

// Load latest releases
async function loadLatestReleases() {
    const container = document.getElementById('releasesList');
    const section = document.getElementById('releasesSection');

    if (!container) return;

    try {
        container.innerHTML = '<div class="flex justify-center py-8"><span class="loading loading-spinner loading-md"></span><span class="ml-3 text-base-content/60">Chargement des dernières sorties...</span></div>';

        const response = await fetch(`${API_BASE}/releases/latest?limit=12`);
        const data = await response.json();

        console.log('Releases response:', data);

        if (data.releases && data.releases.length > 0) {
            container.innerHTML = `<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">${data.releases.map(anime =>
                renderReleaseCard(anime)
            ).join('')}</div>`;
        } else {
            container.innerHTML = `
                <div class="text-center py-16 text-base-content/50">
                    <i class="fa-solid fa-triangle-exclamation text-3xl mb-3 block"></i>
                    <p>Aucune sortie disponible pour le moment.</p>
                    <p class="text-xs mt-2 text-base-content/40">
                        L'API MyAnimeList pourrait être temporairement inaccessible.
                    </p>
                    <button class="btn btn-secondary btn-sm mt-3" onclick="loadLatestReleases()">
                        <i class="fa-solid fa-rotate"></i> Réessayer
                    </button>
                </div>
            `;
        }

        section.style.display = 'block';
    } catch (error) {
        console.error('Error loading releases:', error);
        container.innerHTML = `
            <div class="text-center py-16 text-base-content/50">
                <i class="fa-solid fa-xmark text-3xl mb-3 block"></i>
                <p>Erreur lors du chargement des sorties.</p>
                <p class="text-xs mt-2 text-error">${error.message}</p>
                <button class="btn btn-secondary btn-sm mt-3" onclick="loadLatestReleases()">
                    <i class="fa-solid fa-rotate"></i> Réessayer
                </button>
            </div>
        `;
        section.style.display = 'block';
    }
}

// Load all home content
async function loadHomeContent() {
    console.log('loadHomeContent() called');

    const loading = document.getElementById('homeLoading');
    const recommendationsSection = document.getElementById('recommendationsSection');
    const releasesSection = document.getElementById('releasesSection');

    console.log('Elements found:', {
        loading: !!loading,
        recommendationsSection: !!recommendationsSection,
        releasesSection: !!releasesSection
    });

    if (loading) loading.style.display = 'block';
    if (recommendationsSection) recommendationsSection.style.display = 'none';
    if (releasesSection) releasesSection.style.display = 'none';

    try {
        // Load both sections in parallel
        console.log('Loading recommendations and releases...');
        await Promise.all([
            loadRecommendations(),
            loadLatestReleases()
        ]);
        console.log('Home content loaded successfully');

        // Show sections if they have content
        if (recommendationsSection) recommendationsSection.style.display = 'block';
        if (releasesSection) releasesSection.style.display = 'block';
    } catch (error) {
        console.error('Error loading home content:', error);
        if (loading) {
            loading.innerHTML = 'Erreur lors du chargement. Consultez la console pour plus de détails.';
        }
    } finally {
        if (loading) loading.style.display = 'none';
    }
}

// Render recommendation card (horizontal compact)
function renderRecommendationCard(anime) {
    const images = anime.images || {};
    const imageUrl = images.jpg?.image_url || images.webp?.image_url || '';

    const genres = anime.genres || [];
    const score = anime.score || 0;
    const reason = anime.recommendation_reason || 'Recommandé';

    return `
        <div class="card bg-base-200 border border-base-300 shadow-sm relative">
            ${reason ? `<div class="badge badge-accent badge-sm absolute top-2 left-2 z-10"><i class="fa-solid fa-lightbulb"></i> ${escapeHtml(reason)}</div>` : ''}

            <div class="card-body p-4">
                <div class="flex justify-between items-start">
                    <h4 class="card-title text-base">${escapeHtml(anime.title)}</h4>
                    ${score > 0 ? `<span class="badge badge-warning badge-sm shrink-0 ml-2"><i class="fa-solid fa-star"></i> ${score.toFixed(1)}</span>` : ''}
                </div>

                <div class="flex gap-3 mt-1">
                    ${imageUrl ? `<img src="${escapeHtml(imageUrl)}" alt="" class="w-20 h-28 object-cover rounded-lg shrink-0" onerror="this.style.display='none'">` : ''}

                    <div class="flex flex-col gap-2 text-sm">
                        <div class="flex flex-wrap gap-1">
                            ${genres.slice(0, 3).map(g => `<span class="badge badge-outline badge-sm">${escapeHtml(g)}</span>`).join('')}
                        </div>

                        <div class="text-base-content/60 text-xs">
                            ${anime.episodes ? `<i class="fa-solid fa-tv"></i> ${anime.episodes} ep` : ''}
                            ${anime.episodes && anime.status ? ' • ' : ''}
                            ${anime.status ? translateStatus(anime.status) : ''}
                        </div>
                    </div>
                </div>

                ${anime.synopsis ? `
                    <details class="collapse collapse-arrow border border-base-300 mt-2 bg-base-300/30">
                        <summary class="collapse-title text-xs font-medium py-2 min-h-0"><i class="fa-solid fa-book"></i> Synopsis</summary>
                        <div class="collapse-content text-xs text-base-content/70">
                            <p>${escapeHtml(anime.synopsis.substring(0, 150))}${anime.synopsis.length > 150 ? '...' : ''}</p>
                        </div>
                    </details>
                ` : ''}

                <div class="card-actions justify-end mt-2">
                    <button class="btn btn-secondary btn-sm" onclick="window.open('${escapeHtml(anime.url)}', '_blank')">
                        <i class="fa-solid fa-link"></i> MAL
                    </button>
                    <button class="btn btn-primary btn-sm" onclick="searchAnimeOnProviders('${escapeHtml(anime.title)}')">
                        <i class="fa-solid fa-download"></i> Télécharger
                    </button>
                </div>
            </div>
        </div>
    `;
}

// Render release card (horizontal compact)
function renderReleaseCard(anime) {
    const images = anime.images || {};
    const imageUrl = images.jpg?.image_url || images.webp?.image_url || '';

    const genres = anime.genres || [];
    const score = anime.score || 0;
    const releaseType = anime.release_type || 'Nouveau';

    return `
        <div class="card bg-base-200 border border-base-300 shadow-sm relative">
            <div class="badge badge-error badge-sm absolute top-2 left-2 z-10"><i class="fa-solid fa-fire"></i> ${escapeHtml(releaseType)}</div>

            <div class="card-body p-4">
                <div class="flex justify-between items-start">
                    <h4 class="card-title text-base">${escapeHtml(anime.title)}</h4>
                    ${score > 0 ? `<span class="badge badge-warning badge-sm shrink-0 ml-2"><i class="fa-solid fa-star"></i> ${score.toFixed(1)}</span>` : ''}
                </div>

                <div class="flex gap-3 mt-1">
                    ${imageUrl ? `<img src="${escapeHtml(imageUrl)}" alt="" class="w-20 h-28 object-cover rounded-lg shrink-0" onerror="this.style.display='none'">` : ''}

                    <div class="flex flex-col gap-2 text-sm">
                        <div class="flex flex-wrap gap-1">
                            ${genres.slice(0, 3).map(g => `<span class="badge badge-error badge-outline badge-sm">${escapeHtml(g)}</span>`).join('')}
                        </div>

                        <div class="text-base-content/60 text-xs">
                            ${anime.episodes ? `<i class="fa-solid fa-tv"></i> ${anime.episodes} ep` : ''}
                            ${anime.episodes && anime.status ? ' • ' : ''}
                            ${anime.status ? translateStatus(anime.status) : ''}
                        </div>
                    </div>
                </div>

                ${anime.synopsis ? `
                    <details class="collapse collapse-arrow border border-base-300 mt-2 bg-base-300/30">
                        <summary class="collapse-title text-xs font-medium py-2 min-h-0"><i class="fa-solid fa-book"></i> Synopsis</summary>
                        <div class="collapse-content text-xs text-base-content/70">
                            <p>${escapeHtml(anime.synopsis.substring(0, 150))}${anime.synopsis.length > 150 ? '...' : ''}</p>
                        </div>
                    </details>
                ` : ''}

                <div class="card-actions justify-end mt-2">
                    <button class="btn btn-secondary btn-sm" onclick="window.open('${escapeHtml(anime.url)}', '_blank')">
                        <i class="fa-solid fa-link"></i> MAL
                    </button>
                    <button class="btn btn-primary btn-sm" onclick="searchAnimeOnProviders('${escapeHtml(anime.title)}')">
                        <i class="fa-solid fa-download"></i> Télécharger
                    </button>
                </div>
            </div>
        </div>
    `;
}

// Get rating color based on score
function getRatingColor(score) {
    if (score >= 9) return 'text-warning';
    if (score >= 8) return 'text-success';
    if (score >= 7) return 'text-warning';
    if (score >= 6) return 'text-warning';
    return 'text-base-content/40';
}

// Search anime on providers (redirects to anime tab)
function searchAnimeOnProviders(title) {
    // Switch to anime tab
    switchTab('anime');

    // Fill search input
    const searchInput = document.getElementById('animeSearchInput');
    if (searchInput) {
        searchInput.value = title;

        // Trigger search
        setTimeout(() => {
            if (typeof handleAnimeSearch === 'function') {
                handleAnimeSearch();
            }
        }, 300);
    }
}
