{% extends "base.html" %}
{% block title %}Viral Scanner - Viral Social Pro{% endblock %}
{% block nav_scanner %}active{% endblock %}
{% block mnav_scanner %}active{% endblock %}
{% block page_title %}Viral Scanner{% endblock %}
{% block page_subtitle %}Encontre videos virais com minimo consumo de API{% endblock %}

{% block content %}
<div x-data="scannerApp()" x-init="init()" class="space-y-5">

    <!-- Header + Scan Panel -->
    <div class="glass-card rounded-2xl overflow-hidden animate-fade-up">
        <!-- Top bar -->
        <div class="p-5 flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div class="flex items-center gap-4">
                <div class="w-12 h-12 rounded-xl gradient-brand flex items-center justify-center flex-shrink-0">
                    <i data-lucide="scan" class="w-6 h-6 text-white"></i>
                </div>
                <div>
                    <h1 class="text-xl md:text-2xl font-bold text-white">Viral Scanner</h1>
                    <p class="text-sm text-white/40 mt-0.5">Encontre videos virais de todas as plataformas</p>
                </div>
            </div>
            <div class="flex items-center gap-3">
                <div class="glass-light rounded-xl px-4 py-2 text-sm">
                    <span class="text-white/50"><span class="text-brand-300 font-bold" x-text="total"></span> videos</span>
                    <span class="text-white/20 mx-2">|</span>
                    <span class="text-white/50"><span class="text-orange-400 font-bold" x-text="usage.credits_today || 0"></span> creditos hoje</span>
                </div>
                <button @click="showScanPanel = !showScanPanel" class="px-4 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition flex items-center gap-2">
                    <i data-lucide="radar" class="w-4 h-4"></i> Novo Scan
                </button>
            </div>
        </div>

        <!-- Scan Panel (collapsible) -->
        <div x-show="showScanPanel" x-collapse x-cloak class="border-t border-white/5">
            <div class="p-5 space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- Keywords input -->
                    <div>
                        <label class="text-[11px] text-white/40 uppercase tracking-wider font-semibold mb-2 block">Keywords para buscar</label>
                        <textarea x-model="scanKeywords" rows="3" placeholder="Digite keywords separadas por virgula. Ex: skincare viral, receita facil, diy casa, maquiagem tutorial"
                                  class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-sm text-white/80 outline-none placeholder:text-white/20 resize-none focus:border-brand-500/50 transition"></textarea>
                        <p class="text-[10px] text-white/30 mt-1">Separe cada keyword com virgula. Deixe vazio para usar keywords configuradas.</p>
                    </div>
                    <!-- Options -->
                    <div class="space-y-3">
                        <div>
                            <label class="text-[11px] text-white/40 uppercase tracking-wider font-semibold mb-2 block">Plataformas para buscar</label>
                            <div class="flex flex-wrap gap-2">
                                <button @click="scanPlatforms.tiktok = !scanPlatforms.tiktok"
                                        class="px-3 py-1.5 rounded-lg text-xs font-semibold transition flex items-center gap-1.5"
                                        :class="scanPlatforms.tiktok ? 'bg-white/15 text-white border border-white/30' : 'glass-light text-white/40'">
                                    <span class="w-2 h-2 rounded-full" :class="scanPlatforms.tiktok ? 'bg-white' : 'bg-white/20'"></span> TikTok
                                </button>
                                <button @click="scanPlatforms.youtube = !scanPlatforms.youtube"
                                        class="px-3 py-1.5 rounded-lg text-xs font-semibold transition flex items-center gap-1.5"
                                        :class="scanPlatforms.youtube ? 'bg-red-500/20 text-red-400 border border-red-500/30' : 'glass-light text-white/40'">
                                    <span class="w-2 h-2 rounded-full" :class="scanPlatforms.youtube ? 'bg-red-400' : 'bg-white/20'"></span> YouTube
                                </button>
                                <button @click="scanPlatforms.instagram = !scanPlatforms.instagram"
                                        class="px-3 py-1.5 rounded-lg text-xs font-semibold transition flex items-center gap-1.5"
                                        :class="scanPlatforms.instagram ? 'bg-pink-500/20 text-pink-400 border border-pink-500/30' : 'glass-light text-white/40'">
                                    <span class="w-2 h-2 rounded-full" :class="scanPlatforms.instagram ? 'bg-pink-400' : 'bg-white/20'"></span> Instagram
                                </button>
                            </div>
                        </div>
                        <div>
                            <label class="text-[11px] text-white/40 uppercase tracking-wider font-semibold mb-2 block">Quantidade por keyword</label>
                            <div class="flex gap-2">
                                <template x-for="n in [10, 20, 30, 50]">
                                    <button @click="scanMaxResults = n" class="px-3 py-1.5 rounded-lg text-xs font-semibold transition"
                                            :class="scanMaxResults === n ? 'bg-brand-500/30 text-brand-300 border border-brand-500/50' : 'glass-light text-white/50'"
                                            x-text="n + ' videos'"></button>
                                </template>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Hashtag & Sound scan -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div>
                        <label class="text-[11px] text-white/40 uppercase tracking-wider font-semibold mb-1 block">Scan por Hashtag</label>
                        <div class="flex gap-2">
                            <input x-model="scanHashtag" type="text" placeholder="#construcao, #viral"
                                   class="flex-1 bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white/80 outline-none placeholder:text-white/20 focus:border-purple-500/50 transition">
                            <button @click="runHashtagScan()" :disabled="scanning"
                                    class="px-3 py-2 rounded-lg bg-purple-600 hover:bg-purple-500 text-white text-xs font-bold transition disabled:opacity-50 flex items-center gap-1">
                                <i data-lucide="hash" class="w-3 h-3"></i> Scan
                            </button>
                        </div>
                    </div>
                    <div>
                        <label class="text-[11px] text-white/40 uppercase tracking-wider font-semibold mb-1 block">Scan por Som/Musica</label>
                        <div class="flex gap-2">
                            <input x-model="scanSoundUrl" type="text" placeholder="URL do som TikTok"
                                   class="flex-1 bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white/80 outline-none placeholder:text-white/20 focus:border-pink-500/50 transition">
                            <button @click="runSoundScan()" :disabled="scanning"
                                    class="px-3 py-2 rounded-lg bg-pink-600 hover:bg-pink-500 text-white text-xs font-bold transition disabled:opacity-50 flex items-center gap-1">
                                <i data-lucide="music" class="w-3 h-3"></i> Scan
                            </button>
                        </div>
                    </div>
                </div>
                <!-- Scan actions -->
                <div class="flex flex-wrap items-center gap-3 pt-2 border-t border-white/5">
                    <button @click="runScan()" :disabled="scanning"
                            class="px-6 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition flex items-center gap-2 disabled:opacity-50">
                        <i data-lucide="radar" class="w-4 h-4" :class="scanning && 'animate-spin'"></i>
                        <span x-text="scanning ? 'Escaneando...' : 'Executar Scan'"></span>
                    </button>
                    <button @click="runCreativeCenter()" :disabled="scanning"
                            class="px-5 py-2.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-semibold text-sm transition flex items-center gap-2 disabled:opacity-50">
                        <i data-lucide="sparkles" class="w-4 h-4"></i> Creative Center
                        <span class="text-[10px] bg-emerald-400/30 px-1.5 py-0.5 rounded-full font-bold">FREE</span>
                    </button>
                    <button @click="emergencyPause()"
                            class="px-4 py-2.5 rounded-xl bg-red-600/80 hover:bg-red-500 text-white font-semibold text-sm transition flex items-center gap-2">
                        <i data-lucide="octagon" class="w-4 h-4"></i> Pausa
                    </button>
                    <!-- Scan result feedback -->
                    <div x-show="scanResult" class="flex-1 text-sm text-white/60" x-text="scanResult"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Platform Tabs + Quick Presets -->
    <div class="space-y-3 animate-fade-up-delay">
        <!-- Platform tabs -->
        <div class="flex flex-wrap items-center gap-3">
            <div class="flex gap-1 bg-white/5 rounded-xl p-1">
                <button @click="filters.platform=''; applyFilters()" class="tab-btn" :class="filters.platform==='' && 'active'">Todos</button>
                <button @click="filters.platform='youtube'; applyFilters()" class="tab-btn" :class="filters.platform==='youtube' && 'active'">YouTube</button>
                <button @click="filters.platform='tiktok'; applyFilters()" class="tab-btn" :class="filters.platform==='tiktok' && 'active'">TikTok</button>
                <button @click="filters.platform='instagram'; applyFilters()" class="tab-btn" :class="filters.platform==='instagram' && 'active'">Instagram</button>
            </div>
            <!-- Search -->
            <div class="flex-1 min-w-[200px] flex items-center glass-light rounded-xl px-3 py-2">
                <i data-lucide="search" class="w-4 h-4 text-white/30 mr-2 flex-shrink-0"></i>
                <input type="text" x-model="filters.description_contains" @keyup.enter="applyFilters()" placeholder="Buscar por titulo, descricao..." class="bg-transparent border-none outline-none text-sm text-white/80 placeholder:text-white/25 w-full">
            </div>
        </div>
        <!-- Quick presets -->
        <div class="flex flex-wrap gap-2">
            <button @click="applyPreset('mega_viral')"
                    class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                    :class="activePreset === 'mega_viral' ? 'bg-red-500 text-white shadow-lg shadow-red-500/30' : 'glass-light text-red-400 hover:bg-red-500/20'">
                MEGA VIRAL
            </button>
            <button @click="applyPreset('shop_viral')"
                    class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                    :class="activePreset === 'shop_viral' ? 'bg-emerald-500 text-white shadow-lg shadow-emerald-500/30' : 'glass-light text-emerald-400 hover:bg-emerald-500/20'">
                Shop Viral
            </button>
            <button @click="applyPreset('small_creator')"
                    class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                    :class="activePreset === 'small_creator' ? 'bg-blue-500 text-white shadow-lg shadow-blue-500/30' : 'glass-light text-blue-400 hover:bg-blue-500/20'">
                Criador Pequeno
            </button>
            <button @click="applyPreset('trending_now')"
                    class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                    :class="activePreset === 'trending_now' ? 'bg-yellow-500 text-black shadow-lg shadow-yellow-500/30' : 'glass-light text-yellow-400 hover:bg-yellow-500/20'">
                Trending Agora
            </button>
            <button @click="applyPreset('replicable')"
                    class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                    :class="activePreset === 'replicable' ? 'bg-purple-500 text-white shadow-lg shadow-purple-500/30' : 'glass-light text-purple-400 hover:bg-purple-500/20'">
                Facil Replicar
            </button>
            <button @click="applyPreset('emerging')"
                    class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                    :class="activePreset === 'emerging' ? 'bg-cyan-500 text-white shadow-lg shadow-cyan-500/30' : 'glass-light text-cyan-400 hover:bg-cyan-500/20'">
                Emergentes
            </button>
        </div>
    </div>

    <!-- Main Layout: Filters Sidebar + Content Grid -->
    <div class="flex gap-5">

        <!-- Filter Panel (Sidebar) -->
        <div class="hidden md:block transition-all duration-300"
             :class="showFilters ? 'w-[320px] flex-shrink-0' : 'w-0 overflow-hidden'">
            <div class="glass-card rounded-2xl p-4 space-y-5 sticky top-20">
                <div class="flex items-center justify-between">
                    <h3 class="text-sm font-bold text-white/80 flex items-center gap-2">
                        <i data-lucide="sliders-horizontal" class="w-4 h-4 text-brand-300"></i> Filtros
                    </h3>
                    <button @click="showFilters = false" class="p-1 rounded-lg hover:bg-white/10 transition">
                        <i data-lucide="panel-left-close" class="w-4 h-4 text-white/40"></i>
                    </button>
                </div>

                <!-- Sort -->
                <div>
                    <label class="text-[11px] text-white/40 uppercase tracking-wider font-semibold mb-1.5 block">Ordenar por</label>
                    <select x-model="filters.sort_by" class="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 outline-none">
                        <option value="viral_score">Viral Score</option>
                        <option value="views">Views</option>
                        <option value="engagement">Engagement</option>
                        <option value="recent">Recente</option>
                        <option value="outlier">Outlier Ratio</option>
                        <option value="likes">Likes</option>
                    </select>
                </div>

                <!-- Categoria Section -->
                <div>
                    <p class="text-[10px] text-white/30 uppercase tracking-widest font-semibold mb-3 flex items-center gap-2">
                        <i data-lucide="layout-grid" class="w-3 h-3"></i> Categoria
                    </p>
                    <div class="flex flex-wrap gap-1.5">
                        <button @click="filters.category = ''" class="px-2.5 py-1 rounded-lg text-[10px] font-semibold transition"
                                :class="!filters.category ? 'bg-brand-500/30 text-brand-300 border border-brand-500/50' : 'glass-light text-white/50 hover:text-white/80'">Todas</button>
                        <template x-for="cat in categories">
                            <button @click="filters.category = filters.category === cat.id ? '' : cat.id"
                                    class="px-2.5 py-1 rounded-lg text-[10px] font-semibold transition flex items-center gap-1"
                                    :class="filters.category === cat.id ? 'bg-brand-500/30 text-brand-300 border border-brand-500/50' : 'glass-light text-white/50 hover:text-white/80'">
                                <span x-text="cat.icon"></span> <span x-text="cat.name"></span>
                            </button>
                        </template>
                    </div>
                </div>

                <!-- Estilo de Video Section -->
                <div>
                    <p class="text-[10px] text-white/30 uppercase tracking-widest font-semibold mb-3 flex items-center gap-2">
                        <i data-lucide="clapperboard" class="w-3 h-3"></i> Estilo de Video
                    </p>
                    <div class="flex flex-wrap gap-1.5">
                        <button @click="filters.style = ''" class="px-2.5 py-1 rounded-lg text-[10px] font-semibold transition"
                                :class="!filters.style ? 'bg-cyan-500/30 text-cyan-300 border border-cyan-500/50' : 'glass-light text-white/50 hover:text-white/80'">Todos</button>
                        <template x-for="st in styles">
                            <button @click="filters.style = filters.style === st.id ? '' : st.id"
                                    class="px-2.5 py-1 rounded-lg text-[10px] font-semibold transition flex items-center gap-1"
                                    :class="filters.style === st.id ? 'bg-cyan-500/30 text-cyan-300 border border-cyan-500/50' : 'glass-light text-white/50 hover:text-white/80'">
                                <span x-text="st.icon"></span> <span x-text="st.name"></span>
                            </button>
                        </template>
                    </div>
                </div>

                <!-- Performance Section -->
                <div>
                    <p class="text-[10px] text-white/30 uppercase tracking-widest font-semibold mb-3 flex items-center gap-2">
                        <i data-lucide="bar-chart-3" class="w-3 h-3"></i> Performance
                    </p>

                    <!-- Views minimas -->
                    <div class="mb-3">
                        <label class="text-[11px] text-white/40 mb-1 block">Views minimas</label>
                        <div class="flex flex-wrap gap-1.5">
                            <template x-for="v in [50000, 100000, 500000, 1000000, 5000000]">
                                <button @click="filters.min_views = filters.min_views === v ? 0 : v"
                                        class="px-2 py-1 rounded-lg text-[10px] font-semibold transition"
                                        :class="filters.min_views === v ? 'bg-brand-500/30 text-brand-300 border border-brand-500/50' : 'glass-light text-white/50 hover:text-white/80'"
                                        x-text="formatNumber(v)"></button>
                            </template>
                        </div>
                    </div>

                    <!-- Viral Score -->
                    <div class="mb-3">
                        <label class="text-[11px] text-white/40 mb-1 flex justify-between">
                            <span>Viral Score minimo</span>
                            <span class="text-brand-300" x-text="filters.min_viral_score || 'Qualquer'"></span>
                        </label>
                        <input type="range" x-model.number="filters.min_viral_score" min="0" max="90" step="10" class="w-full accent-brand-500">
                    </div>

                    <!-- Outlier Ratio -->
                    <div class="mb-3">
                        <label class="text-[11px] text-white/40 mb-1 block">Outlier Ratio</label>
                        <div class="flex flex-wrap gap-1.5">
                            <template x-for="o in [2, 5, 10, 20]">
                                <button @click="filters.min_outlier = filters.min_outlier === o ? 0 : o"
                                        class="px-2.5 py-1 rounded-lg text-[10px] font-semibold transition"
                                        :class="filters.min_outlier === o ? 'bg-orange-500/30 text-orange-300 border border-orange-500/50' : 'glass-light text-white/50 hover:text-white/80'"
                                        x-text="o + 'x'"></button>
                            </template>
                        </div>
                    </div>
                </div>

                <!-- Conteudo Section -->
                <div>
                    <p class="text-[10px] text-white/30 uppercase tracking-widest font-semibold mb-3 flex items-center gap-2">
                        <i data-lucide="film" class="w-3 h-3"></i> Conteudo
                    </p>

                    <!-- Duracao -->
                    <div class="mb-3">
                        <label class="text-[11px] text-white/40 mb-1 block">Duracao</label>
                        <select x-model="filters.max_duration" @change="
                            if ($event.target.value === '15') { filters.min_duration = 0; filters.max_duration = 15; }
                            else if ($event.target.value === '30') { filters.min_duration = 15; filters.max_duration = 30; }
                            else if ($event.target.value === '60') { filters.min_duration = 30; filters.max_duration = 60; }
                            else if ($event.target.value === '180') { filters.min_duration = 60; filters.max_duration = 180; }
                            else if ($event.target.value === '9999') { filters.min_duration = 180; filters.max_duration = 9999; }
                            else { filters.min_duration = 0; filters.max_duration = 0; }
                        " class="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-1.5 text-xs text-white/70 outline-none">
                            <option value="0">Todas</option>
                            <option value="15">0-15s (Shorts)</option>
                            <option value="30">15-30s</option>
                            <option value="60">30-60s</option>
                            <option value="180">1-3min</option>
                            <option value="9999">3min+</option>
                        </select>
                    </div>

                    <!-- Publicado nos ultimos -->
                    <div class="mb-3">
                        <label class="text-[11px] text-white/40 mb-1 block">Publicado nos ultimos</label>
                        <select x-model.number="filters.published_within_hours" class="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-1.5 text-xs text-white/70 outline-none">
                            <option value="0">Todos</option>
                            <option value="24">1 dia</option>
                            <option value="168">7 dias</option>
                            <option value="720">30 dias</option>
                            <option value="2160">90 dias</option>
                        </select>
                    </div>

                    <!-- Tamanho do criador -->
                    <div class="mb-3">
                        <label class="text-[11px] text-white/40 mb-1 block">Tamanho do criador</label>
                        <div class="flex flex-wrap gap-1.5">
                            <template x-for="tier in ['Nano', 'Micro', 'Mid', 'Macro', 'Mega']">
                                <button @click="filters.creator_tier = filters.creator_tier === tier.toLowerCase() ? '' : tier.toLowerCase()"
                                        class="px-2 py-1 rounded-lg text-[10px] font-semibold transition"
                                        :class="filters.creator_tier === tier.toLowerCase() ? 'bg-brand-500/30 text-brand-300 border border-brand-500/50' : 'glass-light text-white/50 hover:text-white/80'"
                                        x-text="tier"></button>
                            </template>
                        </div>
                    </div>

                    <!-- Tem Produto Shop -->
                    <div class="mb-3">
                        <label class="text-[11px] text-white/40 mb-1 flex items-center justify-between">
                            <span>Tem Produto Shop</span>
                            <button @click="filters.has_product = filters.has_product === 'yes' ? '' : 'yes'"
                                    class="relative w-10 h-5 rounded-full transition-colors duration-200"
                                    :class="filters.has_product === 'yes' ? 'bg-emerald-500' : 'bg-white/10'">
                                <span class="absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform duration-200"
                                      :class="filters.has_product === 'yes' && 'translate-x-5'"></span>
                            </button>
                        </label>
                    </div>
                </div>

                <!-- Filter Actions -->
                <div class="flex gap-2 pt-2 border-t border-white/5">
                    <button @click="applyFilters()" class="flex-1 px-4 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition flex items-center justify-center gap-2">
                        <i data-lucide="filter" class="w-4 h-4"></i> Aplicar
                    </button>
                    <button @click="clearFilters()" class="px-4 py-2.5 rounded-xl glass-light text-white/60 font-medium text-sm hover:text-white transition">
                        Limpar
                    </button>
                </div>
            </div>
        </div>

        <!-- Mobile Filter Button -->
        <button @click="showMobileFilters = true" class="md:hidden fixed bottom-20 right-4 z-40 w-12 h-12 rounded-full gradient-brand flex items-center justify-center shadow-lg shadow-brand-500/30">
            <i data-lucide="sliders-horizontal" class="w-5 h-5 text-white"></i>
        </button>

        <!-- Mobile Filter Modal -->
        <div x-show="showMobileFilters" x-cloak class="md:hidden fixed inset-0 z-50 bg-black/80 backdrop-blur-sm" @click.self="showMobileFilters = false"
             x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100"
             x-transition:leave="transition ease-in duration-150" x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0">
            <div class="absolute right-0 top-0 h-full w-[85vw] max-w-[360px] overflow-y-auto"
                 style="background: linear-gradient(180deg, rgba(15,10,30,0.98) 0%, rgba(5,2,8,0.98) 100%); border-left: 1px solid rgba(124,58,237,0.15);"
                 x-transition:enter="transition ease-out duration-300" x-transition:enter-start="translate-x-full" x-transition:enter-end="translate-x-0"
                 x-transition:leave="transition ease-in duration-200" x-transition:leave-start="translate-x-0" x-transition:leave-end="translate-x-full">
                <div class="p-4 space-y-4">
                    <div class="flex items-center justify-between">
                        <h3 class="text-base font-bold text-white flex items-center gap-2">
                            <i data-lucide="sliders-horizontal" class="w-5 h-5 text-brand-300"></i> Filtros
                        </h3>
                        <button @click="showMobileFilters = false" class="p-2 rounded-lg hover:bg-white/10">
                            <i data-lucide="x" class="w-5 h-5 text-white/60"></i>
                        </button>
                    </div>

                    <!-- Sort (mobile) -->
                    <div>
                        <label class="text-[11px] text-white/40 uppercase tracking-wider font-semibold mb-1.5 block">Ordenar por</label>
                        <select x-model="filters.sort_by" class="w-full bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 outline-none">
                            <option value="viral_score">Viral Score</option>
                            <option value="views">Views</option>
                            <option value="engagement">Engagement</option>
                            <option value="recent">Recente</option>
                            <option value="outlier">Outlier Ratio</option>
                            <option value="likes">Likes</option>
                        </select>
                    </div>

                    <!-- Categoria (mobile) -->
                    <div>
                        <p class="text-[10px] text-white/30 uppercase tracking-widest font-semibold mb-2">Categoria</p>
                        <div class="flex flex-wrap gap-1">
                            <button @click="filters.category = ''" class="px-2 py-0.5 rounded text-[10px] font-semibold transition"
                                    :class="!filters.category ? 'bg-brand-500/30 text-brand-300' : 'bg-white/5 text-white/50'">Todas</button>
                            <template x-for="cat in categories">
                                <button @click="filters.category = filters.category === cat.id ? '' : cat.id"
                                        class="px-2 py-0.5 rounded text-[10px] font-semibold transition"
                                        :class="filters.category === cat.id ? 'bg-brand-500/30 text-brand-300' : 'bg-white/5 text-white/50'">
                                    <span x-text="cat.icon + ' ' + cat.name"></span>
                                </button>
                            </template>
                        </div>
                    </div>

                    <!-- Estilo (mobile) -->
                    <div>
                        <p class="text-[10px] text-white/30 uppercase tracking-widest font-semibold mb-2">Estilo de Video</p>
                        <div class="flex flex-wrap gap-1">
                            <button @click="filters.style = ''" class="px-2 py-0.5 rounded text-[10px] font-semibold transition"
                                    :class="!filters.style ? 'bg-cyan-500/30 text-cyan-300' : 'bg-white/5 text-white/50'">Todos</button>
                            <template x-for="st in styles">
                                <button @click="filters.style = filters.style === st.id ? '' : st.id"
                                        class="px-2 py-0.5 rounded text-[10px] font-semibold transition"
                                        :class="filters.style === st.id ? 'bg-cyan-500/30 text-cyan-300' : 'bg-white/5 text-white/50'">
                                    <span x-text="st.icon + ' ' + st.name"></span>
                                </button>
                            </template>
                        </div>
                    </div>

                    <!-- Performance (mobile) -->
                    <div>
                        <p class="text-[10px] text-white/30 uppercase tracking-widest font-semibold mb-2">Performance</p>
                        <div class="space-y-2">
                            <div>
                                <label class="text-[11px] text-white/40 mb-1 block">Views minimas</label>
                                <div class="flex flex-wrap gap-1">
                                    <template x-for="v in [50000, 100000, 500000, 1000000]">
                                        <button @click="filters.min_views = filters.min_views === v ? 0 : v"
                                                class="px-2 py-0.5 rounded text-[10px] font-semibold transition"
                                                :class="filters.min_views === v ? 'bg-brand-500/30 text-brand-300' : 'bg-white/5 text-white/50'"
                                                x-text="formatNumber(v)"></button>
                                    </template>
                                </div>
                            </div>
                            <div>
                                <label class="text-[10px] text-white/40 flex justify-between"><span>Viral Score</span><span class="text-brand-300" x-text="filters.min_viral_score || 'Qualquer'"></span></label>
                                <input type="range" x-model.number="filters.min_viral_score" min="0" max="90" step="10" class="w-full accent-brand-500">
                            </div>
                            <div>
                                <label class="text-[10px] text-white/40 block mb-1">Outlier</label>
                                <div class="flex gap-1.5">
                                    <template x-for="o in [2, 5, 10, 20]">
                                        <button @click="filters.min_outlier = filters.min_outlier === o ? 0 : o"
                                                class="px-2 py-0.5 rounded text-[10px] font-semibold transition"
                                                :class="filters.min_outlier === o ? 'bg-orange-500/30 text-orange-300' : 'bg-white/5 text-white/50'"
                                                x-text="o + 'x'"></button>
                                    </template>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Conteudo (mobile) -->
                    <div>
                        <p class="text-[10px] text-white/30 uppercase tracking-widest font-semibold mb-2">Conteudo</p>
                        <div class="space-y-2">
                            <div>
                                <label class="text-[10px] text-white/40 block">Duracao</label>
                                <select x-model="filters.max_duration" @change="
                                    if ($event.target.value === '15') { filters.min_duration = 0; filters.max_duration = 15; }
                                    else if ($event.target.value === '30') { filters.min_duration = 15; filters.max_duration = 30; }
                                    else if ($event.target.value === '60') { filters.min_duration = 30; filters.max_duration = 60; }
                                    else if ($event.target.value === '180') { filters.min_duration = 60; filters.max_duration = 180; }
                                    else { filters.min_duration = 0; filters.max_duration = 0; }
                                " class="w-full bg-white/5 border border-white/10 rounded px-2 py-1 text-[11px] text-white/70 outline-none">
                                    <option value="0">Todas</option>
                                    <option value="15">0-15s</option>
                                    <option value="30">15-30s</option>
                                    <option value="60">30-60s</option>
                                    <option value="180">1-3min</option>
                                </select>
                            </div>
                            <div>
                                <label class="text-[10px] text-white/40 block">Publicado nos ultimos</label>
                                <select x-model.number="filters.published_within_hours" class="w-full bg-white/5 border border-white/10 rounded px-2 py-1 text-[11px] text-white/70 outline-none">
                                    <option value="0">Todos</option>
                                    <option value="24">1 dia</option>
                                    <option value="168">7 dias</option>
                                    <option value="720">30 dias</option>
                                    <option value="2160">90 dias</option>
                                </select>
                            </div>
                            <div>
                                <label class="text-[10px] text-white/40 block mb-1">Tamanho criador</label>
                                <div class="flex flex-wrap gap-1">
                                    <template x-for="tier in ['Nano', 'Micro', 'Mid', 'Macro', 'Mega']">
                                        <button @click="filters.creator_tier = filters.creator_tier === tier.toLowerCase() ? '' : tier.toLowerCase()"
                                                class="px-2 py-0.5 rounded text-[10px] font-semibold transition"
                                                :class="filters.creator_tier === tier.toLowerCase() ? 'bg-brand-500/30 text-brand-300' : 'bg-white/5 text-white/50'"
                                                x-text="tier"></button>
                                    </template>
                                </div>
                            </div>
                            <div class="flex items-center justify-between">
                                <span class="text-[10px] text-white/40">Tem Produto Shop</span>
                                <button @click="filters.has_product = filters.has_product === 'yes' ? '' : 'yes'"
                                        class="relative w-9 h-[18px] rounded-full transition-colors duration-200"
                                        :class="filters.has_product === 'yes' ? 'bg-emerald-500' : 'bg-white/10'">
                                    <span class="absolute top-[2px] left-[2px] w-[14px] h-[14px] rounded-full bg-white transition-transform duration-200"
                                          :class="filters.has_product === 'yes' && 'translate-x-[18px]'"></span>
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="flex gap-2 pt-3 border-t border-white/5 sticky bottom-0 pb-4" style="background: inherit;">
                        <button @click="applyFilters(); showMobileFilters = false" class="flex-1 px-4 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm">
                            Aplicar
                        </button>
                        <button @click="clearFilters()" class="px-4 py-2.5 rounded-xl glass-light text-white/60 font-medium text-sm">
                            Limpar
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Content Area -->
        <div class="flex-1 min-w-0 space-y-4">

            <!-- Toggle filters button (desktop) + Results count -->
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <button x-show="!showFilters" @click="showFilters = true" class="hidden md:flex items-center gap-2 px-3 py-2 rounded-xl glass-light text-white/60 text-sm hover:text-white transition">
                        <i data-lucide="panel-left-open" class="w-4 h-4"></i> Filtros
                    </button>
                    <p class="text-sm text-white/40"><span class="text-white font-bold" x-text="total"></span> videos encontrados</p>
                </div>
            </div>

            <!-- Loading skeleton -->
            <div x-show="loading" class="grid-cards">
                <template x-for="i in 8">
                    <div class="rounded-2xl overflow-hidden">
                        <div class="skeleton aspect-video"></div>
                        <div class="p-3 space-y-2">
                            <div class="skeleton h-4 w-3/4"></div>
                            <div class="skeleton h-3 w-1/2"></div>
                        </div>
                    </div>
                </template>
            </div>

            <!-- Video Grid (9:16 cards with embed player) -->
            <div x-show="!loading" class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
                <template x-for="video in videos" :key="video.id">
                    <div class="glass-card rounded-2xl overflow-hidden group">
                        <!-- Video Area (9:16) -->
                        <div class="relative bg-dark-800 overflow-hidden" style="aspect-ratio: 9/16;">
                            <!-- Playing: TikTok Embed -->
                            <template x-if="playingVideoId === video.id && getTikTokVideoId(video)">
                                <iframe :src="'https://www.tiktok.com/player/v1/' + getTikTokVideoId(video) + '?autoplay=1&loop=1&controls=1&music_info=0&description=0'"
                                    class="w-full h-full" frameborder="0" allow="autoplay; encrypted-media; fullscreen" allowfullscreen style="border:0;"></iframe>
                            </template>
                            <!-- Playing: YouTube Embed -->
                            <template x-if="playingVideoId === video.id && !getTikTokVideoId(video) && getYouTubeVideoId(video)">
                                <iframe :src="'https://www.youtube-nocookie.com/embed/' + getYouTubeVideoId(video) + '?autoplay=1&loop=1&rel=0&modestbranding=1&playsinline=1'"
                                    class="w-full h-full" frameborder="0" allow="autoplay; encrypted-media; fullscreen" allowfullscreen style="border:0;"></iframe>
                            </template>
                            <!-- Not playing: Thumbnail + Play button -->
                            <template x-if="playingVideoId !== video.id || !getEmbeddableVideoId(video)">
                                <div class="relative w-full h-full">
                                    <img :src="'/api/thumbnail/' + video.id" :alt="video.title" class="w-full h-full object-cover" loading="lazy" onerror="this.src=video.thumbnail_url; this.onerror=null">
                                    <!-- Top badges -->
                                    <div class="absolute top-2 left-2 flex gap-1.5">
                                        <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold uppercase" :class="'badge-'+video.platform" x-text="video.platform"></span>
                                        <span class="px-2 py-0.5 text-[10px] font-bold rounded-lg" :class="getViralBadgeClass(video.viral_score)" x-text="video.viral_label"></span>
                                    </div>
                                    <div class="absolute top-2 right-2">
                                        <div class="w-9 h-9 rounded-full flex items-center justify-center text-[10px] font-bold" :style="'background:'+getScoreColor(video.viral_score)+'22; color:'+getScoreColor(video.viral_score)+'; border: 2px solid '+getScoreColor(video.viral_score)+'44'" x-text="Math.round(video.viral_score)"></div>
                                    </div>
                                    <!-- Bottom badges -->
                                    <span x-show="video.is_small_creator" class="absolute bottom-12 left-2 px-2 py-0.5 rounded-lg text-[10px] font-bold bg-brand-500/80 text-white">Criador Pequeno</span>
                                    <div x-show="video.duration" class="absolute bottom-12 right-2 px-2 py-0.5 rounded-md bg-black/70 text-[10px] text-white/80 font-medium" x-text="video.duration_formatted"></div>
                                    <!-- Play button -->
                                    <div class="absolute inset-0 flex items-center justify-center cursor-pointer"
                                         @click="if(getEmbeddableVideoId(video)) { playingVideoId = video.id; $nextTick(() => { if(window.lucide) lucide.createIcons(); }); } else { openPreview(video); }">
                                        <div class="w-14 h-14 rounded-full bg-black/40 backdrop-blur-sm flex items-center justify-center group-hover:scale-110 transition-transform border border-white/20">
                                            <i data-lucide="play" class="w-7 h-7 text-white ml-0.5"></i>
                                        </div>
                                    </div>
                                    <!-- Bottom stats bar -->
                                    <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-2.5 pt-6">
                                        <div class="flex items-center justify-between text-[10px] text-white/80">
                                            <div class="flex items-center gap-2">
                                                <span class="flex items-center gap-0.5"><i data-lucide="eye" class="w-3 h-3"></i><span x-text="video.views_formatted"></span></span>
                                                <span class="flex items-center gap-0.5"><i data-lucide="heart" class="w-3 h-3"></i><span x-text="formatNumber(video.likes)"></span></span>
                                            </div>
                                            <div class="flex gap-1">
                                                <button @click.stop="doDownload(video)" class="p-1 rounded-lg bg-white/20 hover:bg-emerald-500/40 transition" title="Download"><i data-lucide="download" class="w-3 h-3"></i></button>
                                                <a @click.stop :href="video.url" target="_blank" class="p-1 rounded-lg bg-white/20 hover:bg-white/40 transition" title="Abrir original"><i data-lucide="external-link" class="w-3 h-3"></i></a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </div>
                        <!-- Info area -->
                        <div class="p-2.5">
                            <h4 class="text-xs font-semibold text-white/90 line-clamp-2 leading-snug mb-1.5" x-text="video.title?.substring(0,80)"></h4>
                            <div class="flex items-center justify-between mb-1.5">
                                <span class="text-[10px] text-white/40 truncate" x-text="'@'+(video.creator?.username || 'unknown')"></span>
                                <span class="text-[10px] px-1.5 py-0.5 rounded-full font-semibold flex-shrink-0" :style="'background:'+getScoreColor(video.viral_score)+'15; color:'+getScoreColor(video.viral_score)" x-text="video.engagement_rate.toFixed(1)+'%'"></span>
                            </div>
                            <!-- Advanced metrics row -->
                            <div class="flex items-center gap-1 flex-wrap">
                                <span class="px-1.5 py-0.5 rounded text-[9px] font-bold"
                                      :class="video.hook_score >= 50 ? 'bg-purple-500/20 text-purple-400' : video.hook_score >= 30 ? 'bg-purple-500/10 text-purple-400/60' : 'bg-white/5 text-white/30'"
                                      :title="'Hook: ' + video.hook_type">
                                    <span x-text="'🪝 ' + video.hook_score"></span>
                                </span>
                                <span class="px-1.5 py-0.5 rounded text-[9px] font-bold"
                                      :class="video.velocity_score >= 60 ? 'bg-cyan-500/20 text-cyan-400' : video.velocity_score >= 30 ? 'bg-cyan-500/10 text-cyan-400/60' : 'bg-white/5 text-white/30'">
                                    <span x-text="'⚡ ' + Math.round(video.velocity_score)"></span>
                                </span>
                                <span class="px-1.5 py-0.5 rounded text-[9px] font-bold"
                                      :class="video.shareability_score >= 60 ? 'bg-pink-500/20 text-pink-400' : video.shareability_score >= 30 ? 'bg-pink-500/10 text-pink-400/60' : 'bg-white/5 text-white/30'">
                                    <span x-text="'📤 ' + video.shareability_score"></span>
                                </span>
                                <button @click.stop="openAIAnalysis(video)" class="ml-auto p-1 rounded bg-brand-500/20 hover:bg-brand-500/40 transition" title="Analisar com IA">
                                    <i data-lucide="brain" class="w-3 h-3 text-brand-300"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </template>
            </div>

            <!-- Empty state -->
            <div x-show="!loading && videos.length === 0" class="glass-card rounded-2xl p-12 text-center">
                <div class="w-16 h-16 rounded-2xl gradient-brand flex items-center justify-center mx-auto mb-4">
                    <i data-lucide="scan" class="w-8 h-8 text-white"></i>
                </div>
                <h3 class="text-lg font-bold text-white/80 mb-2">Nenhum video encontrado</h3>
                <p class="text-sm text-white/40 mb-6">Ajuste os filtros ou execute um novo scan</p>
                <button @click="runScan()" class="inline-flex items-center gap-2 px-6 py-3 rounded-xl gradient-brand text-white font-semibold text-sm">
                    <i data-lucide="radar" class="w-4 h-4"></i> Executar Scan
                </button>
            </div>

            <!-- Load More -->
            <div x-show="!loading && videos.length > 0 && videos.length < total" class="flex justify-center py-4">
                <button @click="loadMore()" :disabled="loading"
                        class="px-8 py-3 rounded-xl glass-card text-white/70 font-semibold text-sm hover:text-white hover:border-brand-500/30 transition flex items-center gap-2 disabled:opacity-50">
                    <i data-lucide="chevrons-down" class="w-4 h-4"></i>
                    Carregar mais (<span x-text="total - videos.length"></span> restantes)
                </button>
            </div>
        </div>
    </div>

    <!-- Usage Dashboard (Collapsible) -->
    <div class="glass-card rounded-2xl overflow-hidden animate-fade-up-delay" x-data="{ showUsage: false }">
        <button @click="showUsage = !showUsage; if(showUsage) initUsageChart()" class="w-full flex items-center justify-between p-4 hover:bg-white/5 transition">
            <div class="flex items-center gap-3">
                <div class="w-8 h-8 rounded-lg bg-brand-500/20 flex items-center justify-center">
                    <i data-lucide="activity" class="w-4 h-4 text-brand-300"></i>
                </div>
                <h3 class="text-sm font-bold text-white/80">Dashboard de Uso</h3>
            </div>
            <i data-lucide="chevron-down" class="w-5 h-5 text-white/40 transition-transform" :class="showUsage && 'rotate-180'"></i>
        </button>

        <div x-show="showUsage" x-collapse x-cloak class="border-t border-white/5">
            <!-- Usage Stats -->
            <div class="grid grid-cols-2 md:grid-cols-4 gap-3 p-4">
                <div class="glass-light rounded-xl p-3 text-center">
                    <p class="text-2xl font-bold text-brand-300" x-text="usage.credits_today || 0"></p>
                    <p class="text-[10px] text-white/40 mt-1">Creditos Hoje</p>
                </div>
                <div class="glass-light rounded-xl p-3 text-center">
                    <p class="text-2xl font-bold text-cyan-400" x-text="usage.credits_this_week || 0"></p>
                    <p class="text-[10px] text-white/40 mt-1">Esta Semana</p>
                </div>
                <div class="glass-light rounded-xl p-3 text-center">
                    <p class="text-2xl font-bold text-orange-400" x-text="usage.credits_this_month || 0"></p>
                    <p class="text-[10px] text-white/40 mt-1">Este Mes</p>
                </div>
                <div class="glass-light rounded-xl p-3 text-center">
                    <p class="text-2xl font-bold text-emerald-400" x-text="usage.credits_remaining || '--'"></p>
                    <p class="text-[10px] text-white/40 mt-1">Restantes (projecao)</p>
                </div>
            </div>

            <!-- Daily Chart -->
            <div class="px-4 pb-4">
                <div class="glass-light rounded-xl p-4">
                    <h4 class="text-xs font-semibold text-white/50 mb-3">Creditos por Dia</h4>
                    <div class="h-48">
                        <canvas id="usageChart"></canvas>
                    </div>
                </div>
            </div>

            <!-- Recent API Log -->
            <div class="px-4 pb-4">
                <div class="glass-light rounded-xl overflow-hidden">
                    <h4 class="text-xs font-semibold text-white/50 p-3 border-b border-white/5">Log de API Recente</h4>
                    <div class="overflow-x-auto">
                        <table class="w-full text-xs">
                            <thead>
                                <tr class="text-white/30 border-b border-white/5">
                                    <th class="text-left p-2.5 font-semibold">Timestamp</th>
                                    <th class="text-left p-2.5 font-semibold">Endpoint</th>
                                    <th class="text-left p-2.5 font-semibold">Keyword</th>
                                    <th class="text-right p-2.5 font-semibold">Creditos</th>
                                    <th class="text-center p-2.5 font-semibold">Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <template x-for="log in (usage.recent_log || [])" :key="log.timestamp">
                                    <tr class="border-b border-white/5 hover:bg-white/5 transition">
                                        <td class="p-2.5 text-white/50" x-text="log.timestamp"></td>
                                        <td class="p-2.5 text-white/70 font-medium" x-text="log.endpoint"></td>
                                        <td class="p-2.5 text-white/50" x-text="log.keyword || '--'"></td>
                                        <td class="p-2.5 text-right text-orange-400 font-semibold" x-text="log.credits"></td>
                                        <td class="p-2.5 text-center">
                                            <span class="px-1.5 py-0.5 rounded-full text-[10px] font-bold"
                                                  :class="log.status === 'success' ? 'bg-emerald-500/20 text-emerald-400' : 'bg-red-500/20 text-red-400'"
                                                  x-text="log.status"></span>
                                        </td>
                                    </tr>
                                </template>
                                <tr x-show="!usage.recent_log || usage.recent_log.length === 0">
                                    <td colspan="5" class="p-4 text-center text-white/30">Nenhum log disponivel</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- AI Analysis Modal -->
    <div x-show="aiModal.open" x-cloak
         class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm"
         @click.self="aiModal.open = false" @keydown.escape.window="aiModal.open = false">
        <div class="glass-card rounded-2xl w-full max-w-2xl max-h-[85vh] overflow-y-auto" @click.stop>
            <!-- Header -->
            <div class="sticky top-0 z-10 bg-dark-900/95 backdrop-blur p-5 border-b border-white/10 flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-xl bg-brand-500/20 flex items-center justify-center">
                        <i data-lucide="brain" class="w-5 h-5 text-brand-300"></i>
                    </div>
                    <div>
                        <h3 class="font-bold text-white">Analise com IA</h3>
                        <p class="text-xs text-white/40" x-text="aiModal.video?.title?.substring(0,60)"></p>
                    </div>
                </div>
                <button @click="aiModal.open = false" class="p-2 rounded-lg hover:bg-white/10 transition">
                    <i data-lucide="x" class="w-5 h-5 text-white/50"></i>
                </button>
            </div>

            <!-- Loading -->
            <div x-show="aiModal.loading" class="p-8 text-center">
                <div class="w-12 h-12 rounded-full border-2 border-brand-500 border-t-transparent animate-spin mx-auto mb-4"></div>
                <p class="text-white/60">Analisando com Qwen 2.5 3B...</p>
                <p class="text-xs text-white/30 mt-1">IA local, 100% gratuito</p>
            </div>

            <!-- Results -->
            <div x-show="!aiModal.loading && aiModal.data" class="p-5 space-y-4">
                <!-- Scores Grid -->
                <div class="grid grid-cols-3 md:grid-cols-6 gap-2">
                    <div class="glass-light rounded-xl p-3 text-center">
                        <p class="text-lg font-bold" :class="(aiModal.data?.hook_score?.score||0) >= 50 ? 'text-purple-400' : 'text-white/50'" x-text="aiModal.data?.hook_score?.score || 0"></p>
                        <p class="text-[9px] text-white/40 mt-0.5">Hook</p>
                    </div>
                    <div class="glass-light rounded-xl p-3 text-center">
                        <p class="text-lg font-bold" :class="(aiModal.data?.shareability?.score||0) >= 50 ? 'text-pink-400' : 'text-white/50'" x-text="aiModal.data?.shareability?.score || 0"></p>
                        <p class="text-[9px] text-white/40 mt-0.5">Share</p>
                    </div>
                    <div class="glass-light rounded-xl p-3 text-center">
                        <p class="text-lg font-bold" :class="(aiModal.data?.engagement_velocity?.velocity_score||0) >= 50 ? 'text-cyan-400' : 'text-white/50'" x-text="Math.round(aiModal.data?.engagement_velocity?.velocity_score || 0)"></p>
                        <p class="text-[9px] text-white/40 mt-0.5">Velocity</p>
                    </div>
                    <div class="glass-light rounded-xl p-3 text-center">
                        <p class="text-lg font-bold" :class="(aiModal.data?.completion_rate?.predicted_rate||0) >= 50 ? 'text-emerald-400' : 'text-white/50'" x-text="aiModal.data?.completion_rate?.predicted_rate || 0"></p>
                        <p class="text-[9px] text-white/40 mt-0.5">Retencao %</p>
                    </div>
                    <div class="glass-light rounded-xl p-3 text-center">
                        <p class="text-lg font-bold" :class="(aiModal.data?.monetization_potential?.score||0) >= 50 ? 'text-yellow-400' : 'text-white/50'" x-text="aiModal.data?.monetization_potential?.score || 0"></p>
                        <p class="text-[9px] text-white/40 mt-0.5">Monetiz.</p>
                    </div>
                    <div class="glass-light rounded-xl p-3 text-center" x-show="aiModal.data?.blue_ocean">
                        <p class="text-lg font-bold" :class="(aiModal.data?.blue_ocean?.score||0) >= 50 ? 'text-blue-400' : 'text-white/50'" x-text="Math.round(aiModal.data?.blue_ocean?.score || 0)"></p>
                        <p class="text-[9px] text-white/40 mt-0.5">Blue Ocean</p>
                    </div>
                </div>

                <!-- Hook Analysis -->
                <div class="glass-light rounded-xl p-4" x-show="aiModal.data?.hook_score">
                    <h4 class="text-sm font-bold text-purple-400 mb-2 flex items-center gap-2">
                        <span>Hook Analysis</span>
                        <span class="text-[10px] px-2 py-0.5 rounded-full bg-purple-500/20" x-text="aiModal.data?.hook_score?.hook_type"></span>
                    </h4>
                    <div class="flex flex-wrap gap-1 mb-2">
                        <template x-for="type in (aiModal.data?.hook_score?.hook_types || [])" :key="type">
                            <span class="px-2 py-0.5 rounded-full text-[10px] bg-purple-500/10 text-purple-300" x-text="type"></span>
                        </template>
                        <template x-for="cta in (aiModal.data?.hook_score?.ctas_found || [])" :key="cta">
                            <span class="px-2 py-0.5 rounded-full text-[10px] bg-emerald-500/10 text-emerald-300" x-text="'CTA: '+cta"></span>
                        </template>
                    </div>
                    <template x-if="aiModal.data?.hook_score?.tips?.length">
                        <ul class="space-y-1">
                            <template x-for="tip in aiModal.data.hook_score.tips" :key="tip">
                                <li class="text-[11px] text-white/50 flex items-start gap-1.5">
                                    <span class="text-yellow-400 mt-0.5">*</span>
                                    <span x-text="tip"></span>
                                </li>
                            </template>
                        </ul>
                    </template>
                </div>

                <!-- Script Analysis (AI) -->
                <div class="glass-light rounded-xl p-4" x-show="aiModal.data?.script_analysis?.success">
                    <h4 class="text-sm font-bold text-brand-300 mb-3">Analise de Script (IA)</h4>
                    <div class="space-y-2 text-[11px]">
                        <div x-show="aiModal.data?.script_analysis?.hook">
                            <span class="text-white/40">Hook:</span>
                            <span class="text-white/80 ml-1" x-text="aiModal.data?.script_analysis?.hook"></span>
                        </div>
                        <div x-show="aiModal.data?.script_analysis?.problem">
                            <span class="text-white/40">Problema:</span>
                            <span class="text-white/80 ml-1" x-text="aiModal.data?.script_analysis?.problem"></span>
                        </div>
                        <div x-show="aiModal.data?.script_analysis?.solution">
                            <span class="text-white/40">Solucao:</span>
                            <span class="text-white/80 ml-1" x-text="aiModal.data?.script_analysis?.solution"></span>
                        </div>
                        <div x-show="aiModal.data?.script_analysis?.cta">
                            <span class="text-white/40">CTA:</span>
                            <span class="text-white/80 ml-1" x-text="aiModal.data?.script_analysis?.cta"></span>
                        </div>
                        <div x-show="aiModal.data?.script_analysis?.emotional_arc">
                            <span class="text-white/40">Emocao:</span>
                            <span class="text-white/80 ml-1" x-text="aiModal.data?.script_analysis?.emotional_arc"></span>
                        </div>
                    </div>
                    <!-- Strengths & Weaknesses -->
                    <div class="grid grid-cols-2 gap-3 mt-3">
                        <div x-show="aiModal.data?.script_analysis?.strengths?.length">
                            <p class="text-[10px] text-emerald-400 font-bold mb-1">Pontos Fortes</p>
                            <template x-for="s in (aiModal.data?.script_analysis?.strengths || [])" :key="s">
                                <p class="text-[10px] text-white/50" x-text="'+ ' + s"></p>
                            </template>
                        </div>
                        <div x-show="aiModal.data?.script_analysis?.weaknesses?.length">
                            <p class="text-[10px] text-red-400 font-bold mb-1">Pontos Fracos</p>
                            <template x-for="w in (aiModal.data?.script_analysis?.weaknesses || [])" :key="w">
                                <p class="text-[10px] text-white/50" x-text="'- ' + w"></p>
                            </template>
                        </div>
                    </div>
                </div>

                <!-- AI Suggestions -->
                <div class="glass-light rounded-xl p-4" x-show="aiModal.data?.ai_suggestions?.length">
                    <h4 class="text-sm font-bold text-yellow-400 mb-2">Sugestoes de Melhoria (IA)</h4>
                    <ul class="space-y-1.5">
                        <template x-for="(sug, i) in (aiModal.data?.ai_suggestions || [])" :key="i">
                            <li class="text-[11px] text-white/60 flex items-start gap-2">
                                <span class="text-yellow-400 font-bold" x-text="(i+1)+'.'"></span>
                                <span x-text="sug"></span>
                            </li>
                        </template>
                    </ul>
                </div>

                <!-- Velocity, Shareability, Pacing Details -->
                <div class="grid grid-cols-3 gap-3">
                    <div class="glass-light rounded-xl p-3">
                        <h5 class="text-[10px] font-bold text-cyan-400 mb-1.5">Velocidade</h5>
                        <p class="text-xs text-white/60"><span class="text-white/80 font-bold" x-text="aiModal.data?.engagement_velocity?.label"></span></p>
                        <p class="text-[10px] text-white/40 mt-1" x-text="Math.round(aiModal.data?.engagement_velocity?.views_per_hour || 0).toLocaleString() + ' views/hora'"></p>
                        <p class="text-[10px] text-white/40" x-text="Math.round(aiModal.data?.engagement_velocity?.engagement_per_hour || 0).toLocaleString() + ' eng/hora'"></p>
                    </div>
                    <div class="glass-light rounded-xl p-3">
                        <h5 class="text-[10px] font-bold text-pink-400 mb-1.5">Shareability</h5>
                        <p class="text-xs text-white/60"><span class="text-white/80 font-bold" x-text="aiModal.data?.shareability?.label"></span></p>
                        <p class="text-[10px] text-white/40 mt-1" x-text="'Share ratio: ' + (aiModal.data?.shareability?.share_ratio || 0) + '%'"></p>
                        <template x-for="f in (aiModal.data?.shareability?.factors || [])" :key="f">
                            <p class="text-[10px] text-white/30" x-text="'* ' + f"></p>
                        </template>
                    </div>
                    <div class="glass-light rounded-xl p-3" x-show="aiModal.data?.pacing">
                        <h5 class="text-[10px] font-bold text-orange-400 mb-1.5">Pacing</h5>
                        <p class="text-xs text-white/60"><span class="text-white/80 font-bold" x-text="aiModal.data?.pacing?.label"></span></p>
                        <p class="text-[10px] text-white/40 mt-1" x-text="aiModal.data?.pacing?.duration_advice"></p>
                        <p class="text-[10px] text-white/30 mt-0.5" x-text="aiModal.data?.pacing?.interrupt_tip"></p>
                    </div>
                </div>

                <!-- Transcription -->
                <div class="glass-light rounded-xl p-4">
                    <div class="flex items-center justify-between mb-2">
                        <h4 class="text-sm font-bold text-emerald-400 flex items-center gap-2">
                            <i data-lucide="mic" class="w-4 h-4"></i> Transcricao
                            <span class="text-[10px] px-2 py-0.5 rounded-full bg-emerald-500/20 font-normal">Whisper local - FREE</span>
                        </h4>
                        <button @click="transcribeVideo(aiModal.video?.id)" x-show="!aiModal.data?.transcription"
                                class="px-3 py-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-bold transition flex items-center gap-1">
                            <i data-lucide="play" class="w-3 h-3"></i> Transcrever
                        </button>
                    </div>
                    <div x-show="aiModal.data?.transcription?.success">
                        <p class="text-[10px] text-white/40 mb-1">
                            <span x-text="(aiModal.data?.transcription?.word_count || 0) + ' palavras'"></span> |
                            <span x-text="'Idioma: ' + (aiModal.data?.transcription?.language || '?')"></span> |
                            <span x-text="(aiModal.data?.transcription?.duration || 0) + 's audio'"></span>
                        </p>
                        <p class="text-[11px] text-white/70 max-h-32 overflow-y-auto leading-relaxed" x-text="aiModal.data?.transcription?.transcript_text"></p>
                    </div>
                    <p x-show="!aiModal.data?.transcription" class="text-[10px] text-white/30">Clique em "Transcrever" para extrair o audio do video e transcrever com IA local</p>
                </div>

                <!-- AI Hook Analysis (transcript-based) -->
                <div class="glass-light rounded-xl p-4" x-show="aiModal.hookAI">
                    <h4 class="text-sm font-bold text-violet-400 mb-3 flex items-center gap-2">
                        <i data-lucide="sparkles" class="w-4 h-4"></i> AI Hook Scoring
                        <span class="text-[10px] px-2 py-0.5 rounded-full bg-violet-500/20 font-normal" x-text="'Score: ' + (aiModal.hookAI?.score || 0) + '/100'"></span>
                    </h4>
                    <div class="space-y-2 text-[11px]">
                        <div class="flex items-center gap-3">
                            <span class="text-white/40">Tipo:</span>
                            <span class="px-2 py-0.5 rounded-full bg-violet-500/10 text-violet-300 text-[10px]" x-text="aiModal.hookAI?.hook_type || '-'"></span>
                            <span class="text-white/40">Atencao:</span>
                            <span class="text-white/70" x-text="aiModal.hookAI?.attention_grab || '-'"></span>
                            <span class="text-white/40">Retencao:</span>
                            <span class="text-white/70" x-text="aiModal.hookAI?.retention_prediction || '-'"></span>
                        </div>
                        <div x-show="aiModal.hookAI?.emotional_trigger">
                            <span class="text-white/40">Emocao ativada:</span>
                            <span class="text-white/70 ml-1" x-text="aiModal.hookAI?.emotional_trigger"></span>
                        </div>
                        <div x-show="aiModal.hookAI?.reasoning">
                            <span class="text-white/40">Analise:</span>
                            <p class="text-white/60 mt-1" x-text="aiModal.hookAI?.reasoning"></p>
                        </div>
                        <div x-show="aiModal.hookAI?.improved_hook" class="bg-violet-500/10 rounded-lg p-2 mt-2">
                            <span class="text-violet-300 text-[10px] font-bold">Hook melhorado:</span>
                            <p class="text-white/80 mt-0.5" x-text="aiModal.hookAI?.improved_hook"></p>
                        </div>
                        <template x-if="aiModal.hookAI?.tips?.length">
                            <div class="mt-2">
                                <template x-for="tip in aiModal.hookAI.tips" :key="tip">
                                    <p class="text-[10px] text-white/40"><span class="text-violet-400">*</span> <span x-text="tip"></span></p>
                                </template>
                            </div>
                        </template>
                    </div>
                </div>

                <!-- Save/Share Algo Boost -->
                <div class="glass-light rounded-xl p-4" x-show="aiModal.data?.save_share_ratio">
                    <h4 class="text-sm font-bold text-teal-400 mb-3 flex items-center gap-2">
                        <i data-lucide="bookmark" class="w-4 h-4"></i> Save/Share & Boost Algoritmico
                        <span class="text-[10px] px-2 py-0.5 rounded-full bg-teal-500/20 font-normal" x-text="'Boost: ' + (aiModal.data?.save_share_ratio?.algo_boost_score || 0) + '/100'"></span>
                    </h4>
                    <div class="grid grid-cols-4 gap-2 mb-3">
                        <div class="text-center">
                            <p class="text-sm font-bold text-teal-300" x-text="(aiModal.data?.save_share_ratio?.save_ratio || 0) + '%'"></p>
                            <p class="text-[9px] text-white/40">Saves</p>
                        </div>
                        <div class="text-center">
                            <p class="text-sm font-bold text-pink-300" x-text="(aiModal.data?.save_share_ratio?.share_ratio || 0) + '%'"></p>
                            <p class="text-[9px] text-white/40">Shares</p>
                        </div>
                        <div class="text-center">
                            <p class="text-sm font-bold text-red-300" x-text="(aiModal.data?.save_share_ratio?.like_ratio || 0) + '%'"></p>
                            <p class="text-[9px] text-white/40">Likes</p>
                        </div>
                        <div class="text-center">
                            <p class="text-sm font-bold text-blue-300" x-text="(aiModal.data?.save_share_ratio?.comment_ratio || 0) + '%'"></p>
                            <p class="text-[9px] text-white/40">Comments</p>
                        </div>
                    </div>
                    <template x-if="aiModal.data?.save_share_ratio?.boost_signals?.length">
                        <div>
                            <p class="text-[10px] text-white/40 font-bold mb-1">Sinais de boost:</p>
                            <template x-for="signal in aiModal.data.save_share_ratio.boost_signals" :key="signal">
                                <span class="inline-block px-2 py-0.5 rounded-full text-[9px] bg-teal-500/10 text-teal-300 mr-1 mb-1" x-text="signal"></span>
                            </template>
                        </div>
                    </template>
                </div>

                <!-- Transcrever + Analisar IA completo -->
                <div class="p-4" x-show="!aiModal.hookAI && aiModal.data?.transcription?.success">
                    <button @click="analyzeHookAI(aiModal.video?.id, aiModal.data?.transcription?.transcript_text)"
                            class="w-full py-3 rounded-xl bg-gradient-to-r from-violet-600 to-brand-600 hover:from-violet-500 hover:to-brand-500 text-white font-bold text-sm transition flex items-center justify-center gap-2"
                            :disabled="aiModal.hookLoading">
                        <template x-if="!aiModal.hookLoading">
                            <span class="flex items-center gap-2"><i data-lucide="sparkles" class="w-4 h-4"></i> Analisar Hook com IA</span>
                        </template>
                        <template x-if="aiModal.hookLoading">
                            <span class="flex items-center gap-2"><div class="w-4 h-4 rounded-full border-2 border-white border-t-transparent animate-spin"></div> Analisando...</span>
                        </template>
                    </button>
                </div>

                <!-- Full pipeline button: Transcrever + Analisar -->
                <div class="p-4" x-show="!aiModal.data?.transcription?.success && !aiModal.hookAI">
                    <button @click="fullTranscribeAnalyze(aiModal.video?.id)"
                            class="w-full py-3 rounded-xl bg-gradient-to-r from-emerald-600 to-violet-600 hover:from-emerald-500 hover:to-violet-500 text-white font-bold text-sm transition flex items-center justify-center gap-2"
                            :disabled="aiModal.fullPipelineLoading">
                        <template x-if="!aiModal.fullPipelineLoading">
                            <span class="flex items-center gap-2"><i data-lucide="wand-2" class="w-4 h-4"></i> Transcrever + Analisar IA</span>
                        </template>
                        <template x-if="aiModal.fullPipelineLoading">
                            <span class="flex items-center gap-2"><div class="w-4 h-4 rounded-full border-2 border-white border-t-transparent animate-spin"></div> Processando pipeline...</span>
                        </template>
                    </button>
                    <p class="text-[10px] text-white/30 text-center mt-1">Whisper (transcricao) + Qwen 2.5 (analise hook) - 100% local e gratuito</p>
                </div>
            </div>
        </div>
    </div>

