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

{% block content %}
<div class="p-6 space-y-6" x-data="scrapeApp()">
    <!-- Header -->
    <div class="gradient-bg rounded-2xl p-8 text-white">
        <h1 class="text-3xl font-bold mb-2">Coletar Vídeos</h1>
        <p class="text-indigo-200">Busque e colete vídeos virais das redes sociais</p>
    </div>

    <!-- Status Banner -->
    <div x-show="statusLoaded" x-cloak class="bg-white rounded-xl shadow-sm p-4">
        <div class="flex flex-wrap items-center gap-3 text-sm">
            <span class="font-medium text-gray-700">Status:</span>
            <span class="px-3 py-1.5 rounded-full text-xs font-medium"
                  :class="status.youtube?.api_key ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'">
                YouTube: <span x-text="status.youtube?.api_key ? 'API OK' : 'Sem API key'"></span>
            </span>
            <span class="px-3 py-1.5 rounded-full text-xs font-medium bg-green-100 text-green-700">
                TikTok: Creative Center + Perfis
            </span>
            <span class="px-3 py-1.5 rounded-full text-xs font-medium"
                  :class="status.instagram?.cookies ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'">
                Instagram: <span x-text="status.instagram?.cookies ? 'Pronto' : 'Requer cookies'"></span>
            </span>
        </div>
        <div x-show="sourcesLoaded" x-cloak class="flex flex-wrap items-center gap-3 text-sm mt-2 pt-2 border-t">
            <span class="font-medium text-gray-700">APIs pagas:</span>
            <span class="px-3 py-1.5 rounded-full text-xs font-medium"
                  :class="discoverySources?.paid_sources?.scrapecreators?.configured ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-400'">
                ScrapeCreators: <span x-text="discoverySources?.paid_sources?.scrapecreators?.configured ? 'Ativo' : 'Nao config.'"></span>
            </span>
            <span class="px-3 py-1.5 rounded-full text-xs font-medium"
                  :class="discoverySources?.paid_sources?.apify?.configured ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-400'">
                Apify: <span x-text="discoverySources?.paid_sources?.apify?.configured ? 'Ativo' : 'Nao config.'"></span>
            </span>
        </div>
    </div>

    <!-- Discovery Card - Master button -->
    <div class="bg-white rounded-xl shadow-sm overflow-hidden">
        <div class="bg-gradient-to-r from-indigo-600 via-purple-600 to-pink-500 p-6 text-white">
            <div class="flex items-center justify-between">
                <div>
                    <h2 class="text-2xl font-bold mb-1">Discovery Engine</h2>
                    <p class="text-indigo-100">Busca automatica em TODAS as fontes disponiveis (YouTube + TikTok + Instagram)</p>
                </div>
                <span class="text-5xl">&#x1F680;</span>
            </div>
        </div>
        <div class="p-5 space-y-4">
            <!-- Sources Status -->
            <div x-show="sourcesLoaded" x-cloak>
                <p class="text-sm font-medium text-gray-700 mb-2">Fontes configuradas:</p>
                <div class="flex flex-wrap gap-2">
                    <template x-for="(info, name) in (discoverySources?.free_sources || {})" :key="name">
                        <span class="px-2.5 py-1 rounded-full text-xs font-medium"
                              :class="info.configured ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'"
                              x-text="name.replace(/_/g, ' ')"></span>
                    </template>
                    <template x-for="(info, name) in (discoverySources?.paid_sources || {})" :key="name">
                        <span class="px-2.5 py-1 rounded-full text-xs font-medium"
                              :class="info.configured ? 'bg-blue-100 text-blue-700' : 'bg-gray-100 text-gray-500'"
                              x-text="name + (info.configured ? '' : ' (nao config.)')"></span>
                    </template>
                </div>
                <p x-show="discoverySources?.recommendation" class="text-xs text-amber-600 mt-2" x-text="discoverySources?.recommendation"></p>
            </div>

            <div class="flex gap-3 items-end">
                <div class="flex-1">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Regiao</label>
                    <select x-model="discovery.region" class="w-full px-4 py-2.5 border border-gray-200 rounded-lg outline-none">
                        <option value="BR">Brasil</option>
                        <option value="US">EUA</option>
                        <option value="GB">Reino Unido</option>
                        <option value="MX">Mexico</option>
                        <option value="AR">Argentina</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Max por plataforma</label>
                    <input type="number" x-model="discovery.maxPerPlatform" min="10" max="100" value="50"
                           class="w-24 px-3 py-2.5 border border-gray-200 rounded-lg outline-none">
                </div>
            </div>

            <button @click="runDiscovery()"
                    :disabled="discovery.loading"
                    class="w-full py-4 bg-gradient-to-r from-indigo-600 via-purple-600 to-pink-500 text-white rounded-lg hover:opacity-90 font-bold text-lg transition disabled:opacity-50">
                <span x-show="!discovery.loading">Descobrir Videos Virais Agora</span>
                <span x-show="discovery.loading" class="flex items-center justify-center gap-2">
                    <svg class="animate-spin h-6 w-6" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                    Buscando em todas as fontes... (pode levar 1-2 min)
                </span>
            </button>

            <div x-show="discovery.result" x-cloak class="rounded-lg p-4"
                 :class="discovery.total > 0 ? 'bg-green-50 border border-green-200' : 'bg-orange-50 border border-orange-200'">
                <p class="text-sm font-medium" :class="discovery.total > 0 ? 'text-green-700' : 'text-orange-700'"
                   x-text="discovery.result"></p>
                <div x-show="discovery.sources.length > 0" class="mt-2 flex flex-wrap gap-1">
                    <template x-for="src in discovery.sources" :key="src">
                        <span class="px-2 py-0.5 bg-white rounded text-xs text-gray-600" x-text="src"></span>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- Scrape Cards -->
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

        <!-- YouTube -->
        <div class="bg-white rounded-xl shadow-sm overflow-hidden">
            <div class="bg-red-500 p-4 text-white">
                <div class="flex items-center gap-3">
                    <span class="text-3xl">▶️</span>
                    <div>
                        <h2 class="text-lg font-bold">YouTube</h2>
                        <p class="text-red-100 text-sm">Trending & busca por palavras-chave</p>
                    </div>
                </div>
            </div>
            <div class="p-5 space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Buscar por</label>
                    <input type="text" x-model="youtube.query" placeholder="Ex: receitas virais, trends..."
                           class="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-red-500 outline-none">
                </div>
                <div class="flex gap-3">
                    <div class="flex-1">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Região</label>
                        <select x-model="youtube.region" class="w-full px-4 py-2.5 border border-gray-200 rounded-lg outline-none">
                            <option value="BR">Brasil</option>
                            <option value="US">EUA</option>
                            <option value="GB">Reino Unido</option>
                            <option value="PT">Portugal</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Qtd</label>
                        <input type="number" x-model="youtube.maxResults" min="5" max="50" value="25"
                               class="w-20 px-3 py-2.5 border border-gray-200 rounded-lg outline-none">
                    </div>
                </div>
                <div class="flex items-center gap-2">
                    <input type="checkbox" x-model="youtube.trending" id="yt-trending" class="rounded">
                    <label for="yt-trending" class="text-sm text-gray-600">Apenas trending (em alta)</label>
                </div>
                <button @click="scrapeYoutube()"
                        :disabled="youtube.loading"
                        class="w-full py-3 bg-red-500 text-white rounded-lg hover:bg-red-600 font-medium transition disabled:opacity-50">
                    <span x-show="!youtube.loading">Coletar do YouTube</span>
                    <span x-show="youtube.loading" class="flex items-center justify-center gap-2">
                        <svg class="animate-spin h-5 w-5" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                        Coletando...
                    </span>
                </button>
                <div x-show="youtube.result" x-cloak class="text-sm font-medium text-center p-2 rounded"
                     :class="youtube.found > 0 ? 'text-green-600 bg-green-50' : 'text-orange-600 bg-orange-50'"
                     x-text="youtube.result"></div>
            </div>
        </div>

        <!-- TikTok -->
        <div class="bg-white rounded-xl shadow-sm overflow-hidden">
            <div class="bg-gray-900 p-4 text-white">
                <div class="flex items-center gap-3">
                    <span class="text-3xl">🎵</span>
                    <div>
                        <h2 class="text-lg font-bold">TikTok</h2>
                        <p class="text-gray-300 text-sm">Coleta por perfil de criador</p>
                    </div>
                </div>
            </div>
            <div class="p-5 space-y-4">
                <div class="bg-blue-50 border border-blue-200 rounded-lg p-3 text-xs text-blue-700">
                    <strong>Como funciona:</strong> Digite o nome de um criador do TikTok (sem @).
                    O sistema coleta os vídeos mais recentes do perfil dele.
                    <span class="block mt-1 text-blue-500">A coleta pode levar 10-30 segundos, aguarde!</span>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Nome do criador</label>
                    <input type="text" x-model="tiktok.username" placeholder="Ex: charlidamelio, zachking, mrbeast..."
                           class="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-gray-500 outline-none"
                           @keydown.enter="scrapeTiktok()">
                </div>
                <div class="flex flex-wrap gap-2">
                    <span class="text-xs text-gray-400">Sugestões:</span>
                    <button type="button" @click="tiktok.username = 'charlidamelio'" class="text-xs px-2 py-1 bg-gray-100 rounded-lg hover:bg-gray-200 transition">charlidamelio</button>
                    <button type="button" @click="tiktok.username = 'zachking'" class="text-xs px-2 py-1 bg-gray-100 rounded-lg hover:bg-gray-200 transition">zachking</button>
                    <button type="button" @click="tiktok.username = 'mrbeast'" class="text-xs px-2 py-1 bg-gray-100 rounded-lg hover:bg-gray-200 transition">mrbeast</button>
                    <button type="button" @click="tiktok.username = 'khaby.lame'" class="text-xs px-2 py-1 bg-gray-100 rounded-lg hover:bg-gray-200 transition">khaby.lame</button>
                    <button type="button" @click="tiktok.username = 'bellapoarch'" class="text-xs px-2 py-1 bg-gray-100 rounded-lg hover:bg-gray-200 transition">bellapoarch</button>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Quantidade</label>
                    <input type="number" x-model="tiktok.maxResults" min="3" max="30" value="10"
                           class="w-20 px-3 py-2.5 border border-gray-200 rounded-lg outline-none">
                </div>
                <button @click="scrapeTiktok()"
                        :disabled="tiktok.loading"
                        class="w-full py-3 bg-gray-900 text-white rounded-lg hover:bg-gray-800 font-medium transition disabled:opacity-50">
                    <span x-show="!tiktok.loading">Coletar do TikTok</span>
                    <span x-show="tiktok.loading" class="flex items-center justify-center gap-2">
                        <svg class="animate-spin h-5 w-5" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                        Coletando... (pode levar até 30s)
                    </span>
                </button>
                <div x-show="tiktok.result" x-cloak class="text-sm font-medium text-center p-2 rounded"
                     :class="tiktok.found > 0 ? 'text-green-600 bg-green-50' : 'text-orange-600 bg-orange-50'"
                     x-text="tiktok.result"></div>
            </div>
        </div>

        <!-- Instagram -->
        <div class="bg-white rounded-xl shadow-sm overflow-hidden">
            <div class="bg-gradient-to-r from-purple-500 to-pink-500 p-4 text-white">
                <div class="flex items-center gap-3">
                    <span class="text-3xl">📷</span>
                    <div>
                        <h2 class="text-lg font-bold">Instagram</h2>
                        <p class="text-pink-100 text-sm">Reels por hashtag ou perfil</p>
                    </div>
                </div>
            </div>
            <div class="p-5 space-y-4">
                <template x-if="!status.instagram?.cookies">
                    <div class="bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-700">
                        <strong class="block mb-1">Cookies necessarios</strong>
                        <p class="mb-2">Instagram bloqueia acesso sem login. Para usar esta funcao:</p>
                        <ol class="list-decimal ml-4 space-y-1 text-xs">
                            <li>Instale a extensao "Get cookies.txt" no Chrome/Firefox</li>
                            <li>Acesse instagram.com e faca login</li>
                            <li>Exporte os cookies como arquivo <code class="bg-red-100 px-1 rounded">cookies.txt</code></li>
                            <li>Adicione no arquivo <code class="bg-red-100 px-1 rounded">.env</code>: <br><code class="bg-red-100 px-1 rounded">INSTAGRAM_COOKIE_FILE=/caminho/para/cookies.txt</code></li>
                            <li>Reinicie o servidor</li>
                        </ol>
                    </div>
                </template>
                <template x-if="status.instagram?.cookies">
                    <div class="bg-green-50 border border-green-200 rounded-lg p-3 text-xs text-green-700">
                        <strong>Cookies configurados!</strong> A coleta do Instagram esta pronta para uso.
                    </div>
                </template>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Perfil do criador</label>
                    <input type="text" x-model="instagram.username" placeholder="Ex: natgeo, nike, cristiano..."
                           class="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-pink-500 outline-none"
                           :disabled="!status.instagram?.cookies"
                           @keydown.enter="scrapeInstagram()">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Ou por hashtag</label>
                    <input type="text" x-model="instagram.hashtag" placeholder="Ex: reels, viral..."
                           class="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-pink-500 outline-none"
                           :disabled="!status.instagram?.cookies">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Quantidade</label>
                    <input type="number" x-model="instagram.maxResults" min="3" max="30" value="10"
                           class="w-20 px-3 py-2.5 border border-gray-200 rounded-lg outline-none"
                           :disabled="!status.instagram?.cookies">
                </div>
                <button @click="scrapeInstagram()"
                        :disabled="instagram.loading || !status.instagram?.cookies"
                        class="w-full py-3 bg-gradient-to-r from-purple-500 to-pink-500 text-white rounded-lg hover:from-purple-600 hover:to-pink-600 font-medium transition disabled:opacity-50 disabled:cursor-not-allowed">
                    <span x-show="!instagram.loading" x-text="status.instagram?.cookies ? 'Coletar do Instagram' : 'Cookies nao configurados'"></span>
                    <span x-show="instagram.loading" class="flex items-center justify-center gap-2">
                        <svg class="animate-spin h-5 w-5" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                        Coletando...
                    </span>
                </button>
                <div x-show="instagram.result" x-cloak class="text-sm font-medium text-center p-2 rounded"
                     :class="instagram.found > 0 ? 'text-green-600 bg-green-50' : 'text-orange-600 bg-orange-50'"
                     x-text="instagram.result"></div>
            </div>
        </div>
    </div>

