/**
 * Series search functionality for FS7
 */

// Handle series search
async function handleSeriesSearch() {
    const searchInput = document.getElementById('seriesSearchInput');
    const resultsContainer = document.getElementById('seriesSearchResults');

    if (!searchInput || !resultsContainer) return;

    const query = searchInput.value.trim();
    if (!query) {
        alert('Veuillez entrer un nom de série');
        return;
    }

    try {
        resultsContainer.innerHTML = '<div class="loading-spinner">Recherche de séries TV en cours...</div>';

        // Search on series providers using the dedicated endpoint
        const response = await fetch(`${API_BASE}/series/search?q=${encodeURIComponent(query)}&lang=vf`);
        const data = await response.json();

        if (data.results && data.results['fs7'] && data.results['fs7'].length > 0) {
            const series = data.results['fs7'];
            let html = `
                <div class="streaming-results-header">
                    <h3>📺 Résultats pour "${escapeHtml(query)}"</h3>
                </div>
                <div class="search-results" style="margin-top: 20px;">
            `;

            series.forEach(s => {
                let coverImage = s.cover_image || '';

                // Convert relative poster.php URLs to absolute URLs
                if (coverImage.startsWith('/poster.php?url=')) {
                    const actualUrl = coverImage.replace('/poster.php?url=', '');
                    coverImage = actualUrl;
                } else if (coverImage.startsWith('/')) {
                    coverImage = 'https://fs7.lol' + coverImage;
                }

                html += `
                    <div class="anime-card" id="series-fs7-${encodeURIComponent(s.url)}">
                        <div class="anime-card-header">
                            <div class="anime-card-title">${escapeHtml(s.title)}</div>
                            <div class="anime-card-provider">📺 French Stream</div>
                        </div>
                        ${coverImage ? `
                            <div style="text-align: center; margin: 10px 0;">
                                <img src="${escapeHtml(coverImage)}" alt="" style="max-width: 200px; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.3);" onerror="this.style.display='none'">
                            </div>
                        ` : ''}
                        <div class="anime-card-actions">
                            <button class="btn btn-secondary btn-small" onclick="window.open('${escapeHtml(s.url)}', '_blank')">
                                🔗 Voir sur FS7
                            </button>
                            <button class="btn btn-primary btn-small" onclick="loadSeriesEpisodesDirect('${escapeHtml(s.url)}', '${escapeHtml(s.title)}')">
                                📥 Voir les épisodes
                            </button>
                        </div>
                        <div id="episodes-fs7-${encodeURIComponent(s.url)}" style="margin-top: 10px;"></div>
                    </div>
                `;
            });

            html += '</div>';
            resultsContainer.innerHTML = html;
        } else {
            resultsContainer.innerHTML = `
                <div class="no-results">
                    <p>❌ Aucune série trouvée pour "${escapeHtml(query)}"</p>
                    <p style="font-size: 12px; margin-top: 10px; opacity: 0.7;">
                        Essayez avec un autre titre ou vérifiez l'orthographe
                    </p>
                </div>`;
        }
    } catch (error) {
        console.error('Error searching series:', error);
        resultsContainer.innerHTML = `
            <div class="no-results">
                <p>❌ Erreur lors de la recherche</p>
                <p style="font-size: 12px; margin-top: 10px; color: #ff6b6b;">${error.message}</p>
            </div>`;
    }
}

// Load series episodes directly without redirecting to search
async function loadSeriesEpisodesDirect(url, title) {
    const episodesContainer = document.getElementById(`episodes-fs7-${encodeURIComponent(url)}`);

    if (!episodesContainer) return;

    try {
        episodesContainer.innerHTML = '<div class="loading-spinner">Chargement des épisodes...</div>';

        const response = await fetch(`${API_BASE}/anime/episodes?url=${encodeURIComponent(url)}&lang=vf`);
        const data = await response.json();

        if (data.episodes && data.episodes.length > 0) {
            let html = `
                <div style="margin-top: 15px;">
                    <label style="font-size: 12px; color: #00d9ff; margin-bottom: 5px; display: block;">
                        📺 Sélectionner un épisode:
                    </label>
                    <select id="select-episodes-${encodeURIComponent(url)}" style="width: 100%; padding: 8px; border-radius: 4px; border: 1px solid rgba(0, 217, 255, 0.3); background: rgba(0, 0, 0, 0.3); color: white;">
                        <option value="">Sélectionner un épisode</option>
                        ${data.episodes.map(ep => `
                            <option value="${escapeHtml(ep.url)}">Épisode ${escapeHtml(ep.episode)}</option>
                        `).join('')}
                    </select>
                    <button class="btn btn-primary" style="margin-top: 10px; width: 100%;" onclick="downloadSeriesEpisode('${escapeHtml(url)}', '${escapeHtml(title)}')">
                        <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" style="width:14px;height:14px;margin-right:4px;">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"></path>
                        </svg>
                        Télécharger l'épisode
                    </button>
                </div>
            `;
            episodesContainer.innerHTML = html;
        } else {
            episodesContainer.innerHTML = '<div class="no-results" style="margin-top: 10px;">Aucun épisode disponible</div>';
        }
    } catch (error) {
        console.error('Error loading episodes:', error);
        episodesContainer.innerHTML = `<div class="no-results" style="margin-top: 10px; color: #ff6b6b;">Erreur: ${error.message}</div>`;
    }
}

// Download series episode
async function downloadSeriesEpisode(url, title) {
    const select = document.getElementById(`select-episodes-${encodeURIComponent(url)}`);
    if (!select || !select.value) {
        alert('Veuillez sélectionner un épisode');
        return;
    }

    const episodeUrl = select.value;

    try {
        const response = await fetch(`${API_BASE}/anime/download?url=${encodeURIComponent(episodeUrl)}`, {
            method: 'POST'
        });

        if (response.ok) {
            alert(`✅ Téléchargement démarré pour "${title}"`);
            // Refresh downloads
            if (typeof loadDownloads === 'function') {
                loadDownloads();
            }
        } else {
            const error = await response.json();
            const errorMessage = error.detail
                ? (typeof error.detail === 'string' ? error.detail : JSON.stringify(error.detail))
                : 'Impossible de démarrer le téléchargement';
            alert(`❌ Erreur: ${errorMessage}`);
        }
    } catch (error) {
        console.error('Download error:', error);
        alert(`❌ Erreur lors du téléchargement: ${error.message}`);
    }
}

// Make functions available globally
window.handleSeriesSearch = handleSeriesSearch;
window.loadSeriesEpisodesDirect = loadSeriesEpisodesDirect;
window.downloadSeriesEpisode = downloadSeriesEpisode;
