{% extends "base.html" %}
{% block title %}Feed Viral - Viral Social Pro{% endblock %}
{% block nav_feed %}active{% endblock %}
{% block mnav_feed %}active{% endblock %}
{% block page_title %}Feed Viral{% endblock %}
{% block page_subtitle %}Os videos mais virais agora{% endblock %}

{% block content %}
<div x-data="feedApp()" x-init="loadFeed(); window.addEventListener('lang-changed', e => { filterLang = e.detail; loadFeed(); })" class="space-y-4 animate-fade-up">

    <!-- Filters bar -->
    <div class="glass-card rounded-2xl p-4">
        <div class="flex flex-wrap items-center gap-3">
            <!-- Platform tabs -->
            <div class="flex gap-1 bg-white/5 rounded-xl p-1">
                <button @click="filterPlatform=''; loadFeed()" class="tab-btn" :class="filterPlatform==='' && 'active'">Todos</button>
                <button @click="filterPlatform='youtube'; loadFeed()" class="tab-btn" :class="filterPlatform==='youtube' && 'active'">YouTube</button>
                <button @click="filterPlatform='tiktok'; loadFeed()" class="tab-btn" :class="filterPlatform==='tiktok' && 'active'">TikTok</button>
                <button @click="filterPlatform='instagram'; loadFeed()" class="tab-btn" :class="filterPlatform==='instagram' && 'active'">Instagram</button>
            </div>
            <!-- Sort -->
            <select x-model="sortBy" @change="loadFeed()" class="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="outlier">Outlier Ratio</option>
                <option value="replicability">Replicabilidade</option>
                <option value="views">Mais Views</option>
                <option value="recent">Mais Recente</option>
                <option value="engagement">Engajamento</option>
            </select>
            <!-- Creator tier -->
            <select x-model="creatorTier" @change="loadFeed()" class="bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 outline-none">
                <option value="">Todos criadores</option>
                <option value="small">Pequenos (< 100K)</option>
                <option value="nano">Nano (< 10K)</option>
                <option value="micro">Micro (10K-100K)</option>
            </select>
            <!-- Language -->
            <select x-model="filterLang" @change="loadFeed()" class="bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 outline-none">
                <option value="">Todos idiomas</option>
                <option value="pt">Portugues</option>
                <option value="en">English</option>
                <option value="es">Espanol</option>
            </select>
            <!-- Min score -->
            <div class="flex items-center gap-2 ml-auto">
                <span class="text-xs text-white/40">Score min:</span>
                <input type="range" x-model="minScore" @change="loadFeed()" min="0" max="100" step="10" class="w-20 accent-brand-500">
                <span class="text-xs text-white/60 w-6" x-text="minScore"></span>
            </div>
        </div>
    </div>

    <!-- Results count -->
    <div class="flex items-center justify-between">
        <p class="text-sm text-white/40"><span class="text-white font-bold" x-text="totalVideos"></span> videos encontrados</p>
        <div class="flex gap-2">
            <button @click="viewMode='grid'" class="p-2 rounded-lg transition" :class="viewMode==='grid' ? 'bg-brand-500/20 text-brand-300' : 'text-white/30 hover:text-white/60'"><i data-lucide="grid-3x3" class="w-4 h-4"></i></button>
            <button @click="viewMode='list'" class="p-2 rounded-lg transition" :class="viewMode==='list' ? 'bg-brand-500/20 text-brand-300' : 'text-white/30 hover:text-white/60'"><i data-lucide="list" class="w-4 h-4"></i></button>
        </div>
    </div>

    <!-- Loading skeleton -->
    <div x-show="loading" class="grid-cards">
        <template x-for="i in 6"><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>

    <!-- Grid view -->
    <div x-show="!loading && viewMode==='grid'" class="grid-cards">
        <template x-for="video in videos" :key="video.id">
            <div class="glass-card rounded-2xl overflow-hidden cursor-pointer group" @click="$root.previewVideo = video">
                <div class="relative aspect-video bg-dark-800 overflow-hidden">
                    <img :src="video.thumbnail_url" :alt="video.title" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" loading="lazy" onerror="this.style.display='none'">
                    <div class="absolute top-2 left-2 flex gap-1.5">
                        <span class="px-2 py-1 rounded-lg text-[10px] font-bold uppercase" :class="'badge-'+video.platform" x-text="video.platform"></span>
                        <!-- Outlier badge -->
                        <span x-show="video.outlier_ratio >= 5" class="px-2 py-1 rounded-lg text-[10px] font-bold"
                              :class="video.outlier_ratio >= 20 ? 'bg-red-500/90 text-white' : video.outlier_ratio >= 10 ? 'bg-orange-500/90 text-white' : 'bg-yellow-500/90 text-black'"
                              x-text="video.outlier_ratio.toFixed(0) + 'x'"></span>
                    </div>
                    <div class="absolute top-2 right-2">
                        <div class="w-10 h-10 rounded-full flex items-center justify-center text-xs 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>
                    <div x-show="video.duration" class="absolute bottom-2 right-2 px-2 py-0.5 rounded-md bg-black/70 text-[11px] text-white/80 font-medium" x-text="formatDuration(video.duration)"></div>
                    <span x-show="video.is_small_creator" class="absolute bottom-2 left-2 px-2 py-0.5 rounded-lg text-[10px] font-bold bg-brand-500/80 text-white">Criador Pequeno</span>
                    <!-- Hover overlay -->
                    <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-3 pt-8 opacity-0 group-hover:opacity-100 transition-opacity">
                        <div class="flex items-center justify-between text-xs text-white/80">
                            <div class="flex items-center gap-4">
                                <span class="flex items-center gap-1"><i data-lucide="eye" class="w-3 h-3"></i><span x-text="formatNumber(video.views)"></span></span>
                                <span class="flex items-center gap-1"><i data-lucide="heart" class="w-3 h-3"></i><span x-text="formatNumber(video.likes)"></span></span>
                                <span class="flex items-center gap-1"><i data-lucide="message-circle" class="w-3 h-3"></i><span x-text="formatNumber(video.comments)"></span></span>
                            </div>
                            <button @click.stop="$root.downloadVideo(video)" class="p-1.5 rounded-lg bg-white/20 hover:bg-white/40 transition" title="Download">
                                <i data-lucide="download" class="w-3.5 h-3.5"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="p-3">
                    <h4 class="text-sm font-semibold text-white/90 line-clamp-2 leading-snug mb-2" x-text="video.title?.substring(0,80)"></h4>
                    <div class="flex items-center justify-between">
                        <div class="min-w-0">
                            <span class="text-xs text-white/40" x-text="'@'+(video.creator?.username || 'unknown')"></span>
                            <span x-show="video.creator_followers > 0" class="text-[10px] text-white/25 ml-1" x-text="formatNumber(video.creator_followers) + ' seg'"></span>
                        </div>
                        <div class="flex gap-2 items-center flex-shrink-0">
                            <span x-show="video.replicability_score >= 50" class="text-[10px] px-1.5 py-0.5 rounded font-semibold bg-green-500/15 text-green-400" x-text="'Rep '+Math.round(video.replicability_score)+'%'"></span>
                            <span class="text-[10px] px-2 py-0.5 rounded-full font-semibold" :style="'background:'+scoreColor(video.viral_score)+'15; color:'+scoreColor(video.viral_score)" x-text="engagementRate(video.views, video.likes, video.comments, video.shares)+'% eng'"></span>
                        </div>
                    </div>
                </div>
            </div>
        </template>
    </div>

    <!-- List view -->
    <div x-show="!loading && viewMode==='list'" class="space-y-2">
        <template x-for="video in videos" :key="video.id">
            <div class="glass-card rounded-xl p-3 flex gap-4 items-center cursor-pointer hover:border-brand-500/30" @click="$root.previewVideo = video">
                <div class="w-32 h-20 md:w-40 md:h-24 rounded-xl bg-dark-800 overflow-hidden flex-shrink-0">
                    <img :src="video.thumbnail_url" class="w-full h-full object-cover" loading="lazy" onerror="this.style.display='none'">
                </div>
                <div class="flex-1 min-w-0">
                    <div class="flex items-start gap-2 mb-1">
                        <span class="px-1.5 py-0.5 rounded text-[9px] font-bold uppercase flex-shrink-0" :class="'badge-'+video.platform" x-text="video.platform"></span>
                        <span x-show="video.outlier_ratio >= 5" class="px-1.5 py-0.5 rounded text-[9px] font-bold flex-shrink-0"
                              :class="video.outlier_ratio >= 20 ? 'bg-red-500/20 text-red-400' : 'bg-orange-500/20 text-orange-400'"
                              x-text="video.outlier_ratio.toFixed(0)+'x outlier'"></span>
                        <h4 class="text-sm font-semibold text-white/90 line-clamp-1" x-text="video.title"></h4>
                    </div>
                    <p class="text-xs text-white/40 mb-2">
                        <span x-text="'@'+(video.creator?.username || 'unknown')"></span>
                        <span x-show="video.creator_followers > 0" class="text-white/25" x-text="' · '+formatNumber(video.creator_followers)+' seg'"></span>
                        <span x-show="video.is_small_creator" class="ml-1 text-brand-300 font-semibold">Pequeno</span>
                    </p>
                    <div class="flex items-center gap-4 text-xs text-white/50">
                        <span x-text="formatNumber(video.views)+' views'"></span>
                        <span x-text="formatNumber(video.likes)+' likes'"></span>
                        <span x-text="engagementRate(video.views,video.likes,video.comments,video.shares)+'% eng'"></span>
                        <span x-show="video.replicability_score >= 50" class="text-green-400 font-semibold" x-text="'Rep '+Math.round(video.replicability_score)+'%'"></span>
                    </div>
                </div>
                <div class="flex items-center gap-2 flex-shrink-0">
                    <button @click.stop="$root.downloadVideo(video)" class="p-2 rounded-lg bg-white/5 hover:bg-emerald-500/20 transition" title="Download">
                        <i data-lucide="download" class="w-4 h-4 text-white/40 hover:text-emerald-400"></i>
                    </button>
                    <div class="w-12 h-12 rounded-full flex items-center justify-center text-sm 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>
                    <span class="text-[9px] text-white/30">Score</span>
                </div>
            </div>
        </template>
    </div>

    <!-- Pagination -->
    <div x-show="totalPages > 1" class="flex items-center justify-center gap-2 py-4">
        <button @click="page > 1 && (page--, loadFeed())" :disabled="page <= 1" class="px-4 py-2 rounded-xl glass-card text-sm font-medium disabled:opacity-30">Anterior</button>
        <span class="text-sm text-white/40">Pagina <span x-text="page"></span> de <span x-text="totalPages"></span></span>
        <button @click="page < totalPages && (page++, loadFeed())" :disabled="page >= totalPages" class="px-4 py-2 rounded-xl glass-card text-sm font-medium disabled:opacity-30">Proxima</button>
    </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-fire flex items-center justify-center mx-auto mb-4"><i data-lucide="flame" class="w-8 h-8"></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">Tente ajustar os filtros ou colete mais videos</p>
        <a href="/scrape" 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> Coletar Videos</a>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
function feedApp() {
    return {
        videos: [],
        loading: true,
        filterPlatform: '',
        filterLang: localStorage.getItem('globalLang') || '',
        sortBy: 'viral_score',
        minScore: 0,
        creatorTier: '',
        viewMode: 'grid',
        page: 1,
        totalVideos: 0,
        totalPages: 1,
        perPage: 24,

        async loadFeed() {
            this.loading = true;
            try {
                const params = new URLSearchParams({
                    limit: this.perPage,
                    offset: (this.page - 1) * this.perPage,
                    min_score: this.minScore,
                    sort_by: this.sortBy,
                });
                if (this.filterPlatform) params.set('platform', this.filterPlatform);
                if (this.creatorTier) params.set('creator_tier', this.creatorTier);
                // Use local filter or global lang
                const lang = this.filterLang || '';
                if (lang) params.set('language', lang);
                const resp = await fetch(`/api/videos?${params}`);
                const data = await resp.json();
                this.videos = data.videos || [];
                this.totalVideos = data.total || 0;
                this.totalPages = Math.ceil(this.totalVideos / this.perPage) || 1;
            } catch(e) {
                showToast('Erro ao carregar feed', 'error');
            }
            this.loading = false;
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        }
    };
}
</script>
{% endblock %}
