{% extends "base.html" %}
{% block title %}Videos Campeoes - Viral Social Pro{% endblock %}
{% block nav_campeoes %}active{% endblock %}
{% block page_title %}Videos Campeoes{% endblock %}
{% block page_subtitle %}Videos que mais vendem no TikTok Shop{% endblock %}

{% block content %}
<div x-data="championApp()" x-init="init()">

    <!-- STATS CARDS -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 mb-6 animate-fade-up">
        <div class="glass-card rounded-2xl p-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center"><i data-lucide="trophy" class="w-5 h-5"></i></div>
                <div>
                    <p class="text-2xl font-extrabold text-white" x-text="stats.total_videos || 0"></p>
                    <p class="text-xs text-white/40">Videos Campeoes</p>
                </div>
            </div>
        </div>
        <div class="glass-card rounded-2xl p-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl gradient-fire flex items-center justify-center"><i data-lucide="eye" class="w-5 h-5"></i></div>
                <div>
                    <p class="text-2xl font-extrabold text-white" x-text="stats.total_views_formatted || '0'"></p>
                    <p class="text-xs text-white/40">Views Totais</p>
                </div>
            </div>
        </div>
        <div class="glass-card rounded-2xl p-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl gradient-success flex items-center justify-center"><i data-lucide="package" class="w-5 h-5"></i></div>
                <div>
                    <p class="text-2xl font-extrabold text-white" x-text="stats.total_products || 0"></p>
                    <p class="text-xs text-white/40">Produtos</p>
                </div>
            </div>
        </div>
        <div class="glass-card rounded-2xl p-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl gradient-ocean flex items-center justify-center"><i data-lucide="bookmark" class="w-5 h-5"></i></div>
                <div>
                    <p class="text-2xl font-extrabold text-white" x-text="stats.total_saved || 0"></p>
                    <p class="text-xs text-white/40">Salvos</p>
                </div>
            </div>
        </div>
    </div>

    <!-- TABS -->
    <div class="flex items-center gap-2 mb-6 overflow-x-auto pb-2 animate-fade-up-delay">
        <button @click="activeTab = 'campeoes'" class="tab-btn" :class="activeTab === 'campeoes' && 'active'">
            <i data-lucide="trophy" class="w-4 h-4 inline-block mr-1"></i> Videos Campeoes
        </button>
        <button @click="activeTab = 'salvos'; loadSaved()" class="tab-btn" :class="activeTab === 'salvos' && 'active'">
            <i data-lucide="bookmark" class="w-4 h-4 inline-block mr-1"></i> Minha Biblioteca
        </button>
    </div>

    <!-- CHAMPION VIDEOS TAB -->
    <div x-show="activeTab === 'campeoes'">
        <!-- FILTERS BAR -->
        <div class="glass rounded-2xl p-4 mb-6 animate-fade-up-delay">
            <div class="flex flex-wrap items-center gap-3">
                <!-- Search -->
                <div class="flex items-center glass-light rounded-xl px-3 py-2 flex-1 min-w-[200px]">
                    <i data-lucide="search" class="w-4 h-4 text-white/30 mr-2"></i>
                    <input type="text" x-model="filters.search" @keyup.enter="loadVideos()" placeholder="Buscar videos, produtos, criadores..."
                        class="bg-transparent border-none outline-none text-sm text-white/80 placeholder:text-white/25 w-full">
                </div>

                <!-- Country -->
                <div class="flex items-center gap-1 bg-white/5 rounded-xl p-0.5">
                    <button @click="filters.country = 'all'; loadVideos()" class="px-3 py-1.5 rounded-lg text-xs font-semibold transition"
                        :class="filters.country === 'all' ? 'gradient-brand text-white' : 'text-white/40 hover:text-white/70'">Todos</button>
                    <button @click="filters.country = 'br'; loadVideos()" class="px-3 py-1.5 rounded-lg text-xs font-semibold transition flex items-center gap-1"
                        :class="filters.country === 'br' ? 'gradient-brand text-white' : 'text-white/40 hover:text-white/70'">BR</button>
                    <button @click="filters.country = 'us'; loadVideos()" class="px-3 py-1.5 rounded-lg text-xs font-semibold transition flex items-center gap-1"
                        :class="filters.country === 'us' ? 'gradient-brand text-white' : 'text-white/40 hover:text-white/70'">USA</button>
                </div>

                <!-- Sort -->
                <select x-model="filters.sort_by" @change="loadVideos()" class="bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 outline-none">
                    <option value="revenue">Mais Receita</option>
                    <option value="views">Mais Views</option>
                    <option value="viral_score">Viral Score</option>
                    <option value="recent">Mais Recentes</option>
                    <option value="engagement">Engajamento</option>
                    <option value="likes">Mais Likes</option>
                </select>

                <!-- Niche -->
                <select x-model="filters.niche" @change="loadVideos()" class="bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 outline-none">
                    <option value="">Todos Nichos</option>
                    <option value="moda">Moda & Fashion</option>
                    <option value="beleza">Beleza & Skincare</option>
                    <option value="casa">Casa & Decoracao</option>
                    <option value="eletronicos">Eletronicos & Tech</option>
                    <option value="esportes">Esportes & Fitness</option>
                    <option value="saude">Saude & Bem-estar</option>
                    <option value="pet">Pet</option>
                    <option value="bebe">Bebe & Maternidade</option>
                    <option value="automotivo">Automotivo</option>
                    <option value="papelaria">Papelaria</option>
                </select>

                <!-- Min Views -->
                <select x-model="filters.min_views" @change="loadVideos()" class="bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 outline-none">
                    <option value="0">Todas Views</option>
                    <option value="10000">10K+ views</option>
                    <option value="50000">50K+ views</option>
                    <option value="100000">100K+ views</option>
                    <option value="500000">500K+ views</option>
                    <option value="1000000">1M+ views</option>
                </select>

                <button @click="loadVideos()" class="px-4 py-2 rounded-xl gradient-brand text-white text-sm font-semibold hover:opacity-90 transition flex items-center gap-2">
                    <i data-lucide="search" class="w-4 h-4"></i> Filtrar
                </button>

                <button @click="clearFilters()" class="px-3 py-2 rounded-xl glass-light text-white/50 text-sm hover:text-white/80 transition">
                    <i data-lucide="x" class="w-4 h-4"></i>
                </button>
            </div>
        </div>

        <!-- RESULTS INFO -->
        <div class="flex items-center justify-between mb-4">
            <p class="text-sm text-white/40">
                <span x-text="total"></span> videos campeoes encontrados
            </p>
        </div>

        <!-- LOADING -->
        <div x-show="loading" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <template x-for="i in 6">
                <div class="glass-card rounded-2xl overflow-hidden">
                    <div class="skeleton h-48"></div>
                    <div class="p-4 space-y-3">
                        <div class="skeleton h-4 w-3/4"></div>
                        <div class="skeleton h-3 w-1/2"></div>
                        <div class="skeleton h-8 w-full"></div>
                    </div>
                </div>
            </template>
        </div>

        <!-- VIDEO CARDS (9:16 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 -->
                        <template x-if="playingVideoId !== video.id || !getEmbeddableVideoId(video)">
                            <div class="relative w-full h-full">
                                <img :src="video.thumbnail_url || '/api/thumbnail/' + video.id" :alt="video.title" class="w-full h-full object-cover" loading="lazy" onerror="this.style.display='none'">
                                <!-- Revenue Badge -->
                                <div class="absolute top-2 left-2 px-2 py-1 rounded-lg text-[10px] font-bold text-white" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                                    <span x-text="video.estimated_revenue_formatted"></span>
                                </div>
                                <!-- Score -->
                                <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:'+scoreColor(video.viral_score)+'22; color:'+scoreColor(video.viral_score)+'; border: 2px solid '+scoreColor(video.viral_score)+'44'" x-text="Math.round(video.viral_score)"></div>
                                </div>
                                <!-- Country + Niche badges -->
                                <div class="absolute bottom-12 left-2 flex gap-1" x-show="video.region || (video.niche && video.niche !== 'outros')">
                                    <span x-show="video.region" class="px-1.5 py-0.5 rounded text-[9px] font-bold glass" x-text="video.region"></span>
                                    <span x-show="video.niche && video.niche !== 'outros'" class="px-1.5 py-0.5 rounded text-[9px] font-medium glass text-brand-300 capitalize" x-text="nicheLabels[video.niche] || video.niche"></span>
                                </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 { openAnalysis(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 -->
                                <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-2 pt-6">
                                    <div class="flex items-center justify-between text-[10px] text-white/80">
                                        <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>
                            </div>
                        </template>
                    </div>
                    <!-- Info -->
                    <div class="p-2.5 space-y-2">
                        <h3 class="text-xs font-semibold text-white/90 line-clamp-2 leading-snug" x-text="video.title || 'Sem titulo'"></h3>
                        <div class="flex items-center justify-between text-[10px] text-white/40">
                            <span class="truncate" x-text="'@' + (video.creator_username || 'unknown')"></span>
                            <span class="text-accent-green font-bold flex-shrink-0" x-text="video.estimated_commission_formatted"></span>
                        </div>
                        <!-- Actions -->
                        <div class="flex items-center gap-1.5">
                            <button @click="openAnalysis(video)" class="flex-1 flex items-center justify-center gap-1 px-2 py-1.5 rounded-lg gradient-brand text-white text-[10px] font-semibold hover:opacity-90 transition">
                                <i data-lucide="scan" class="w-3 h-3"></i> Analisar
                            </button>
                            <button @click="toggleSave(video)" class="p-1.5 rounded-lg hover:bg-white/5 transition"
                                :class="video.is_saved ? 'text-accent-pink' : 'text-white/30 hover:text-white/60'">
                                <i :data-lucide="video.is_saved ? 'bookmark-check' : 'bookmark'" class="w-3.5 h-3.5"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </template>
        </div>

        <!-- Empty state -->
        <div x-show="!loading && videos.length === 0" class="text-center py-20">
            <div class="w-20 h-20 rounded-2xl gradient-brand mx-auto flex items-center justify-center mb-4 opacity-50">
                <i data-lucide="trophy" class="w-10 h-10 text-white"></i>
            </div>
            <h3 class="text-lg font-bold text-white/60 mb-2">Nenhum video campeao encontrado</h3>
            <p class="text-sm text-white/30 max-w-md mx-auto">
                Videos campeoes sao videos do TikTok Shop que promovem produtos e geram vendas.
                Use o Scanner para coletar videos com produtos.
            </p>
        </div>

        <!-- Load More -->
        <div x-show="videos.length < total && videos.length > 0" class="text-center mt-8">
            <button @click="loadMore()" :disabled="loadingMore" class="px-8 py-3 rounded-xl gradient-brand text-white font-semibold hover:opacity-90 transition disabled:opacity-50">
                <span x-show="!loadingMore">Carregar Mais</span>
                <span x-show="loadingMore">Carregando...</span>
            </button>
        </div>
    </div>

    <!-- SAVED VIDEOS TAB -->
    <div x-show="activeTab === 'salvos'">
        <!-- Folders -->
        <div class="flex items-center gap-2 mb-6 overflow-x-auto pb-2" x-show="folders.length > 0">
            <button @click="savedFolder = ''; loadSaved()" class="px-4 py-2 rounded-xl text-xs font-semibold transition whitespace-nowrap"
                :class="savedFolder === '' ? 'gradient-brand text-white' : 'glass-light text-white/50 hover:text-white/80'">
                Todos
            </button>
            <template x-for="f in folders" :key="f.folder">
                <button @click="savedFolder = f.folder; loadSaved()" class="px-4 py-2 rounded-xl text-xs font-semibold transition whitespace-nowrap flex items-center gap-1.5"
                    :class="savedFolder === f.folder ? 'gradient-brand text-white' : 'glass-light text-white/50 hover:text-white/80'">
                    <i data-lucide="folder" class="w-3.5 h-3.5"></i>
                    <span x-text="f.folder"></span>
                    <span class="opacity-60" x-text="'(' + f.count + ')'"></span>
                </button>
            </template>
        </div>

        <!-- Saved Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <template x-for="sv in savedVideos" :key="sv.saved_id">
                <div class="glass-card rounded-2xl overflow-hidden">
                    <div class="relative aspect-video bg-dark-800">
                        <img :src="sv.thumbnail_url || ''" class="w-full h-full object-cover" :alt="sv.title" onerror="this.style.display='none'">
                        <div class="absolute top-3 left-3 px-3 py-1.5 rounded-xl text-xs font-bold text-white" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                            <span x-text="sv.estimated_revenue_formatted"></span>
                        </div>
                    </div>
                    <div class="p-4 space-y-2">
                        <h3 class="text-sm font-semibold text-white/90 line-clamp-2" x-text="sv.title || 'Sem titulo'"></h3>
                        <div class="flex items-center gap-2 text-xs text-white/40">
                            <span x-text="'@' + (sv.creator_username || 'unknown')"></span>
                            <span>-</span>
                            <span x-text="sv.views_formatted + ' views'"></span>
                        </div>
                        <div class="flex items-center justify-between">
                            <span class="text-xs text-white/30 capitalize" x-text="sv.folder"></span>
                            <span class="text-xs text-white/20" x-text="timeAgo(sv.saved_at)"></span>
                        </div>
                        <div class="flex items-center gap-2 pt-1">
                            <a :href="sv.url" target="_blank" rel="noopener" class="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-xl glass-light text-white/60 text-xs font-medium hover:text-white">
                                <i data-lucide="external-link" class="w-3.5 h-3.5"></i> Ver
                            </a>
                            <button @click="removeSaved(sv)" class="p-2 rounded-xl hover:bg-white/5 text-accent-pink">
                                <i data-lucide="bookmark-minus" class="w-4 h-4"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </template>
        </div>

        <div x-show="savedVideos.length === 0" class="text-center py-20">
            <div class="w-20 h-20 rounded-2xl gradient-ocean mx-auto flex items-center justify-center mb-4 opacity-50">
                <i data-lucide="bookmark" class="w-10 h-10 text-white"></i>
            </div>
            <h3 class="text-lg font-bold text-white/60 mb-2">Biblioteca vazia</h3>
            <p class="text-sm text-white/30">Salve videos campeoes para acessar rapidamente depois.</p>
        </div>
    </div>

    <!-- ANALYSIS MODAL -->
    <div x-show="analysisVideo" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
         @click.self="analysisVideo = null; playingInModal = false" @keydown.escape.window="analysisVideo = null; playingInModal = false"
         x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100">
        <div class="glass rounded-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto" @click.stop>
            <!-- Header -->
            <div class="p-4 flex items-center justify-between border-b border-white/5">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center">
                        <i data-lucide="scan" class="w-5 h-5"></i>
                    </div>
                    <div>
                        <h3 class="font-bold text-white/90">Analise do Video</h3>
                        <p class="text-xs text-white/40">Transcricao IA & Receita Estimada</p>
                    </div>
                </div>
                <button @click="analysisVideo = null; playingInModal = false" class="p-1.5 rounded-lg hover:bg-white/10"><i data-lucide="x" class="w-5 h-5"></i></button>
            </div>

            <div class="p-5 space-y-5" x-show="analysisVideo">
                <!-- Video Player + Info -->
                <div class="flex flex-col md:flex-row gap-4">
                    <!-- Video Embed Player -->
                    <div class="flex-shrink-0 mx-auto md:mx-0">
                        <!-- TikTok Player -->
                        <template x-if="playingInModal && getTikTokVideoId(analysisVideo)">
                            <div class="rounded-xl overflow-hidden bg-dark-800 border border-white/5" style="width: 280px; height: 498px;">
                                <iframe :src="'https://www.tiktok.com/player/v1/' + getTikTokVideoId(analysisVideo) + '?autoplay=1&loop=0&controls=1&music_info=0&description=0'"
                                    width="100%" height="100%" frameborder="0" allow="autoplay; encrypted-media; fullscreen" allowfullscreen
                                    style="border:0; border-radius: 12px;"></iframe>
                            </div>
                        </template>
                        <!-- YouTube Player -->
                        <template x-if="playingInModal && !getTikTokVideoId(analysisVideo) && getYouTubeVideoId(analysisVideo)">
                            <div class="rounded-xl overflow-hidden bg-dark-800 border border-white/5" style="width: 280px; height: 498px;">
                                <iframe :src="'https://www.youtube-nocookie.com/embed/' + getYouTubeVideoId(analysisVideo) + '?autoplay=1&loop=1&rel=0&modestbranding=1&playsinline=1'"
                                    width="100%" height="100%" frameborder="0" allow="autoplay; encrypted-media; fullscreen" allowfullscreen
                                    style="border:0; border-radius: 12px;"></iframe>
                            </div>
                        </template>
                        <!-- Thumbnail (not playing) -->
                        <template x-if="!playingInModal || !getEmbeddableVideoId(analysisVideo)">
                            <div class="relative rounded-xl overflow-hidden bg-dark-800 cursor-pointer group" style="width: 280px; height: 498px;"
                                 @click="if(getEmbeddableVideoId(analysisVideo)) playingInModal = true">
                                <img :src="analysisVideo?.thumbnail_url || ''" class="w-full h-full object-cover" onerror="this.style.display='none'">
                                <div x-show="getEmbeddableVideoId(analysisVideo)" class="absolute inset-0 bg-black/30 group-hover:bg-black/50 transition flex items-center justify-center">
                                    <div class="w-16 h-16 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center group-hover:scale-110 transition-transform">
                                        <i data-lucide="play" class="w-8 h-8 text-white ml-1"></i>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </div>
                    <div class="flex-1 min-w-0">
                        <h4 class="text-sm font-bold text-white/90 line-clamp-2 mb-2" x-text="analysisVideo?.title"></h4>
                        <p class="text-xs text-white/40 mb-1" x-text="'@' + (analysisVideo?.creator_username || 'unknown')"></p>
                        <div class="flex items-center gap-3 text-xs text-white/50 mb-3">
                            <span x-text="analysisVideo?.views_formatted + ' views'"></span>
                            <span x-text="formatNumber(analysisVideo?.likes || 0) + ' likes'"></span>
                            <span x-text="analysisVideo?.duration_formatted"></span>
                        </div>
                        <!-- Inline stats -->
                        <div class="grid grid-cols-2 gap-2">
                            <div class="glass-light rounded-lg p-2 text-center">
                                <p class="text-sm font-bold text-accent-green" x-text="analysisVideo?.estimated_revenue_formatted"></p>
                                <p class="text-[9px] text-white/30">Receita Est.</p>
                            </div>
                            <div class="glass-light rounded-lg p-2 text-center">
                                <p class="text-sm font-bold text-brand-300" x-text="analysisVideo?.estimated_commission_formatted"></p>
                                <p class="text-[9px] text-white/30">Comissao 10%</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Revenue Estimation -->
                <div class="glass-light rounded-2xl p-5">
                    <h4 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                        <i data-lucide="dollar-sign" class="w-4 h-4 text-accent-green"></i> Receita Estimada
                    </h4>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <div class="text-center">
                            <p class="text-xl font-extrabold text-accent-green" x-text="analysisVideo?.estimated_revenue_formatted"></p>
                            <p class="text-[10px] text-white/30 mt-1">Receita Total</p>
                        </div>
                        <div class="text-center">
                            <p class="text-xl font-extrabold text-brand-300" x-text="analysisVideo?.estimated_commission_formatted"></p>
                            <p class="text-[10px] text-white/30 mt-1">Comissao (10%)</p>
                        </div>
                        <div class="text-center">
                            <p class="text-xl font-extrabold text-white/80" x-text="analysisVideo?.estimated_sales?.toLocaleString('pt-BR') || '0'"></p>
                            <p class="text-[10px] text-white/30 mt-1">Vendas Estimadas</p>
                        </div>
                        <div class="text-center">
                            <p class="text-xl font-extrabold text-accent-cyan" x-text="analysisVideo?.product_price_formatted || 'N/A'"></p>
                            <p class="text-[10px] text-white/30 mt-1">Preco Produto</p>
                        </div>
                    </div>
                </div>

                <!-- Script Analysis -->
                <div class="glass-light rounded-2xl p-5" x-show="analysisData">
                    <div class="flex items-center justify-between mb-4">
                        <h4 class="text-sm font-bold text-white/80 flex items-center gap-2">
                            <i data-lucide="file-text" class="w-4 h-4 text-brand-400"></i> Analise do Script (IA)
                        </h4>
                        <div class="flex items-center gap-2">
                            <span class="text-xs text-white/30">Nota:</span>
                            <span class="px-2.5 py-1 rounded-lg text-xs font-bold"
                                :style="'background:' + scoreColor(analysisData?.script?.script_score || 0) + '20; color:' + scoreColor(analysisData?.script?.script_score || 0)"
                                x-text="(analysisData?.script?.script_grade || '-') + ' (' + (analysisData?.script?.script_score || 0) + '/100)'"></span>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <!-- Hooks -->
                        <div class="space-y-2">
                            <div class="flex items-center gap-2">
                                <div class="w-6 h-6 rounded-lg bg-accent-orange/20 flex items-center justify-center">
                                    <i data-lucide="zap" class="w-3.5 h-3.5 text-accent-orange"></i>
                                </div>
                                <span class="text-xs font-semibold text-accent-orange">Hooks (Ganchos)</span>
                            </div>
                            <template x-for="h in (analysisData?.script?.hooks || [])" :key="h">
                                <p class="text-xs text-white/60 pl-8 italic" x-text="'\"' + h + '\"'"></p>
                            </template>
                            <p x-show="!analysisData?.script?.hooks?.length" class="text-xs text-white/30 pl-8">Nenhum hook detectado</p>
                        </div>

                        <!-- Pain Points -->
                        <div class="space-y-2">
                            <div class="flex items-center gap-2">
                                <div class="w-6 h-6 rounded-lg bg-accent-red/20 flex items-center justify-center">
                                    <i data-lucide="alert-triangle" class="w-3.5 h-3.5 text-accent-red"></i>
                                </div>
                                <span class="text-xs font-semibold text-accent-red">Dores (Pain Points)</span>
                            </div>
                            <template x-for="p in (analysisData?.script?.pain_points || [])" :key="p">
                                <p class="text-xs text-white/60 pl-8 italic" x-text="'\"' + p + '\"'"></p>
                            </template>
                            <p x-show="!analysisData?.script?.pain_points?.length" class="text-xs text-white/30 pl-8">Nenhuma dor detectada</p>
                        </div>

                        <!-- Solutions -->
                        <div class="space-y-2">
                            <div class="flex items-center gap-2">
                                <div class="w-6 h-6 rounded-lg bg-accent-green/20 flex items-center justify-center">
                                    <i data-lucide="check-circle" class="w-3.5 h-3.5 text-accent-green"></i>
                                </div>
                                <span class="text-xs font-semibold text-accent-green">Solucoes</span>
                            </div>
                            <template x-for="s in (analysisData?.script?.solutions || [])" :key="s">
                                <p class="text-xs text-white/60 pl-8 italic" x-text="'\"' + s + '\"'"></p>
                            </template>
                            <p x-show="!analysisData?.script?.solutions?.length" class="text-xs text-white/30 pl-8">Nenhuma solucao detectada</p>
                        </div>

                        <!-- CTAs -->
                        <div class="space-y-2">
                            <div class="flex items-center gap-2">
                                <div class="w-6 h-6 rounded-lg bg-brand-400/20 flex items-center justify-center">
                                    <i data-lucide="mouse-pointer-click" class="w-3.5 h-3.5 text-brand-400"></i>
                                </div>
                                <span class="text-xs font-semibold text-brand-400">CTAs (Chamada para Acao)</span>
                            </div>
                            <template x-for="c in (analysisData?.script?.ctas || [])" :key="c">
                                <p class="text-xs text-white/60 pl-8 italic" x-text="'\"' + c + '\"'"></p>
                            </template>
                            <p x-show="!analysisData?.script?.ctas?.length" class="text-xs text-white/30 pl-8">Nenhum CTA detectado</p>
                        </div>
                    </div>

                    <!-- Extra Indicators -->
                    <div class="flex flex-wrap gap-2 mt-4 pt-4 border-t border-white/5">
                        <span class="px-2.5 py-1 rounded-lg text-[10px] font-medium"
                            :class="analysisData?.script?.has_price_mention ? 'bg-accent-green/20 text-accent-green' : 'bg-white/5 text-white/30'"
                            x-text="analysisData?.script?.has_price_mention ? 'Menciona Preco' : 'Sem Preco'"></span>
                        <span class="px-2.5 py-1 rounded-lg text-[10px] font-medium"
                            :class="analysisData?.script?.has_urgency ? 'bg-accent-orange/20 text-accent-orange' : 'bg-white/5 text-white/30'"
                            x-text="analysisData?.script?.has_urgency ? 'Tem Urgencia' : 'Sem Urgencia'"></span>
                        <span class="px-2.5 py-1 rounded-lg text-[10px] font-medium"
                            :class="analysisData?.script?.has_social_proof ? 'bg-brand-400/20 text-brand-400' : 'bg-white/5 text-white/30'"
                            x-text="analysisData?.script?.has_social_proof ? 'Prova Social' : 'Sem Prova Social'"></span>
                        <span class="px-2.5 py-1 rounded-lg text-[10px] font-medium bg-white/5 text-white/30"
                            x-text="(analysisData?.script?.word_count || 0) + ' palavras'"></span>
                    </div>
                </div>

                <!-- Product Details -->
                <div class="glass-light rounded-2xl p-5" x-show="analysisVideo?.product">
                    <h4 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2">
                        <i data-lucide="package" class="w-4 h-4 text-accent-cyan"></i> Produto Vinculado
                    </h4>
                    <div class="flex items-center gap-4">
                        <img :src="analysisVideo?.product?.image" class="w-16 h-16 rounded-xl object-cover" onerror="this.style.display='none'">
                        <div>
                            <p class="text-sm font-semibold text-white/80" x-text="analysisVideo?.product?.title || 'Produto'"></p>
                            <div class="flex items-center gap-3 mt-1 text-xs text-white/50">
                                <span x-text="'R$ ' + (analysisVideo?.product?.price || '?')"></span>
                                <span x-text="(analysisVideo?.product?.sold_formatted || '0') + ' vendidos'"></span>
                                <span x-show="analysisVideo?.product?.rating" class="flex items-center gap-0.5">
                                    <i data-lucide="star" class="w-3 h-3 text-yellow-400"></i>
                                    <span x-text="analysisVideo?.product?.rating"></span>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Actions -->
                <div class="flex gap-3">
                    <a :href="analysisVideo?.url" target="_blank" rel="noopener" class="flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition">
                        <i data-lucide="external-link" class="w-4 h-4"></i> Abrir Video
                    </a>
                    <a :href="analysisVideo?.shop_product_url" target="_blank" rel="noopener" x-show="analysisVideo?.shop_product_url" class="flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-xl gradient-success text-white font-semibold text-sm hover:opacity-90 transition">
                        <i data-lucide="shopping-bag" class="w-4 h-4"></i> Ver Produto
                    </a>
                    <button @click="toggleSave(analysisVideo)" class="flex items-center justify-center gap-2 px-4 py-3 rounded-xl glass-card font-medium text-sm transition"
                        :class="analysisVideo?.is_saved ? 'text-accent-pink' : 'text-white/60 hover:text-white'">
                        <i :data-lucide="analysisVideo?.is_saved ? 'bookmark-check' : 'bookmark-plus'" class="w-4 h-4"></i>
                        <span x-text="analysisVideo?.is_saved ? 'Salvo' : 'Salvar'"></span>
                    </button>
                </div>
            </div>
        </div>
    </div>

</div>
{% endblock %}

{% block scripts %}
<script>
function championApp() {
    return {
        activeTab: 'campeoes',
        loading: true,
        loadingMore: false,
        playingVideoId: null,
        videos: [],
        total: 0,
        stats: {},
        filters: {
            search: '',
            country: 'all',
            sort_by: 'revenue',
            niche: '',
            min_views: '10000',
            min_revenue: 0,
        },
        analysisVideo: null,
        analysisData: null,
        playingInModal: false,
        savedVideos: [],
        savedFolder: '',
        folders: [],
        nicheLabels: {
            moda: 'Moda', beleza: 'Beleza', casa: 'Casa', eletronicos: 'Tech',
            esportes: 'Fitness', saude: 'Saude', pet: 'Pet', bebe: 'Bebe',
            automotivo: 'Auto', papelaria: 'Papelaria', outros: 'Outros',
        },

        async init() {
            await Promise.all([this.loadStats(), this.loadVideos()]);
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async loadStats() {
            try {
                const r = await fetch('/api/champion/stats');
                this.stats = await r.json();
            } catch(e) { console.error('Stats error:', e); }
        },

        async loadVideos() {
            this.loading = true;
            this.videos = [];
            try {
                const params = new URLSearchParams({
                    limit: '50',
                    offset: '0',
                    country: this.filters.country,
                    niche: this.filters.niche,
                    sort_by: this.filters.sort_by,
                    min_views: this.filters.min_views,
                    search: this.filters.search,
                });
                if (this.filters.min_revenue > 0) params.set('min_revenue', this.filters.min_revenue);
                const r = await fetch('/api/champion/videos?' + params);
                const data = await r.json();
                this.videos = data.videos || [];
                this.total = data.total || 0;
            } catch(e) {
                console.error('Load error:', e);
                showToast('Erro ao carregar videos', 'error');
            }
            this.loading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async loadMore() {
            this.loadingMore = true;
            try {
                const params = new URLSearchParams({
                    limit: '50',
                    offset: String(this.videos.length),
                    country: this.filters.country,
                    niche: this.filters.niche,
                    sort_by: this.filters.sort_by,
                    min_views: this.filters.min_views,
                    search: this.filters.search,
                });
                const r = await fetch('/api/champion/videos?' + params);
                const data = await r.json();
                this.videos = [...this.videos, ...(data.videos || [])];
                this.total = data.total || this.total;
            } catch(e) { showToast('Erro ao carregar mais', 'error'); }
            this.loadingMore = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        clearFilters() {
            this.filters = { search: '', country: 'all', sort_by: 'revenue', niche: '', min_views: '10000', min_revenue: 0 };
            this.loadVideos();
        },

        async openAnalysis(video) {
            this.analysisVideo = video;
            this.analysisData = null;
            this.playingInModal = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            try {
                const r = await fetch('/api/champion/analyze/' + video.id);
                this.analysisData = await r.json();
            } catch(e) { console.error('Analysis error:', e); }
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async toggleSave(video) {
            if (!video) return;
            try {
                if (video.is_saved) {
                    await fetch('/api/champion/save/' + video.id, { method: 'DELETE' });
                    video.is_saved = false;
                    showToast('Video removido da biblioteca', 'info');
                } else {
                    await fetch('/api/champion/save/' + video.id, { method: 'POST' });
                    video.is_saved = true;
                    showToast('Video salvo na biblioteca!', 'success');
                }
                this.loadStats();
            } catch(e) { showToast('Erro ao salvar', 'error'); }
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async loadSaved() {
            try {
                const [vr, fr] = await Promise.all([
                    fetch('/api/champion/saved?' + new URLSearchParams({ folder: this.savedFolder })),
                    fetch('/api/champion/folders'),
                ]);
                const vdata = await vr.json();
                this.savedVideos = vdata.videos || [];
                this.folders = await fr.json();
            } catch(e) { showToast('Erro ao carregar salvos', 'error'); }
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async removeSaved(sv) {
            try {
                await fetch('/api/champion/save/' + sv.video_id, { method: 'DELETE' });
                this.savedVideos = this.savedVideos.filter(v => v.saved_id !== sv.saved_id);
                showToast('Removido da biblioteca', 'info');
                this.loadStats();
            } catch(e) { showToast('Erro ao remover', 'error'); }
        },
    };
}
</script>
{% endblock %}