</div>
{% endblock %}

{% block scripts %}
<script>
let usageChartInstance = null;

function scannerApp() {
    return {
        videos: [],
        total: 0,
        loading: false,
        playingVideoId: null,
        scanning: false,
        showFilters: true,
        showMobileFilters: false,
        showScanPanel: false,
        offset: 0,
        limit: 24,

        // Scan config
        scanKeywords: '',
        scanHashtag: '',
        scanSoundUrl: '',
        scanPlatforms: { tiktok: true, youtube: true, instagram: false },
        scanMaxResults: 30,
        scanResult: '',

        // Scanner status
        status: {},
        usage: {},

        // Categories and styles for filtering
        categories: [
            { id: 'ai_construcao', name: 'IA Construcao', icon: '🤖🏗️' },
            { id: 'construcao', name: 'Construcao', icon: '🏗️' },
            { id: 'arquitetura', name: 'Arquitetura', icon: '🏛️' },
            { id: 'decoracao', name: 'Decoracao', icon: '🎨' },
            { id: 'diy_reforma', name: 'DIY/Reforma', icon: '🔨' },
            { id: 'lifestyle', name: 'Lifestyle', icon: '✨' },
            { id: 'tech', name: 'Tech', icon: '📱' },
            { id: 'receitas', name: 'Receitas', icon: '🍳' },
            { id: 'fitness', name: 'Fitness', icon: '💪' },
            { id: 'moda', name: 'Moda', icon: '👗' },
            { id: 'beleza', name: 'Beleza', icon: '💄' },
            { id: 'humor', name: 'Humor', icon: '😂' },
            { id: 'educacao', name: 'Educacao', icon: '📚' },
            { id: 'financas', name: 'Financas', icon: '💰' },
            { id: 'pets', name: 'Pets', icon: '🐾' },
            { id: 'viagem', name: 'Viagem', icon: '✈️' },
            { id: 'automotivo', name: 'Automotivo', icon: '🚗' },
            { id: 'jardinagem', name: 'Jardinagem', icon: '🌱' },
            { id: 'games', name: 'Games', icon: '🎮' },
            { id: 'musica', name: 'Musica', icon: '🎵' },
            { id: 'arte', name: 'Arte', icon: '🎨' },
            { id: 'espiritualidade', name: 'Espiritualidade', icon: '🧘' },
            { id: 'maternidade', name: 'Maternidade', icon: '👶' },
            { id: 'empreendedorismo', name: 'Empreendedorismo', icon: '🚀' },
            { id: 'sustentabilidade', name: 'Sustentabilidade', icon: '♻️' },
            { id: 'ciencia', name: 'Ciencia', icon: '🔬' },
            { id: 'fotografia', name: 'Fotografia', icon: '📷' },
            { id: 'livros', name: 'Livros', icon: '📖' },
            { id: 'relacionamentos', name: 'Relacionamentos', icon: '💑' },
            { id: 'saude_mental', name: 'Saude Mental', icon: '🧠' },
        ],
        styles: [
            { id: 'ai_generated', name: 'Gerado por IA', icon: '🤖' },
            { id: 'timelapse', name: 'Timelapse', icon: '⏩' },
            { id: 'tutorial', name: 'Tutorial', icon: '📋' },
            { id: 'before_after', name: 'Antes/Depois', icon: '🔄' },
            { id: 'review', name: 'Review', icon: '⭐' },
            { id: 'unboxing', name: 'Unboxing', icon: '📦' },
            { id: 'vlog', name: 'Vlog', icon: '🎥' },
            { id: 'satisfying', name: 'Satisfying', icon: '🤤' },
            { id: 'behind_scenes', name: 'Bastidores', icon: '🎬' },
            { id: 'storytelling', name: 'Storytelling', icon: '📖' },
            { id: 'pov', name: 'POV', icon: '👁️' },
        ],

        // Filter values
        filters: {
            min_views: 0,
            max_views: 0,
            min_likes: 0,
            min_comments: 0,
            min_shares: 0,
            min_engagement: 0,
            max_engagement: 0,
            min_viral_score: 0,
            max_viral_score: 0,
            viral_level: '',
            min_outlier: 0,
            min_replicability: 0,
            min_duration: 0,
            max_duration: 0,
            has_product: '',
            hashtag_contains: '',
            description_contains: '',
            creator_tier: '',
            min_views_per_follower: 0,
            small_creator_viral: false,
            published_within_hours: 0,
            min_velocity: 0,
            sort_by: 'viral_score',
            platform: 'tiktok',
            language: localStorage.getItem('globalLang') || '',
            category: '',
            style: '',
        },

        // AI Analysis Modal
        aiModal: { open: false, loading: false, data: null, video: null, hookAI: null, hookLoading: false, fullPipelineLoading: false },

        // Quick presets
        activePreset: '',
        presets: {
            mega_viral: { min_viral_score: 90, sort_by: 'viral_score' },
            shop_viral: { has_product: 'yes', min_views: 100000, sort_by: 'views' },
            small_creator: { small_creator_viral: true, sort_by: 'outlier' },
            trending_now: { published_within_hours: 24, min_views: 50000, sort_by: 'views' },
            replicable: { min_replicability: 60, sort_by: 'replicability' },
            emerging: { published_within_hours: 24, min_views: 10000, sort_by: 'views' },
        },

        init() {
            this.loadVideos();
            this.loadStatus();
            setInterval(() => this.loadStatus(), 30000);
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            // Listen for global language changes
            window.addEventListener('lang-changed', e => {
                this.filters.language = e.detail;
                this.applyFilters();
            });
        },

        openPreview(video) {
            // Set the preview modal on the parent viralApp via custom event
            window.dispatchEvent(new CustomEvent('preview-video', { detail: video }));
        },

        async doDownload(video) {
            if (!video?.url) return;
            showToast('Baixando video... aguarde', 'info');
            try {
                const params = new URLSearchParams({ url: video.url, quality: 'best' });
                const r = await fetch('/api/download/url?' + params, { method: 'POST' });
                const d = await r.json();
                if (d.error) { showToast('Erro: ' + d.error, 'error'); }
                else {
                    showToast('Download concluido! Baixando para seu computador...', 'success');
                    // Trigger browser download
                    const a = document.createElement('a');
                    a.href = '/api/downloads/file?path=' + encodeURIComponent(d.path);
                    a.download = d.filename || 'video.mp4';
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                }
            } catch(e) { showToast('Erro no download', 'error'); }
        },

        async loadVideos() {
            this.loading = true;
            const params = new URLSearchParams();
            Object.entries(this.filters).forEach(([k, v]) => {
                if (v !== 0 && v !== '' && v !== false) params.append(k, v);
            });
            params.append('limit', this.limit);
            params.append('offset', this.offset);

            try {
                const res = await fetch('/api/scanner/videos?' + params);
                const data = await res.json();
                if (this.offset === 0) {
                    this.videos = (data.videos || []).map(v => ({...v, showEmbed: false}));
                } else {
                    this.videos = [...this.videos, ...(data.videos || []).map(v => ({...v, showEmbed: false}))];
                }
                this.total = data.total || 0;
            } catch (e) {
                console.error(e);
                showToast('Erro ao carregar videos', 'error');
            }
            this.loading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async loadMore() {
            this.offset += this.limit;
            await this.loadVideos();
        },

        async loadStatus() {
            try {
                const res = await fetch('/api/scanner/status');
                const data = await res.json();
                this.status = data.scanner || {};
                this.usage = data.usage || {};
            } catch(e) {}
        },

        applyFilters() {
            this.offset = 0;
            this.activePreset = '';
            this.loadVideos();
        },

        clearFilters() {
            this.filters = {
                min_views: 0, max_views: 0, min_likes: 0, min_comments: 0,
                min_shares: 0, min_engagement: 0, max_engagement: 0,
                min_viral_score: 0, max_viral_score: 0, viral_level: '',
                min_outlier: 0, min_replicability: 0, min_duration: 0,
                max_duration: 0, has_product: '', hashtag_contains: '',
                description_contains: '', creator_tier: '', min_views_per_follower: 0,
                small_creator_viral: false, published_within_hours: 0,
                min_velocity: 0, sort_by: 'viral_score', platform: 'tiktok',
                language: localStorage.getItem('globalLang') || '',
                category: '', style: '',
            };
            this.activePreset = '';
            this.offset = 0;
            this.loadVideos();
        },

        applyPreset(name) {
            this.clearFilters();
            this.activePreset = name;
            Object.assign(this.filters, this.presets[name]);
            this.offset = 0;
            this.loadVideos();
        },

        async runScan() {
            this.scanning = true;
            this.scanResult = '';
            try {
                const params = new URLSearchParams();
                if (this.scanKeywords.trim()) {
                    params.set('keywords', this.scanKeywords.trim());
                }
                // Build platform list
                const platforms = Object.entries(this.scanPlatforms)
                    .filter(([k, v]) => v).map(([k]) => k).join(',');
                if (platforms) params.set('platforms', platforms);
                params.set('max_results', this.scanMaxResults);

                const res = await fetch('/api/scanner/scan?' + params, {method: 'POST'});
                const data = await res.json();
                if (data.error) {
                    showToast(data.error, 'error');
                    this.scanResult = 'Erro: ' + data.error;
                } else {
                    const msg = (data.total_videos_saved || 0) + ' novos videos encontrados, ' +
                                (data.total_credits_used || 0) + ' creditos usados';
                    showToast('Scan concluido! ' + msg, 'success');
                    this.scanResult = msg;
                    this.offset = 0;
                    this.loadVideos();
                    this.loadStatus();
                }
            } catch(e) {
                showToast('Erro ao executar scan', 'error');
            }
            this.scanning = false;
        },

        async runCreativeCenter() {
            this.scanning = true;
            try {
                const res = await fetch('/api/scanner/scan-creative-center', {method: 'POST'});
                const data = await res.json();
                if (data.error) {
                    showToast(data.error, 'error');
                } else {
                    showToast('Creative Center scan concluido! ' + (data.new_videos || 0) + ' novos videos', 'success');
                    this.loadVideos();
                    this.loadStatus();
                }
            } catch(e) {
                showToast('Erro ao executar scan', 'error');
            }
            this.scanning = false;
        },

        async emergencyPause() {
            if (!confirm('Pausar todos os jobs do scanner?')) return;
            try {
                await fetch('/api/scanner/pause', {method: 'POST'});
                showToast('Scanner pausado com sucesso', 'warning');
                this.loadStatus();
            } catch(e) {
                showToast('Erro ao pausar scanner', 'error');
            }
        },

        formatNumber(n) {
            if (!n) return '0';
            if (n >= 1000000) return (n/1000000).toFixed(1) + 'M';
            if (n >= 1000) return (n/1000).toFixed(1) + 'K';
            return n.toString();
        },

        getScoreColor(score) {
            if (score >= 90) return '#ef4444';
            if (score >= 75) return '#f97316';
            if (score >= 60) return '#eab308';
            if (score >= 40) return '#3b82f6';
            if (score >= 20) return '#22c55e';
            return '#6b7280';
        },

        getViralBadgeClass(score) {
            if (score >= 90) return 'bg-red-500/80 text-white animate-pulse';
            if (score >= 75) return 'bg-orange-500/80 text-white';
            if (score >= 60) return 'bg-yellow-500/80 text-black';
            if (score >= 40) return 'bg-blue-500/80 text-white';
            if (score >= 20) return 'bg-green-500/80 text-white';
            return 'bg-gray-500/80 text-white';
        },

        async openAIAnalysis(video) {
            this.aiModal = { open: true, loading: true, data: null, video: video };
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            try {
                const res = await fetch('/api/analysis/video/' + video.id);
                const data = await res.json();
                this.aiModal.data = data;
            } catch(e) {
                showToast('Erro na analise IA', 'error');
                console.error(e);
            }
            this.aiModal.loading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async runHashtagScan() {
            if (!this.scanHashtag.trim()) { showToast('Digite uma hashtag', 'warning'); return; }
            this.scanning = true;
            this.scanResult = '';
            try {
                const params = new URLSearchParams({ hashtag: this.scanHashtag.trim(), max_results: this.scanMaxResults });
                const res = await fetch('/api/scanner/scan-hashtag?' + params, { method: 'POST' });
                const data = await res.json();
                if (data.error) { showToast(data.error, 'error'); }
                else {
                    showToast(`Hashtag #${data.hashtag}: ${data.videos_saved} videos salvos`, 'success');
                    this.scanResult = `#${data.hashtag}: ${data.videos_found} encontrados, ${data.videos_saved} salvos`;
                    this.offset = 0; this.loadVideos(); this.loadStatus();
                }
            } catch(e) { showToast('Erro ao escanear hashtag', 'error'); }
            this.scanning = false;
        },

        async runSoundScan() {
            if (!this.scanSoundUrl.trim()) { showToast('Digite a URL do som', 'warning'); return; }
            this.scanning = true;
            this.scanResult = '';
            try {
                const params = new URLSearchParams({ sound_url: this.scanSoundUrl.trim(), max_results: this.scanMaxResults });
                const res = await fetch('/api/scanner/scan-sound?' + params, { method: 'POST' });
                const data = await res.json();
                if (data.error) { showToast(data.error, 'error'); }
                else {
                    showToast(`Som: ${data.videos_saved} videos salvos`, 'success');
                    this.scanResult = `Som: ${data.videos_found} encontrados, ${data.videos_saved} salvos`;
                    this.offset = 0; this.loadVideos(); this.loadStatus();
                }
            } catch(e) { showToast('Erro ao escanear som', 'error'); }
            this.scanning = false;
        },

        async transcribeVideo(videoId) {
            showToast('Transcrevendo audio com Whisper (local)...', 'info');
            try {
                const res = await fetch('/api/scanner/transcribe/' + videoId, { method: 'POST' });
                const data = await res.json();
                if (data.success) {
                    this.aiModal.data.transcription = data;
                    showToast(`Transcricao completa: ${data.word_count} palavras (${data.language})`, 'success');
                } else {
                    showToast('Erro: ' + (data.error || 'Falha na transcricao'), 'error');
                }
            } catch(e) { showToast('Erro na transcricao', 'error'); }
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async analyzeHookAI(videoId, transcriptText) {
            this.aiModal.hookLoading = true;
            try {
                const body = new URLSearchParams();
                if (videoId) body.append('video_id', videoId);
                if (transcriptText) body.append('transcript_text', transcriptText);
                const res = await fetch('/api/analysis/hook-ai', { method: 'POST', body });
                const data = await res.json();
                if (data.success) {
                    this.aiModal.hookAI = data;
                    showToast('Hook AI analisado! Score: ' + (data.score || 0), 'success');
                } else {
                    showToast('Erro: ' + (data.error || 'Falha na analise hook'), 'error');
                }
            } catch(e) { showToast('Erro na analise hook AI', 'error'); }
            this.aiModal.hookLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async fullTranscribeAnalyze(videoId) {
            if (!videoId) return showToast('Video ID necessario', 'error');
            this.aiModal.fullPipelineLoading = true;
            try {
                // Step 1: Transcribe
                showToast('Passo 1/2: Transcrevendo com Whisper...', 'info');
                const tRes = await fetch('/api/scanner/transcribe/' + videoId, { method: 'POST' });
                const tData = await tRes.json();
                if (!tData.success) {
                    showToast('Erro na transcricao: ' + (tData.error || ''), 'error');
                    this.aiModal.fullPipelineLoading = false;
                    return;
                }
                this.aiModal.data.transcription = tData;

                // Step 2: AI Hook Analysis
                showToast('Passo 2/2: Analisando hook com IA...', 'info');
                const body = new URLSearchParams();
                body.append('video_id', String(videoId));
                body.append('transcript_text', tData.transcript_text || '');
                const hRes = await fetch('/api/analysis/hook-ai', { method: 'POST', body });
                const hData = await hRes.json();
                if (hData.success) {
                    this.aiModal.hookAI = hData;
                    showToast('Pipeline completo! Hook Score: ' + (hData.score || 0), 'success');
                } else {
                    showToast('Hook analisado parcialmente', 'warning');
                }
            } catch(e) { showToast('Erro no pipeline IA', 'error'); }
            this.aiModal.fullPipelineLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },
    };
}

function initUsageChart() {
    const ctx = document.getElementById('usageChart');
    if (!ctx) return;

    if (usageChartInstance) {
        usageChartInstance.destroy();
    }

    // Get data from Alpine component
    const app = document.querySelector('[x-data]').__x.$data || {};
    const dailyData = (app.usage && app.usage.daily_chart) || {};
    const labels = Object.keys(dailyData);
    const values = Object.values(dailyData);

    usageChartInstance = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels.length > 0 ? labels : ['Sem dados'],
            datasets: [{
                label: 'Creditos',
                data: values.length > 0 ? values : [0],
                backgroundColor: 'rgba(124, 58, 237, 0.5)',
                borderColor: 'rgba(124, 58, 237, 0.8)',
                borderWidth: 1,
                borderRadius: 6,
                maxBarThickness: 40,
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false },
                tooltip: {
                    backgroundColor: 'rgba(15, 10, 30, 0.9)',
                    borderColor: 'rgba(124, 58, 237, 0.3)',
                    borderWidth: 1,
                    titleColor: '#fff',
                    bodyColor: 'rgba(255,255,255,0.7)',
                    padding: 10,
                    cornerRadius: 8,
                }
            },
            scales: {
                x: {
                    grid: { display: false },
                    ticks: { color: 'rgba(255,255,255,0.3)', font: { size: 10 } },
                    border: { display: false },
                },
                y: {
                    grid: { color: 'rgba(255,255,255,0.05)' },
                    ticks: { color: 'rgba(255,255,255,0.3)', font: { size: 10 } },
                    border: { display: false },
                    beginAtZero: true,
                }
            }
        }
    });
}
</script>
{% endblock %}
