{% extends "base.html" %}
{% block title %}Descobrir - Viral Social Pro{% endblock %}
{% block nav_discover %}active{% endblock %}

{% block content %}
<div class="p-6 space-y-6" x-data="discoverApp()">
    <!-- Header -->
    <div class="gradient-bg rounded-2xl p-8 text-white">
        <h1 class="text-3xl font-bold mb-2">Descobrir Virais</h1>
        <p class="text-indigo-200">Explore os vídeos mais virais de todas as plataformas</p>
    </div>

    <!-- Filters -->
    <div class="bg-white rounded-xl p-5 shadow-sm">
        <form method="GET" action="/discover" class="flex flex-wrap gap-4 items-end">
            <div class="flex-1 min-w-[200px]">
                <label class="block text-sm font-medium text-gray-700 mb-1">Buscar</label>
                <input type="text" name="search" value="{{ search }}" placeholder="Palavras-chave, hashtags..."
                       class="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-transparent outline-none">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Plataforma</label>
                <select name="platform" class="px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-500 outline-none">
                    <option value="">Todas</option>
                    <option value="youtube" {% if platform == 'youtube' %}selected{% endif %}>YouTube</option>
                    <option value="tiktok" {% if platform == 'tiktok' %}selected{% endif %}>TikTok</option>
                    <option value="instagram" {% if platform == 'instagram' %}selected{% endif %}>Instagram</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Ordenar por</label>
                <select name="sort_by" class="px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-500 outline-none">
                    <option value="viral_score" {% if sort_by == 'viral_score' %}selected{% endif %}>Viral Score</option>
                    <option value="views" {% if sort_by == 'views' %}selected{% endif %}>Views</option>
                    <option value="likes" {% if sort_by == 'likes' %}selected{% endif %}>Likes</option>
                    <option value="engagement" {% if sort_by == 'engagement' %}selected{% endif %}>Engajamento</option>
                    <option value="recent" {% if sort_by == 'recent' %}selected{% endif %}>Mais recente</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Idioma</label>
                <select name="language" class="px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-500 outline-none">
                    <option value="">Todos</option>
                    <option value="pt" {% if language == 'pt' %}selected{% endif %}>Portugues</option>
                    <option value="en" {% if language == 'en' %}selected{% endif %}>English</option>
                    <option value="es" {% if language == 'es' %}selected{% endif %}>Espanol</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Score mínimo</label>
                <input type="number" name="min_score" value="{{ min_score }}" min="0" max="100" step="5"
                       class="w-24 px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-brand-500 outline-none">
            </div>
            <button type="submit" class="px-6 py-2.5 bg-brand-500 text-white rounded-lg hover:bg-brand-600 font-medium transition">
                Filtrar
            </button>
        </form>
    </div>

    <!-- Results -->
    <div class="flex items-center justify-between">
        <p class="text-sm text-gray-500">{{ total }} vídeos encontrados</p>
    </div>

    {% if videos %}
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
        {% for video in videos %}
        <div class="group bg-white rounded-xl overflow-hidden shadow-sm card-hover fade-in">
            <!-- Thumbnail -->
            <div class="relative aspect-video bg-gray-100 cursor-pointer" onclick="window.open('{{ video.url }}', '_blank')">
                {% if video.thumbnail_url %}
                <img src="{{ video.thumbnail_url }}" alt="{{ video.title }}"
                     class="w-full h-full object-cover"
                     loading="lazy"
                     onerror="this.style.display='none'">
                {% endif %}
                <!-- Overlays -->
                <div class="absolute top-2 right-2 px-2.5 py-1 rounded-lg text-white text-sm font-bold shadow-lg"
                     style="background-color: {{ detector.get_viral_color(video.viral_score).replace('text-', '').replace('red-500', '#ef4444').replace('orange-500', '#f97316').replace('yellow-500', '#eab308').replace('blue-500', '#3b82f6').replace('green-500', '#22c55e').replace('gray-500', '#6b7280') }}">
                    {{ video.viral_score }}
                </div>
                <div class="absolute top-2 left-2 px-2 py-1 rounded-lg bg-black/60 text-white text-xs font-medium">
                    {{ video.platform | upper }}
                </div>
                {% if video.duration > 0 %}
                <div class="absolute bottom-2 right-2 px-2 py-0.5 rounded bg-black/70 text-white text-xs">
                    {{ video.duration_formatted }}
                </div>
                {% endif %}
                <!-- Hover overlay -->
                <div class="absolute inset-0 bg-black/0 group-hover:bg-black/20 transition flex items-center justify-center">
                    <svg class="w-12 h-12 text-white opacity-0 group-hover:opacity-100 transition" fill="currentColor" viewBox="0 0 24 24">
                        <path d="M8 5v14l11-7z"/>
                    </svg>
                </div>
            </div>
            <!-- Info -->
            <div class="p-4">
                <h3 class="font-medium text-sm text-gray-900 line-clamp-2 mb-2 min-h-[2.5rem]">{{ video.title[:100] }}</h3>

                <!-- Metrics -->
                <div class="grid grid-cols-3 gap-2 text-center mb-3">
                    <div class="bg-gray-50 rounded-lg py-1.5">
                        <p class="text-xs text-gray-400">Views</p>
                        <p class="text-sm font-bold text-gray-900">{{ video.views_formatted }}</p>
                    </div>
                    <div class="bg-gray-50 rounded-lg py-1.5">
                        <p class="text-xs text-gray-400">Likes</p>
                        <p class="text-sm font-bold text-gray-900">{{ "{:,}".format(video.likes).replace(",", ".") }}</p>
                    </div>
                    <div class="bg-gray-50 rounded-lg py-1.5">
                        <p class="text-xs text-gray-400">Engage</p>
                        <p class="text-sm font-bold text-gray-900">{{ video.engagement_rate }}%</p>
                    </div>
                </div>

                {% if video.creator %}
                <p class="text-xs text-gray-400 mb-3">@{{ video.creator.username }}</p>
                {% endif %}

                <!-- Actions -->
                <div class="flex gap-2">
                    <a href="{{ video.url }}" target="_blank"
                       class="flex-1 text-center px-3 py-2 text-xs font-medium bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition">
                        Abrir
                    </a>
                    <button onclick="downloadVideo({{ video.id }})"
                            class="flex-1 text-center px-3 py-2 text-xs font-medium bg-brand-500 text-white rounded-lg hover:bg-brand-600 transition"
                            {% if video.is_downloaded %}disabled class="opacity-50"{% endif %}>
                        {% if video.is_downloaded %}Baixado{% else %}Download{% endif %}
                    </button>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>

    <!-- Pagination -->
    {% if total_pages > 1 %}
    <div class="flex justify-center gap-2 mt-6">
        {% if page > 1 %}
        <a href="?page={{ page - 1 }}&platform={{ platform }}&search={{ search }}&sort_by={{ sort_by }}&min_score={{ min_score }}"
           class="px-4 py-2 bg-white border rounded-lg hover:bg-gray-50">← Anterior</a>
        {% endif %}
        <span class="px-4 py-2 bg-brand-500 text-white rounded-lg">{{ page }} / {{ total_pages }}</span>
        {% if page < total_pages %}
        <a href="?page={{ page + 1 }}&platform={{ platform }}&search={{ search }}&sort_by={{ sort_by }}&min_score={{ min_score }}"
           class="px-4 py-2 bg-white border rounded-lg hover:bg-gray-50">Próxima →</a>
        {% endif %}
    </div>
    {% endif %}

    {% else %}
    <div class="bg-white rounded-xl p-16 text-center shadow-sm">
        <div class="text-6xl mb-4">🔍</div>
        <h3 class="text-lg font-medium text-gray-900 mb-2">Nenhum vídeo encontrado</h3>
        <p class="text-gray-500 mb-6">Tente ajustar os filtros ou colete novos vídeos</p>
        <a href="/scrape" class="inline-flex items-center px-6 py-3 bg-brand-500 text-white rounded-xl hover:bg-brand-600 font-medium transition">
            Coletar Vídeos
        </a>
    </div>
    {% endif %}
</div>
{% endblock %}

{% block scripts %}
<script>
function discoverApp() {
    return {};
}

async function downloadVideo(videoId) {
    showToast('Iniciando download... aguarde, isso pode levar alguns segundos', 'info');
    try {
        const data = await apiCall(`/api/download/${videoId}`, 'POST');
        if (data.success) {
            showToast(`Download concluído: ${data.filename} (${data.size_formatted})`, 'success');
            // Trigger actual browser download via iframe (avoids popup blocker)
            triggerBrowserDownload(data.path, data.filename);
        } else {
            showToast(`Erro: ${data.error}`, 'error');
        }
    } catch (e) {
        // handled by apiCall
    }
}

function triggerBrowserDownload(filePath, filename) {
    const url = `/api/downloads/file?path=${encodeURIComponent(filePath)}`;
    // Use hidden iframe to trigger download without navigating away
    const iframe = document.createElement('iframe');
    iframe.style.display = 'none';
    iframe.src = url;
    document.body.appendChild(iframe);
    // Cleanup after download starts
    setTimeout(() => { try { document.body.removeChild(iframe); } catch(e) {} }, 60000);
}
</script>
{% endblock %}