</div>
{% endblock %}

{% block scripts %}
<script>
function scrapeApp() {
    return {
        youtube: { query: '', region: 'BR', maxResults: 25, trending: false, loading: false, result: '', found: 0 },
        tiktok: { username: '', maxResults: 10, loading: false, result: '', found: 0 },
        instagram: { hashtag: '', username: '', maxResults: 10, loading: false, result: '', found: 0 },
        discovery: { region: 'BR', maxPerPlatform: 50, loading: false, result: '', total: 0, sources: [] },
        status: {},
        statusLoaded: false,
        discoverySources: null,
        sourcesLoaded: false,

        init() {
            this.loadStatus();
            this.loadSources();
        },

        async loadSources() {
            try {
                this.discoverySources = await apiCall('/api/discover/sources');
                this.sourcesLoaded = true;
            } catch(e) {}
        },

        async runDiscovery() {
            this.discovery.loading = true;
            this.discovery.result = '';
            this.discovery.total = 0;
            this.discovery.sources = [];
            try {
                const params = new URLSearchParams({
                    region: this.discovery.region,
                    max_per_platform: this.discovery.maxPerPlatform,
                });
                const data = await apiCall(`/api/discover/all?${params}`);
                const yt = data.youtube?.length || 0;
                const tt = data.tiktok?.length || 0;
                const ig = data.instagram?.length || 0;
                this.discovery.total = data.total || 0;
                this.discovery.sources = data.sources_used || [];
                this.discovery.result = `${data.saved_to_db || 0} videos salvos! (YouTube: ${yt}, TikTok: ${tt}, Instagram: ${ig}) de ${this.discovery.sources.length} fontes`;
                showToast(this.discovery.result, this.discovery.total > 0 ? 'success' : 'warning');
            } catch (e) {
                this.discovery.result = e.message || 'Erro no discovery';
                showToast(this.discovery.result, 'error');
            }
            this.discovery.loading = false;
        },

        async loadStatus() {
            try {
                this.status = await apiCall('/api/scraper/status');
                this.statusLoaded = true;
            } catch(e) {}
        },

        async scrapeYoutube() {
            this.youtube.loading = true;
            this.youtube.result = '';
            this.youtube.found = 0;
            try {
                const params = new URLSearchParams();
                if (this.youtube.query) params.set('query', this.youtube.query);
                params.set('region', this.youtube.region);
                params.set('max_results', this.youtube.maxResults);
                params.set('trending', this.youtube.trending);
                const data = await apiCall(`/api/scrape/youtube?${params}`, 'POST');
                this.youtube.result = data.message;
                this.youtube.found = data.found || 0;
                showToast(data.message, data.found > 0 ? 'success' : 'warning');
            } catch (e) {
                const msg = e.message || 'Erro na coleta';
                this.youtube.result = msg;
                showToast(msg, 'error');
            }
            this.youtube.loading = false;
        },

        async scrapeTiktok() {
            const username = (this.tiktok.username || '').trim().replace('@', '');
            if (!username) {
                showToast('Digite o nome de um criador do TikTok', 'warning');
                return;
            }
            this.tiktok.loading = true;
            this.tiktok.result = '';
            this.tiktok.found = 0;
            try {
                const params = new URLSearchParams();
                params.set('username', username);
                params.set('max_results', this.tiktok.maxResults);
                const data = await apiCall(`/api/scrape/tiktok?${params}`, 'POST');
                this.tiktok.result = data.message;
                this.tiktok.found = data.found || 0;
                showToast(data.message, data.found > 0 ? 'success' : 'warning');
            } catch (e) {
                const msg = e.message || 'Erro na coleta do TikTok. Verifique se o nome do criador esta correto.';
                this.tiktok.result = msg;
                showToast(msg, 'error');
            }
            this.tiktok.loading = false;
        },

        async scrapeInstagram() {
            if (!this.status.instagram?.cookies) {
                showToast('Instagram requer cookies de login. Veja as instrucoes no card do Instagram.', 'error');
                return;
            }
            if (!this.instagram.hashtag && !this.instagram.username) {
                showToast('Informe um perfil ou hashtag', 'warning');
                return;
            }
            this.instagram.loading = true;
            this.instagram.result = '';
            this.instagram.found = 0;
            try {
                const params = new URLSearchParams();
                if (this.instagram.username) params.set('username', this.instagram.username.replace('@', ''));
                if (this.instagram.hashtag) params.set('hashtag', this.instagram.hashtag.replace('#', ''));
                params.set('max_results', this.instagram.maxResults);
                const data = await apiCall(`/api/scrape/instagram?${params}`, 'POST');
                this.instagram.result = data.message;
                this.instagram.found = data.found || 0;
                showToast(data.message, data.found > 0 ? 'success' : 'warning');
            } catch (e) {
                const msg = e.message || 'Erro na coleta do Instagram. Verifique se os cookies estao validos.';
                this.instagram.result = msg;
                showToast(msg, 'error');
            }
            this.instagram.loading = false;
        },
    };
}

</script>
{% endblock %}
