{% extends "base.html" %}
{% block title %}TrendRadar - Viral Social Pro{% endblock %}
{% block nav_trends %}active{% endblock %}
{% block page_title %}TrendRadar{% endblock %}
{% block page_subtitle %}Inteligencia de tendencias, nichos, saturacao e alertas{% endblock %}

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

    <!-- Header -->
    <div class="glass-card rounded-2xl overflow-hidden animate-fade-up">
        <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="radar" class="w-6 h-6 text-white"></i>
                </div>
                <div>
                    <h1 class="text-xl md:text-2xl font-bold text-white">TrendRadar Intelligence</h1>
                    <p class="text-sm text-white/40 mt-0.5">Nichos, formatos, saturacao, alertas e previsoes</p>
                </div>
            </div>
            <div class="flex items-center gap-3 flex-wrap">
                <!-- Platform Filter -->
                <div class="flex gap-1 bg-white/5 rounded-xl p-1">
                    <button @click="platform=''; loadAll()" class="tab-btn" :class="platform==='' && 'active'">Todas</button>
                    <button @click="platform='tiktok'; loadAll()" class="tab-btn" :class="platform==='tiktok' && 'active'">TikTok</button>
                    <button @click="platform='youtube'; loadAll()" class="tab-btn" :class="platform==='youtube' && 'active'">YouTube</button>
                    <button @click="platform='instagram'; loadAll()" class="tab-btn" :class="platform==='instagram' && 'active'">Instagram</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Trend Alerts Banner -->
    <div x-show="alerts.length > 0" class="space-y-2 animate-fade-up">
        <template x-for="alert in alerts" :key="alert.title">
            <div class="glass-card rounded-xl p-3 flex items-center gap-3 border-l-4"
                 :class="{
                    'border-red-500 bg-red-500/5': alert.priority === 'urgent',
                    'border-orange-500 bg-orange-500/5': alert.priority === 'high',
                    'border-blue-500 bg-blue-500/5': alert.priority === 'medium',
                    'border-gray-500': alert.priority === 'low',
                 }">
                <div class="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0"
                     :class="{
                        'bg-red-500/20': alert.priority === 'urgent',
                        'bg-orange-500/20': alert.priority === 'high',
                        'bg-blue-500/20': alert.priority === 'medium',
                     }">
                    <i :data-lucide="alert.icon || 'bell'" class="w-4 h-4"
                       :class="{
                          'text-red-400': alert.priority === 'urgent',
                          'text-orange-400': alert.priority === 'high',
                          'text-blue-400': alert.priority === 'medium',
                       }"></i>
                </div>
                <div class="flex-1 min-w-0">
                    <p class="text-sm font-semibold text-white/90 truncate" x-text="alert.title"></p>
                    <p class="text-xs text-white/40 truncate" x-text="alert.detail"></p>
                </div>
                <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase flex-shrink-0"
                      :class="{
                         'bg-red-500/20 text-red-400': alert.priority === 'urgent',
                         'bg-orange-500/20 text-orange-400': alert.priority === 'high',
                         'bg-blue-500/20 text-blue-400': alert.priority === 'medium',
                      }" x-text="alert.type"></span>
            </div>
        </template>
    </div>

    <!-- KPI Stats (from server-side) -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-3 animate-fade-up">
        <div class="glass-card rounded-xl p-4 text-center">
            <p class="stat-number text-brand-300">{{ hashtags | length }}</p>
            <p class="text-[10px] text-white/40 mt-1">Hashtags Ativas</p>
        </div>
        <div class="glass-card rounded-xl p-4 text-center">
            <p class="stat-number text-orange-400">{{ patterns.total_analyzed }}</p>
            <p class="text-[10px] text-white/40 mt-1">Videos Analisados</p>
        </div>
        <div class="glass-card rounded-xl p-4 text-center">
            <p class="stat-number text-cyan-400" x-text="Object.keys(niches).length">--</p>
            <p class="text-[10px] text-white/40 mt-1">Nichos Monitorados</p>
        </div>
        <div class="glass-card rounded-xl p-4 text-center">
            <p class="stat-number text-emerald-400" x-text="crossPlatform.length">--</p>
            <p class="text-[10px] text-white/40 mt-1">Trends Cross-Platform</p>
        </div>
    </div>

    <!-- Tab Navigation for sections -->
    <div class="flex flex-wrap gap-2 animate-fade-up-delay">
        <button @click="tab='niches'" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='niches' ? 'bg-brand-500 text-white shadow-lg shadow-brand-500/30' : 'glass-light text-brand-400 hover:bg-brand-500/20'">
            Radar de Nichos
        </button>
        <button @click="tab='formats'" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='formats' ? 'bg-orange-500 text-white shadow-lg shadow-orange-500/30' : 'glass-light text-orange-400 hover:bg-orange-500/20'">
            Formatos em Alta
        </button>
        <button @click="tab='creators'" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='creators' ? 'bg-cyan-500 text-white shadow-lg shadow-cyan-500/30' : 'glass-light text-cyan-400 hover:bg-cyan-500/20'">
            Creators em Alta
        </button>
        <button @click="tab='crossplatform'" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='crossplatform' ? 'bg-purple-500 text-white shadow-lg shadow-purple-500/30' : 'glass-light text-purple-400 hover:bg-purple-500/20'">
            Cross-Platform
        </button>
        <button @click="tab='saturation'" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='saturation' ? 'bg-red-500 text-white shadow-lg shadow-red-500/30' : 'glass-light text-red-400 hover:bg-red-500/20'">
            Saturacao
        </button>
        <button @click="tab='timeline'" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='timeline' ? 'bg-emerald-500 text-white shadow-lg shadow-emerald-500/30' : 'glass-light text-emerald-400 hover:bg-emerald-500/20'">
            Timeline
        </button>
        <button @click="tab='predictions'" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='predictions' ? 'bg-yellow-500 text-black shadow-lg shadow-yellow-500/30' : 'glass-light text-yellow-400 hover:bg-yellow-500/20'">
            Previsoes
        </button>
        <button @click="tab='hashtags'" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='hashtags' ? 'bg-pink-500 text-white shadow-lg shadow-pink-500/30' : 'glass-light text-pink-400 hover:bg-pink-500/20'">
            Hashtags
        </button>
        <button @click="tab='microtrends'; loadMicroTrends()" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='microtrends' ? 'bg-teal-500 text-white shadow-lg shadow-teal-500/30' : 'glass-light text-teal-400 hover:bg-teal-500/20'">
            Micro-Trends
        </button>
        <button @click="tab='algorithm'; loadAlgorithm()" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='algorithm' ? 'bg-rose-500 text-white shadow-lg shadow-rose-500/30' : 'glass-light text-rose-400 hover:bg-rose-500/20'">
            Algoritmo
        </button>
        <button @click="tab='music'; loadMusic()" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='music' ? 'bg-violet-500 text-white shadow-lg shadow-violet-500/30' : 'glass-light text-violet-400 hover:bg-violet-500/20'">
            Musica
        </button>
        <button @click="tab='globalmap'; loadGlobalMap()" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='globalmap' ? 'bg-sky-500 text-white shadow-lg shadow-sky-500/30' : 'glass-light text-sky-400 hover:bg-sky-500/20'">
            Mapa Global
        </button>
        <button @click="tab='report'; loadWeeklyReport()" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='report' ? 'bg-amber-500 text-black shadow-lg shadow-amber-500/30' : 'glass-light text-amber-400 hover:bg-amber-500/20'">
            Relatorio
        </button>
        <button @click="tab='stepps'" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='stepps' ? 'bg-indigo-500 text-white shadow-lg shadow-indigo-500/30' : 'glass-light text-indigo-400 hover:bg-indigo-500/20'">
            STEPPS
        </button>
        <button @click="tab='revenue'" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='revenue' ? 'bg-emerald-500 text-white shadow-lg shadow-emerald-500/30' : 'glass-light text-emerald-400 hover:bg-emerald-500/20'">
            Receita
        </button>
        <button @click="tab='sentiment'" class="px-3 py-1.5 rounded-lg text-xs font-bold transition"
                :class="tab==='sentiment' ? 'bg-pink-500 text-white shadow-lg shadow-pink-500/30' : 'glass-light text-pink-400 hover:bg-pink-500/20'">
            Sentimento
        </button>
    </div>

    <!-- ===================== NICHE RADAR TAB ===================== -->
    <div x-show="tab==='niches'" class="space-y-4">
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="compass" class="w-5 h-5 text-brand-400"></i> Radar de Nichos
                </h2>
                <p class="text-xs text-white/40 mt-1">Performance e crescimento por nicho nos ultimos 7 dias</p>
            </div>
            <div class="p-5">
                <template x-if="Object.keys(niches).length === 0">
                    <div class="text-center py-8 text-white/30 text-sm">Carregando nichos...</div>
                </template>
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                    <template x-for="[name, data] in Object.entries(niches)" :key="name">
                        <div class="glass-light rounded-xl p-4 hover:border-brand-500/30 transition cursor-default">
                            <div class="flex items-center justify-between mb-3">
                                <span class="text-sm font-bold text-white/90 capitalize" x-text="name.replace('_',' ')"></span>
                                <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase"
                                      :class="{
                                         'bg-red-500/20 text-red-400': data.status === 'hot',
                                         'bg-orange-500/20 text-orange-400': data.status === 'growing',
                                         'bg-blue-500/20 text-blue-400': data.status === 'stable',
                                         'bg-gray-500/20 text-gray-400': data.status === 'declining',
                                      }" x-text="data.status"></span>
                            </div>
                            <div class="grid grid-cols-2 gap-2 text-xs">
                                <div>
                                    <span class="text-white/40">Videos</span>
                                    <p class="font-bold text-white/80" x-text="data.video_count"></p>
                                </div>
                                <div>
                                    <span class="text-white/40">Score Medio</span>
                                    <p class="font-bold text-brand-300" x-text="data.avg_score"></p>
                                </div>
                                <div>
                                    <span class="text-white/40">Views Medio</span>
                                    <p class="font-bold text-white/80" x-text="fmtNum(data.avg_views)"></p>
                                </div>
                                <div>
                                    <span class="text-white/40">Crescimento</span>
                                    <p class="font-bold" :class="data.growth_percent > 0 ? 'text-emerald-400' : 'text-red-400'"
                                       x-text="(data.growth_percent > 0 ? '+' : '') + data.growth_percent + '%'"></p>
                                </div>
                            </div>
                            <!-- Top hashtags for niche -->
                            <div x-show="data.top_hashtags && data.top_hashtags.length > 0" class="mt-3 flex flex-wrap gap-1">
                                <template x-for="[tag, count] in (data.top_hashtags || []).slice(0,5)" :key="tag">
                                    <span class="px-1.5 py-0.5 rounded-md bg-white/5 text-[10px] text-white/50" x-text="'#'+tag"></span>
                                </template>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- ===================== FORMAT TRENDS TAB ===================== -->
    <div x-show="tab==='formats'" class="space-y-4">
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="film" class="w-5 h-5 text-orange-400"></i> Formatos em Alta
                </h2>
                <p class="text-xs text-white/40 mt-1">Quais formatos de video estao performando melhor</p>
            </div>
            <div class="p-5">
                <div class="space-y-2">
                    <template x-for="(fmt, idx) in formats" :key="fmt.format">
                        <div class="flex items-center gap-3 p-3 rounded-xl glass-light">
                            <div class="w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold"
                                 :class="idx < 3 ? 'gradient-fire text-white' : 'bg-white/10 text-white/60'"
                                 x-text="idx + 1"></div>
                            <div class="flex-1 min-w-0">
                                <p class="text-sm font-semibold text-white/90 capitalize" x-text="fmt.format.replace('_',' ')"></p>
                                <div class="flex items-center gap-3 text-xs text-white/40">
                                    <span x-text="fmt.video_count + ' videos'"></span>
                                    <span class="text-brand-300" x-text="'Score: ' + fmt.avg_score"></span>
                                    <span x-text="'Views: ' + fmtNum(fmt.avg_views)"></span>
                                </div>
                            </div>
                            <div class="text-right flex-shrink-0">
                                <p class="text-sm font-bold" :class="fmt.growth_percent > 0 ? 'text-emerald-400' : 'text-red-400'"
                                   x-text="(fmt.growth_percent > 0 ? '+' : '') + fmt.growth_percent + '%'"></p>
                                <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase"
                                      :class="{
                                         'bg-red-500/20 text-red-400': fmt.status === 'hot',
                                         'bg-orange-500/20 text-orange-400': fmt.status === 'growing',
                                         'bg-blue-500/20 text-blue-400': fmt.status === 'stable',
                                         'bg-gray-500/20 text-gray-400': fmt.status === 'declining',
                                      }" x-text="fmt.status"></span>
                            </div>
                        </div>
                    </template>
                    <template x-if="formats.length === 0">
                        <div class="text-center py-8 text-white/30 text-sm">Carregando formatos...</div>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- ===================== TRENDING CREATORS TAB ===================== -->
    <div x-show="tab==='creators'" class="space-y-4">
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="users" class="w-5 h-5 text-cyan-400"></i> Creators em Alta
                </h2>
                <p class="text-xs text-white/40 mt-1">Creators com mais videos virais nos ultimos 7 dias</p>
            </div>
            <div class="p-5">
                <div class="space-y-2">
                    <template x-for="(c, idx) in creators" :key="c.id">
                        <div class="flex items-center gap-3 p-3 rounded-xl glass-light">
                            <div class="w-8 h-8 rounded-full flex items-center justify-center text-xs font-bold"
                                 :class="idx < 3 ? 'gradient-brand text-white' : 'bg-white/10 text-white/60'"
                                 x-text="idx + 1"></div>
                            <div class="w-10 h-10 rounded-full bg-white/10 overflow-hidden flex-shrink-0">
                                <img x-show="c.avatar_url" :src="c.avatar_url" class="w-full h-full object-cover" loading="lazy">
                                <div x-show="!c.avatar_url" class="w-full h-full flex items-center justify-center text-white/30">
                                    <i data-lucide="user" class="w-5 h-5"></i>
                                </div>
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="text-sm font-semibold text-white/90 truncate" x-text="'@' + c.username"></p>
                                <div class="flex items-center gap-3 text-xs text-white/40">
                                    <span class="uppercase" x-text="c.platform"></span>
                                    <span x-text="fmtNum(c.followers) + ' seguidores'"></span>
                                    <span class="text-brand-300" x-text="c.video_count + ' virais'"></span>
                                </div>
                            </div>
                            <div class="text-right flex-shrink-0">
                                <p class="text-sm font-bold text-orange-400" x-text="c.avg_score + ' avg'"></p>
                                <p class="text-[10px] text-white/40" x-text="fmtNum(c.total_views) + ' views'"></p>
                            </div>
                        </div>
                    </template>
                    <template x-if="creators.length === 0">
                        <div class="text-center py-8 text-white/30 text-sm">Carregando creators...</div>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- ===================== CROSS-PLATFORM TAB ===================== -->
    <div x-show="tab==='crossplatform'" class="space-y-4">
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="globe" class="w-5 h-5 text-purple-400"></i> Trends Cross-Platform
                </h2>
                <p class="text-xs text-white/40 mt-1">Hashtags que estao viralizando em multiplas plataformas ao mesmo tempo</p>
            </div>
            <div class="p-5">
                <div class="space-y-2">
                    <template x-for="(ct, idx) in crossPlatform" :key="ct.hashtag">
                        <div class="flex items-center gap-3 p-3 rounded-xl glass-light">
                            <div class="w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold"
                                 :class="ct.platform_count >= 3 ? 'gradient-fire text-white animate-pulse' : 'bg-purple-500/20 text-purple-400'"
                                 x-text="ct.platform_count + 'x'"></div>
                            <div class="flex-1 min-w-0">
                                <p class="text-sm font-bold text-white/90" x-text="'#' + ct.hashtag"></p>
                                <div class="flex items-center gap-2 text-xs text-white/40">
                                    <template x-for="[plat, count] in Object.entries(ct.platforms)" :key="plat">
                                        <span class="px-1.5 py-0.5 rounded-md text-[10px] font-semibold"
                                              :class="plat === 'tiktok' ? 'bg-white/10 text-white/60' : plat === 'youtube' ? 'bg-red-500/20 text-red-400' : 'bg-pink-500/20 text-pink-400'"
                                              x-text="plat + ': ' + count"></span>
                                    </template>
                                </div>
                            </div>
                            <div class="text-right flex-shrink-0">
                                <p class="text-sm font-bold text-brand-300" x-text="ct.avg_score"></p>
                                <p class="text-[10px] text-white/40" x-text="ct.total_videos + ' videos'"></p>
                            </div>
                        </div>
                    </template>
                    <template x-if="crossPlatform.length === 0">
                        <div class="text-center py-8 text-white/30 text-sm">Nenhum trend cross-platform encontrado</div>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- ===================== SATURATION TAB ===================== -->
    <div x-show="tab==='saturation'" class="space-y-4">
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="alert-triangle" class="w-5 h-5 text-red-400"></i> Verificador de Saturacao
                </h2>
                <p class="text-xs text-white/40 mt-1">Verifique se um tema/keyword ja esta saturado antes de criar conteudo</p>
            </div>
            <div class="p-5">
                <div class="flex gap-3 mb-6">
                    <div class="flex-1 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="saturationKeyword" @keyup.enter="checkSaturation()"
                               placeholder="Digite keyword ou tema (ex: ai house, construcao, grwm...)"
                               class="bg-transparent border-none outline-none text-sm text-white/80 placeholder:text-white/25 w-full">
                    </div>
                    <button @click="checkSaturation()" :disabled="!saturationKeyword || saturationLoading"
                            class="px-4 py-2.5 rounded-xl bg-red-500 text-white font-semibold text-sm hover:bg-red-600 transition disabled:opacity-50 flex items-center gap-2">
                        <i data-lucide="search" class="w-4 h-4" :class="saturationLoading && 'animate-spin'"></i>
                        Verificar
                    </button>
                </div>
                <!-- Result -->
                <template x-if="saturationResult">
                    <div class="glass-light rounded-xl p-5">
                        <div class="flex items-center justify-between mb-4">
                            <h3 class="text-base font-bold text-white/90" x-text="'\"' + saturationResult.keyword + '\"'"></h3>
                            <span class="px-3 py-1 rounded-full text-sm font-bold"
                                  :class="{
                                     'bg-red-500/20 text-red-400': saturationResult.label === 'Saturado',
                                     'bg-orange-500/20 text-orange-400': saturationResult.label === 'Alerta',
                                     'bg-emerald-500/20 text-emerald-400': saturationResult.label === 'Oportunidade',
                                  }" x-text="saturationResult.label"></span>
                        </div>
                        <!-- Score bar -->
                        <div class="mb-4">
                            <div class="flex justify-between text-xs text-white/40 mb-1">
                                <span>Saturacao</span>
                                <span x-text="saturationResult.saturation_score + '%'"></span>
                            </div>
                            <div class="h-3 bg-white/10 rounded-full overflow-hidden">
                                <div class="h-full rounded-full transition-all duration-500"
                                     :style="'width:' + saturationResult.saturation_score + '%'"
                                     :class="{
                                        'bg-red-500': saturationResult.saturation_score >= 70,
                                        'bg-orange-500': saturationResult.saturation_score >= 50 && saturationResult.saturation_score < 70,
                                        'bg-emerald-500': saturationResult.saturation_score < 50,
                                     }"></div>
                            </div>
                        </div>
                        <p class="text-sm text-white/70 mb-4" x-text="saturationResult.warning"></p>
                        <!-- Metrics comparison -->
                        <div class="grid grid-cols-2 gap-4">
                            <div class="bg-white/5 rounded-lg p-3">
                                <p class="text-[10px] text-white/40 mb-2">Primeira Metade</p>
                                <div class="space-y-1 text-xs">
                                    <div class="flex justify-between"><span class="text-white/50">Videos</span><span class="text-white/80 font-bold" x-text="saturationResult.metrics.first_half.count"></span></div>
                                    <div class="flex justify-between"><span class="text-white/50">Score</span><span class="text-white/80 font-bold" x-text="saturationResult.metrics.first_half.avg_score"></span></div>
                                    <div class="flex justify-between"><span class="text-white/50">Engajamento</span><span class="text-white/80 font-bold" x-text="saturationResult.metrics.first_half.avg_engagement + '%'"></span></div>
                                </div>
                            </div>
                            <div class="bg-white/5 rounded-lg p-3">
                                <p class="text-[10px] text-white/40 mb-2">Segunda Metade</p>
                                <div class="space-y-1 text-xs">
                                    <div class="flex justify-between"><span class="text-white/50">Videos</span><span class="text-white/80 font-bold" x-text="saturationResult.metrics.second_half.count"></span></div>
                                    <div class="flex justify-between"><span class="text-white/50">Score</span><span class="text-white/80 font-bold" x-text="saturationResult.metrics.second_half.avg_score"></span></div>
                                    <div class="flex justify-between"><span class="text-white/50">Engajamento</span><span class="text-white/80 font-bold" x-text="saturationResult.metrics.second_half.avg_engagement + '%'"></span></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </div>
    </div>

    <!-- ===================== TIMELINE TAB ===================== -->
    <div x-show="tab==='timeline'" class="space-y-4">
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="activity" class="w-5 h-5 text-emerald-400"></i> Trend Timeline
                </h2>
                <p class="text-xs text-white/40 mt-1">Ciclo de vida de um trend: nascimento, crescimento, pico e declinio</p>
            </div>
            <div class="p-5">
                <div class="flex gap-3 mb-6">
                    <div class="flex-1 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="timelineKeyword" @keyup.enter="loadTimeline()"
                               placeholder="Keyword para analisar timeline (ex: ai house, challenge...)"
                               class="bg-transparent border-none outline-none text-sm text-white/80 placeholder:text-white/25 w-full">
                    </div>
                    <button @click="loadTimeline()" :disabled="!timelineKeyword || timelineLoading"
                            class="px-4 py-2.5 rounded-xl bg-emerald-500 text-white font-semibold text-sm hover:bg-emerald-600 transition disabled:opacity-50 flex items-center gap-2">
                        <i data-lucide="activity" class="w-4 h-4" :class="timelineLoading && 'animate-spin'"></i>
                        Analisar
                    </button>
                </div>
                <template x-if="timelineResult">
                    <div>
                        <div class="flex items-center gap-4 mb-4">
                            <h3 class="text-sm font-bold text-white/90" x-text="'\"' + timelineResult.keyword + '\"'"></h3>
                            <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase"
                                  :class="{
                                     'bg-emerald-500/20 text-emerald-400': timelineResult.phase === 'emerging',
                                     'bg-orange-500/20 text-orange-400': timelineResult.phase === 'growing',
                                     'bg-red-500/20 text-red-400': timelineResult.phase === 'peak',
                                     'bg-gray-500/20 text-gray-400': timelineResult.phase === 'declining',
                                  }" x-text="timelineResult.phase"></span>
                            <span class="text-xs text-white/40" x-text="timelineResult.total_videos + ' videos em ' + timelineResult.days_analyzed + ' dias'"></span>
                        </div>
                        <!-- Timeline bars -->
                        <div class="space-y-1">
                            <template x-for="day in timelineResult.timeline" :key="day.date">
                                <div class="flex items-center gap-2 text-xs">
                                    <span class="text-white/40 w-20 flex-shrink-0" x-text="day.date.slice(5)"></span>
                                    <div class="flex-1 h-5 bg-white/5 rounded-md overflow-hidden relative">
                                        <div class="h-full rounded-md transition-all"
                                             :style="'width:' + Math.min(100, (day.video_count / Math.max(...timelineResult.timeline.map(d=>d.video_count))) * 100) + '%'"
                                             :class="day.avg_score >= 60 ? 'bg-gradient-to-r from-orange-500 to-red-500' : day.avg_score >= 30 ? 'bg-gradient-to-r from-blue-500 to-cyan-500' : 'bg-white/20'">
                                        </div>
                                        <span class="absolute right-1 top-0.5 text-[10px] text-white/60" x-text="day.video_count + ' (' + day.avg_score + ')'"></span>
                                    </div>
                                </div>
                            </template>
                        </div>
                        <template x-if="timelineResult.timeline.length === 0">
                            <div class="text-center py-4 text-white/30 text-sm">Nenhum dado encontrado para esta keyword</div>
                        </template>
                    </div>
                </template>
            </div>
        </div>
    </div>

    <!-- ===================== PREDICTIONS TAB ===================== -->
    <div x-show="tab==='predictions'" class="space-y-4">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
            <!-- Best Time -->
            <div class="glass-card rounded-2xl">
                <div class="p-5 border-b border-white/5">
                    <h2 class="text-base font-bold text-white/90 flex items-center gap-2">
                        <i data-lucide="clock" class="w-4 h-4 text-yellow-400"></i> Melhor Horario para Postar
                    </h2>
                </div>
                <div class="p-5">
                    <template x-if="bestTime">
                        <div>
                            <div class="flex items-center gap-4 mb-4">
                                <div class="w-16 h-16 rounded-2xl gradient-fire flex flex-col items-center justify-center">
                                    <span class="text-xl font-bold text-white" x-text="bestTime.best_hour + ':00'"></span>
                                    <span class="text-[10px] text-white/70" x-text="bestTime.best_day"></span>
                                </div>
                                <p class="text-sm text-white/70" x-text="bestTime.recommendation"></p>
                            </div>
                            <!-- Hour bars -->
                            <div class="flex items-end gap-0.5 h-24">
                                <template x-for="h in 24" :key="h">
                                    <div class="flex-1 rounded-t-sm transition-all cursor-default group relative"
                                         :style="'height:' + (bestTime.hours[h-1]?.avg_score > 0 ? Math.max(8, (bestTime.hours[h-1].avg_score / Math.max(...Object.values(bestTime.hours).map(x=>x.avg_score||0))) * 100) : 4) + '%'"
                                         :class="(h-1) === bestTime.best_hour ? 'bg-orange-500' : bestTime.hours[h-1]?.count > 0 ? 'bg-brand-500/60' : 'bg-white/10'"
                                         :title="(h-1) + ':00 - Score: ' + (bestTime.hours[h-1]?.avg_score || 0) + ' (' + (bestTime.hours[h-1]?.count || 0) + ' videos)'">
                                    </div>
                                </template>
                            </div>
                            <div class="flex justify-between text-[10px] text-white/30 mt-1">
                                <span>0h</span><span>6h</span><span>12h</span><span>18h</span><span>23h</span>
                            </div>
                            <p class="text-[10px] text-white/30 text-center mt-1" x-text="bestTime.total_analyzed + ' videos analisados'"></p>
                        </div>
                    </template>
                    <template x-if="!bestTime">
                        <div class="text-center py-8 text-white/30 text-sm">Carregando...</div>
                    </template>
                </div>
            </div>

            <!-- Best Platform -->
            <div class="glass-card rounded-2xl">
                <div class="p-5 border-b border-white/5">
                    <h2 class="text-base font-bold text-white/90 flex items-center gap-2">
                        <i data-lucide="trophy" class="w-4 h-4 text-yellow-400"></i> Melhor Plataforma
                    </h2>
                </div>
                <div class="p-5">
                    <div class="flex gap-3 mb-4">
                        <div class="flex-1 flex items-center glass-light rounded-xl px-3 py-2">
                            <input type="text" x-model="platformKeyword" @keyup.enter="loadBestPlatform()"
                                   placeholder="Keyword (ou vazio para geral)"
                                   class="bg-transparent border-none outline-none text-sm text-white/80 placeholder:text-white/25 w-full">
                        </div>
                        <button @click="loadBestPlatform()" class="px-3 py-2 rounded-xl bg-yellow-500 text-black font-semibold text-sm hover:bg-yellow-400 transition">
                            <i data-lucide="search" class="w-4 h-4"></i>
                        </button>
                    </div>
                    <template x-if="bestPlatform">
                        <div>
                            <p class="text-sm text-white/70 mb-4" x-text="bestPlatform.recommendation"></p>
                            <div class="space-y-2">
                                <template x-for="[plat, data] in Object.entries(bestPlatform.platforms)" :key="plat">
                                    <div class="flex items-center gap-3 p-3 rounded-xl"
                                         :class="plat === bestPlatform.best_platform ? 'bg-yellow-500/10 border border-yellow-500/30' : 'glass-light'">
                                        <span class="text-lg"
                                              x-text="plat === 'tiktok' ? '🎵' : plat === 'youtube' ? '▶️' : '📷'"></span>
                                        <div class="flex-1">
                                            <span class="text-sm font-bold text-white/90 uppercase" x-text="plat"></span>
                                            <div class="flex gap-3 text-xs text-white/40">
                                                <span x-text="data.video_count + ' videos'"></span>
                                                <span class="text-brand-300" x-text="'Score: ' + data.avg_score"></span>
                                            </div>
                                        </div>
                                        <span x-show="plat === bestPlatform.best_platform" class="px-2 py-0.5 rounded-full text-[10px] font-bold bg-yellow-500/20 text-yellow-400">MELHOR</span>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </template>
                    <template x-if="!bestPlatform">
                        <div class="text-center py-8 text-white/30 text-sm">Carregando...</div>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- ===================== HASHTAGS TAB (existing) ===================== -->
    <div x-show="tab==='hashtags'" class="space-y-4">
        <!-- Top Hashtags -->
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="flame" class="w-5 h-5 text-orange-400"></i> Hashtags em Alta
                </h2>
                <p class="text-xs text-white/40 mt-1">Baseado nos videos coletados nos ultimos 30 dias</p>
            </div>
            <div class="p-5">
                {% if hashtags %}
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                    {% for h in hashtags %}
                    <div class="flex items-center gap-3 p-3 rounded-xl glass-light hover:border-brand-500/30 transition group cursor-default">
                        <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center text-white font-bold text-sm flex-shrink-0">
                            {{ loop.index }}
                        </div>
                        <div class="flex-1 min-w-0">
                            <p class="font-semibold text-white/90 truncate text-sm">#{{ h.name }}</p>
                            <div class="flex items-center gap-3 text-xs text-white/40">
                                <span>{{ h.count }} videos</span>
                                <span class="text-brand-300">Score: {{ h.avg_viral_score }}</span>
                            </div>
                        </div>
                        <div class="text-right">
                            <p class="text-sm font-bold text-accent-green">
                                {% if h.avg_views >= 1000000 %}{{ "%.1f"|format(h.avg_views / 1000000) }}M
                                {% elif h.avg_views >= 1000 %}{{ "%.1f"|format(h.avg_views / 1000) }}K
                                {% else %}{{ h.avg_views }}{% endif %}
                            </p>
                            <p class="text-[10px] text-white/30">views/video</p>
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% else %}
                <div class="flex flex-col items-center justify-center py-16 text-center">
                    <div class="w-20 h-20 rounded-2xl glass-light flex items-center justify-center mb-5">
                        <i data-lucide="hash" class="w-10 h-10 text-white/20"></i>
                    </div>
                    <h3 class="text-lg font-bold text-white/60 mb-2">Nenhuma hashtag encontrada</h3>
                    <p class="text-sm text-white/30 max-w-md">Colete videos primeiro para ver as hashtags em alta.</p>
                    <a href="/viral-scanner" class="inline-block mt-4 px-6 py-2.5 rounded-xl gradient-brand text-white text-sm font-semibold">Ir ao Scanner</a>
                </div>
                {% endif %}
            </div>
        </div>

        <!-- Content Patterns (charts) -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
            <div class="glass-card rounded-2xl">
                <div class="p-5 border-b border-white/5">
                    <h2 class="text-base font-bold text-white/90 flex items-center gap-2">
                        <i data-lucide="timer" class="w-4 h-4 text-brand-400"></i> Duracao dos Virais
                    </h2>
                </div>
                <div class="p-5">
                    {% if patterns.total_analyzed > 0 %}
                    <canvas id="durationChart" height="200"></canvas>
                    {% else %}
                    <div class="text-center py-8 text-white/30 text-sm">Dados insuficientes</div>
                    {% endif %}
                </div>
            </div>
            <div class="glass-card rounded-2xl">
                <div class="p-5 border-b border-white/5">
                    <h2 class="text-base font-bold text-white/90 flex items-center gap-2">
                        <i data-lucide="bar-chart" class="w-4 h-4 text-green-400"></i> Distribuicao de Scores
                    </h2>
                </div>
                <div class="p-5">
                    {% if patterns.score_distribution %}
                    <canvas id="scoreChart" height="200"></canvas>
                    {% else %}
                    <div class="text-center py-8 text-white/30 text-sm">Dados insuficientes</div>
                    {% endif %}
                </div>
            </div>
        </div>

        <!-- Platform Performance -->
        {% if patterns.platform_performance %}
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-base font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="trophy" class="w-4 h-4 text-yellow-400"></i> Performance por Plataforma
                </h2>
            </div>
            <div class="p-5">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    {% for platform_name, stats in patterns.platform_performance.items() %}
                    <div class="glass-light rounded-xl p-4 border-l-4 {% if platform_name == 'youtube' %}border-red-500{% elif platform_name == 'tiktok' %}border-white/40{% else %}border-pink-500{% endif %}">
                        <div class="flex items-center gap-2 mb-3">
                            <span class="font-bold text-white/90 text-sm uppercase">{{ platform_name }}</span>
                        </div>
                        <div class="space-y-2 text-sm">
                            <div class="flex justify-between"><span class="text-white/40">Videos</span><span class="font-bold text-white/80">{{ stats.count }}</span></div>
                            <div class="flex justify-between"><span class="text-white/40">Score Medio</span><span class="font-bold text-brand-300">{{ stats.avg_score }}</span></div>
                            <div class="flex justify-between"><span class="text-white/40">Views Medias</span><span class="font-bold text-white/80">
                                {% if stats.avg_views >= 1000000 %}{{ "%.1f"|format(stats.avg_views / 1000000) }}M
                                {% elif stats.avg_views >= 1000 %}{{ "%.1f"|format(stats.avg_views / 1000) }}K
                                {% else %}{{ stats.avg_views }}{% endif %}
                            </span></div>
                            <div class="flex justify-between"><span class="text-white/40">Engajamento</span><span class="font-bold text-accent-green">{{ stats.avg_engagement }}%</span></div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
        {% endif %}
    </div>

    <!-- ===================== MICRO-TRENDS TAB ===================== -->
    <div x-show="tab==='microtrends'" class="space-y-4">
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="sparkles" class="w-5 h-5 text-teal-400"></i> Micro-Trends (Deteccao Precoce)
                </h2>
                <p class="text-xs text-white/40 mt-1">Hashtags NOVAS que surgiram nas ultimas 48h com forte engajamento</p>
            </div>
            <div x-show="microTrendsLoading" class="p-8 text-center">
                <div class="w-5 h-5 border-2 border-teal-400 border-t-transparent rounded-full animate-spin mx-auto"></div>
            </div>
            <div class="p-5">
                <div x-show="!microTrendsLoading && microTrends.length > 0" class="space-y-3">
                    <template x-for="mt in microTrends" :key="mt.hashtag">
                        <div class="bg-white/5 rounded-xl p-4 hover:bg-white/10 transition">
                            <div class="flex items-center justify-between">
                                <div class="flex items-center gap-3">
                                    <span class="text-lg font-bold text-teal-400">#<span x-text="mt.hashtag"></span></span>
                                    <span x-show="mt.is_cross_platform" class="text-[10px] bg-purple-500/20 text-purple-400 rounded-full px-2 py-0.5">CROSS-PLATFORM</span>
                                </div>
                                <span class="text-xs px-2 py-0.5 rounded-full"
                                      :class="mt.potential === 'alto' ? 'bg-emerald-500/20 text-emerald-400' : mt.potential === 'medio' ? 'bg-yellow-500/20 text-yellow-400' : 'bg-white/10 text-white/40'"
                                      x-text="mt.potential.toUpperCase()"></span>
                            </div>
                            <div class="flex items-center gap-4 mt-2 text-xs text-white/40">
                                <span x-text="mt.video_count + ' videos'"></span>
                                <span x-text="'Score: ' + mt.avg_score"></span>
                                <span x-text="fmtNum(mt.total_views) + ' views'"></span>
                                <span x-text="mt.platforms.join(', ')"></span>
                            </div>
                        </div>
                    </template>
                </div>
                <div x-show="!microTrendsLoading && microTrends.length === 0" class="text-center text-white/30 text-sm py-8">Nenhuma micro-trend detectada</div>
            </div>
        </div>
    </div>

    <!-- ===================== ALGORITHM CHANGES TAB ===================== -->
    <div x-show="tab==='algorithm'" class="space-y-4">
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="cpu" class="w-5 h-5 text-rose-400"></i> Detector de Mudancas no Algoritmo
                </h2>
                <p class="text-xs text-white/40 mt-1">Monitora shifts de engagement e viral score por plataforma</p>
            </div>
            <div x-show="algoLoading" class="p-8 text-center">
                <div class="w-5 h-5 border-2 border-rose-400 border-t-transparent rounded-full animate-spin mx-auto"></div>
            </div>
            <div x-show="!algoLoading && algoData" class="p-5">
                <div class="mb-4 p-4 rounded-xl" :class="algoData?.has_changes ? 'bg-rose-500/10 border border-rose-500/20' : 'bg-emerald-500/10 border border-emerald-500/20'">
                    <p class="text-sm font-bold" :class="algoData?.has_changes ? 'text-rose-400' : 'text-emerald-400'" x-text="algoData?.recommendation"></p>
                </div>
                <div x-show="algoData?.anomalies?.length > 0" class="space-y-2 mb-4">
                    <p class="text-xs text-white/50 font-bold">ANOMALIAS DETECTADAS</p>
                    <template x-for="a in algoData?.anomalies || []" :key="a.description">
                        <div class="bg-white/5 rounded-xl p-3 flex items-center gap-3">
                            <i data-lucide="alert-triangle" class="w-4 h-4 text-rose-400 flex-shrink-0"></i>
                            <div>
                                <p class="text-sm text-white/80" x-text="a.description"></p>
                                <p class="text-xs text-white/40" x-text="a.possible_cause"></p>
                            </div>
                            <span class="text-lg font-bold flex-shrink-0" :class="a.direction === 'up' ? 'text-emerald-400' : 'text-red-400'"
                                  x-text="(a.direction === 'up' ? '+' : '') + a.change_percent + '%'"></span>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- ===================== MUSIC PATTERNS TAB ===================== -->
    <div x-show="tab==='music'" class="space-y-4">
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="music" class="w-5 h-5 text-violet-400"></i> Padroes de Musica/Som
                </h2>
                <p class="text-xs text-white/40 mt-1">Sons e generos musicais que estao impulsionando videos virais</p>
            </div>
            <div x-show="musicLoading" class="p-8 text-center">
                <div class="w-5 h-5 border-2 border-violet-400 border-t-transparent rounded-full animate-spin mx-auto"></div>
            </div>
            <div x-show="!musicLoading && musicData" class="p-5">
                <div class="bg-violet-500/10 border border-violet-500/20 rounded-xl p-4 mb-4">
                    <p class="text-sm text-violet-400" x-text="musicData?.recommendation"></p>
                    <p class="text-xs text-white/40 mt-1" x-text="musicData?.total_analyzed + ' videos analisados | ' + musicData?.commerce_music_pct + '% com musica de comercio'"></p>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <template x-for="p in musicData?.patterns || []" :key="p.pattern">
                        <div class="bg-white/5 rounded-xl p-4 hover:bg-white/10 transition">
                            <div class="flex items-center justify-between mb-2">
                                <p class="text-sm font-bold text-white/90" x-text="p.label"></p>
                                <span class="text-xs text-violet-400" x-text="p.video_count + ' videos'"></span>
                            </div>
                            <div class="flex items-center gap-3 text-xs text-white/40">
                                <span x-text="'Score: ' + p.avg_score"></span>
                                <span x-text="fmtNum(p.total_views) + ' views'"></span>
                            </div>
                            <div x-show="p.examples?.length > 0" class="mt-2">
                                <template x-for="ex in p.examples" :key="ex.title">
                                    <p class="text-[10px] text-white/30 truncate" x-text="'- ' + ex.title"></p>
                                </template>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- ===================== GLOBAL MAP TAB ===================== -->
    <div x-show="tab==='globalmap'" class="space-y-4">
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="globe" class="w-5 h-5 text-sky-400"></i> Mapa Global de Tendencias
                </h2>
                <p class="text-xs text-white/40 mt-1">Tendencias por pais/regiao e idioma</p>
            </div>
            <div x-show="globalMapLoading" class="p-8 text-center">
                <div class="w-5 h-5 border-2 border-sky-400 border-t-transparent rounded-full animate-spin mx-auto"></div>
            </div>
            <div x-show="!globalMapLoading && globalMapData" class="p-5">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <p class="text-xs text-white/50 font-bold mb-3">POR REGIAO/PAIS</p>
                        <div class="space-y-2">
                            <template x-for="r in globalMapData?.regions || []" :key="r.code">
                                <div class="bg-white/5 rounded-xl p-3 flex items-center justify-between">
                                    <div>
                                        <p class="text-sm font-bold text-white/90">
                                            <span class="text-sky-400" x-text="r.code"></span>
                                            <span class="text-white/50 ml-1" x-text="r.name"></span>
                                        </p>
                                        <p class="text-[10px] text-white/40" x-text="r.video_count + ' videos | Score: ' + r.avg_score"></p>
                                    </div>
                                    <span class="text-xs text-sky-400 font-bold" x-text="fmtNum(r.total_views) + ' views'"></span>
                                </div>
                            </template>
                        </div>
                    </div>
                    <div>
                        <p class="text-xs text-white/50 font-bold mb-3">POR IDIOMA</p>
                        <div class="space-y-2">
                            <template x-for="l in globalMapData?.languages || []" :key="l.code">
                                <div class="bg-white/5 rounded-xl p-3 flex items-center justify-between">
                                    <p class="text-sm font-bold text-white/90" x-text="l.code.toUpperCase()"></p>
                                    <div class="text-right">
                                        <span class="text-xs text-white/60" x-text="l.video_count + ' videos'"></span>
                                        <span class="text-xs text-sky-400 ml-2" x-text="'Score: ' + l.avg_score"></span>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ===================== WEEKLY REPORT TAB ===================== -->
    <div x-show="tab==='report'" class="space-y-4">
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5 flex items-center justify-between">
                <div>
                    <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                        <i data-lucide="file-text" class="w-5 h-5 text-amber-400"></i> Relatorio Semanal
                    </h2>
                    <p class="text-xs text-white/40 mt-1">Resumo completo de tendencias dos ultimos 7 dias</p>
                </div>
                <div class="flex gap-2">
                    <button @click="sendTelegramReport()" class="px-3 py-2 rounded-xl bg-blue-500/20 text-blue-400 text-xs font-medium hover:bg-blue-500/30 transition flex items-center gap-1">
                        <i data-lucide="send" class="w-3 h-3"></i> Telegram
                    </button>
                </div>
            </div>
            <div x-show="reportLoading" class="p-8 text-center">
                <div class="w-5 h-5 border-2 border-amber-400 border-t-transparent rounded-full animate-spin mx-auto"></div>
            </div>
            <div x-show="!reportLoading && weeklyReport" class="p-5 space-y-4">
                <div class="bg-amber-500/10 border border-amber-500/20 rounded-xl p-4">
                    <p class="text-sm text-amber-400 font-bold" x-text="weeklyReport?.summary"></p>
                    <p class="text-[10px] text-white/30 mt-1" x-text="'Gerado em: ' + weeklyReport?.generated_at?.substring(0, 16)"></p>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <p class="text-xs text-white/50 font-bold mb-2">NICHOS EM ALTA</p>
                        <template x-for="n in weeklyReport?.hot_niches || []" :key="n.name">
                            <div class="bg-white/5 rounded-lg p-2 mb-1 flex justify-between text-xs">
                                <span class="text-white/80" x-text="n.name"></span>
                                <span class="text-emerald-400 font-bold" x-text="'+' + n.growth + '%'"></span>
                            </div>
                        </template>
                    </div>
                    <div>
                        <p class="text-xs text-white/50 font-bold mb-2">FORMATOS EM ALTA</p>
                        <template x-for="f in weeklyReport?.hot_formats || []" :key="f.format">
                            <div class="bg-white/5 rounded-lg p-2 mb-1 flex justify-between text-xs">
                                <span class="text-white/80" x-text="f.format"></span>
                                <span class="text-orange-400 font-bold" x-text="'+' + f.growth_percent + '%'"></span>
                            </div>
                        </template>
                    </div>
                </div>
                <div>
                    <p class="text-xs text-white/50 font-bold mb-2">TOP CREATORS</p>
                    <div class="flex flex-wrap gap-2">
                        <template x-for="c in weeklyReport?.top_creators || []" :key="c.id">
                            <span class="bg-cyan-500/10 text-cyan-400 rounded-lg px-3 py-1 text-xs" x-text="'@' + c.username + ' (' + fmtNum(c.total_views) + ' views)'"></span>
                        </template>
                    </div>
                </div>
                <div>
                    <p class="text-xs text-white/50 font-bold mb-2">MICRO-TRENDS EMERGENTES</p>
                    <div class="flex flex-wrap gap-2">
                        <template x-for="mt in weeklyReport?.micro_trends || []" :key="mt.hashtag">
                            <span class="bg-teal-500/10 text-teal-400 rounded-lg px-3 py-1 text-xs" x-text="'#' + mt.hashtag + ' (' + mt.video_count + ' vids)'"></span>
                        </template>
                    </div>
                </div>
                <div x-show="weeklyReport?.algorithm_changes?.length > 0">
                    <p class="text-xs text-rose-400 font-bold mb-2">MUDANCAS NO ALGORITMO</p>
                    <template x-for="a in weeklyReport?.algorithm_changes || []" :key="a.description">
                        <div class="bg-rose-500/10 rounded-lg p-2 mb-1 text-xs text-rose-300" x-text="a.description"></div>
                    </template>
                </div>
                <!-- AI Narrative -->
                <div x-show="weeklyReport?.ai_narrative && weeklyReport.ai_narrative !== 'Narrativa IA indisponivel.'" class="bg-violet-500/5 border border-violet-500/20 rounded-xl p-4 mt-4">
                    <h4 class="text-xs font-bold text-violet-400 mb-2 flex items-center gap-1"><i data-lucide="sparkles" class="w-3 h-3"></i> Narrativa IA</h4>
                    <p class="text-xs text-white/60 whitespace-pre-line leading-relaxed" x-text="weeklyReport.ai_narrative"></p>
                </div>
            </div>
        </div>
    </div>

    <!-- ===================== STEPPS TAB ===================== -->
    <div x-show="tab==='stepps'" class="space-y-4">
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="hexagon" class="w-5 h-5 text-indigo-400"></i> STEPPS Virality Score
                </h2>
                <p class="text-xs text-white/40 mt-1">Framework de Jonah Berger - 6 principios de viralidade</p>
            </div>
            <div class="p-5">
                <!-- Search -->
                <div class="flex gap-3 mb-4">
                    <input type="text" x-model="steppsKeyword" placeholder="Keyword ou hashtag..." class="flex-1 bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:border-indigo-500 outline-none" @keydown.enter="loadStepps()">
                    <button @click="loadStepps()" :disabled="steppsLoading || !steppsKeyword" class="px-4 py-2 rounded-lg bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white text-sm font-bold transition">
                        <template x-if="!steppsLoading">Analisar</template>
                        <template x-if="steppsLoading"><div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div></template>
                    </button>
                </div>

                <!-- Result -->
                <div x-show="steppsData" class="space-y-4">
                    <!-- Score -->
                    <div class="flex items-center gap-4 bg-indigo-500/10 border border-indigo-500/20 rounded-xl p-4">
                        <div class="text-center">
                            <p class="text-3xl font-black" :class="(steppsData?.score||0) >= 70 ? 'text-indigo-400' : (steppsData?.score||0) >= 40 ? 'text-yellow-400' : 'text-white/40'" x-text="steppsData?.score || 0"></p>
                            <p class="text-[10px] text-white/40">Score /100</p>
                        </div>
                        <div>
                            <p class="text-sm font-bold" :class="(steppsData?.score||0) >= 70 ? 'text-indigo-400' : 'text-white/60'" x-text="steppsData?.label"></p>
                            <p class="text-[10px] text-white/40" x-text="steppsData?.video_count + ' videos | ' + (steppsData?.platforms?.join(', ') || '')"></p>
                            <span x-show="steppsData?.cross_platform_bonus" class="text-[9px] bg-indigo-500/20 text-indigo-300 px-2 py-0.5 rounded-full">+10% cross-platform</span>
                        </div>
                    </div>

                    <!-- Radar Chart Canvas -->
                    <div class="bg-white/5 rounded-xl p-4">
                        <canvas id="steppsChart" style="max-height: 300px;"></canvas>
                    </div>

                    <!-- Breakdown Cards -->
                    <div class="grid grid-cols-2 md:grid-cols-3 gap-3">
                        <div class="bg-white/5 rounded-xl p-3 text-center">
                            <p class="text-lg font-bold text-blue-400" x-text="steppsData?.breakdown?.social_currency || 0"></p>
                            <p class="text-[9px] text-white/40">Social Currency</p>
                            <p class="text-[8px] text-white/20">Exclusividade, status</p>
                        </div>
                        <div class="bg-white/5 rounded-xl p-3 text-center">
                            <p class="text-lg font-bold text-green-400" x-text="steppsData?.breakdown?.triggers || 0"></p>
                            <p class="text-[9px] text-white/40">Triggers</p>
                            <p class="text-[8px] text-white/20">Frequencia, lembretes</p>
                        </div>
                        <div class="bg-white/5 rounded-xl p-3 text-center">
                            <p class="text-lg font-bold text-red-400" x-text="steppsData?.breakdown?.emotion || 0"></p>
                            <p class="text-[9px] text-white/40">Emotion</p>
                            <p class="text-[8px] text-white/20">Intensidade emocional</p>
                        </div>
                        <div class="bg-white/5 rounded-xl p-3 text-center">
                            <p class="text-lg font-bold text-purple-400" x-text="steppsData?.breakdown?.public || 0"></p>
                            <p class="text-[9px] text-white/40">Public</p>
                            <p class="text-[8px] text-white/20">Comportamento visivel</p>
                        </div>
                        <div class="bg-white/5 rounded-xl p-3 text-center">
                            <p class="text-lg font-bold text-yellow-400" x-text="steppsData?.breakdown?.practical_value || 0"></p>
                            <p class="text-[9px] text-white/40">Practical Value</p>
                            <p class="text-[8px] text-white/20">Utilidade, dicas</p>
                        </div>
                        <div class="bg-white/5 rounded-xl p-3 text-center">
                            <p class="text-lg font-bold text-orange-400" x-text="steppsData?.breakdown?.stories || 0"></p>
                            <p class="text-[9px] text-white/40">Stories</p>
                            <p class="text-[8px] text-white/20">Narrativa, jornada</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ===================== RECEITA TAB ===================== -->
    <div x-show="tab==='revenue'" class="space-y-4">
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="dollar-sign" class="w-5 h-5 text-emerald-400"></i> Predicao de Receita por Trend
                </h2>
                <p class="text-xs text-white/40 mt-1">Estime o potencial de monetizacao de uma tendencia</p>
            </div>
            <div class="p-5">
                <div class="flex gap-3 mb-4">
                    <input type="text" x-model="revenueKeyword" placeholder="Keyword..." class="flex-1 bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:border-emerald-500 outline-none" @keydown.enter="loadRevenue()">
                    <select x-model="revenuePlatform" class="bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:border-emerald-500 outline-none">
                        <option value="tiktok">TikTok</option>
                        <option value="youtube">YouTube</option>
                        <option value="instagram">Instagram</option>
                    </select>
                    <button @click="loadRevenue()" :disabled="revenueLoading || !revenueKeyword" class="px-4 py-2 rounded-lg bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white text-sm font-bold transition">
                        <template x-if="!revenueLoading">Calcular</template>
                        <template x-if="revenueLoading"><div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div></template>
                    </button>
                </div>

                <div x-show="revenueData" class="space-y-4">
                    <!-- Current Revenue -->
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                        <div class="bg-emerald-500/10 border border-emerald-500/20 rounded-xl p-4 text-center">
                            <p class="text-lg font-bold text-emerald-400" x-text="'R$' + (revenueData?.revenue?.ad_revenue || 0).toFixed(2)"></p>
                            <p class="text-[9px] text-white/40">Receita Ads</p>
                        </div>
                        <div class="bg-blue-500/10 border border-blue-500/20 rounded-xl p-4 text-center">
                            <p class="text-lg font-bold text-blue-400" x-text="'R$' + (revenueData?.revenue?.fund_revenue || 0).toFixed(2)"></p>
                            <p class="text-[9px] text-white/40">Creator Fund</p>
                        </div>
                        <div class="bg-purple-500/10 border border-purple-500/20 rounded-xl p-4 text-center">
                            <p class="text-lg font-bold text-purple-400" x-text="'R$' + (revenueData?.revenue?.affiliate_estimated || 0).toFixed(2)"></p>
                            <p class="text-[9px] text-white/40">Afiliados Est.</p>
                        </div>
                        <div class="bg-yellow-500/10 border border-yellow-500/20 rounded-xl p-4 text-center">
                            <p class="text-lg font-bold text-yellow-400" x-text="'R$' + (revenueData?.revenue?.total_current || 0).toFixed(2)"></p>
                            <p class="text-[9px] text-white/40">Total Atual</p>
                        </div>
                    </div>

                    <!-- 30-day Projection -->
                    <div class="bg-white/5 rounded-xl p-4">
                        <h4 class="text-xs font-bold text-white/50 mb-3">PROJECAO 30 DIAS</h4>
                        <div class="grid grid-cols-3 gap-4 text-center">
                            <div>
                                <p class="text-sm font-bold text-white/80" x-text="(revenueData?.projection_30d?.projected_views || 0).toLocaleString()"></p>
                                <p class="text-[9px] text-white/40">Views Projetados</p>
                            </div>
                            <div>
                                <p class="text-sm font-bold text-emerald-400" x-text="'R$' + (revenueData?.projection_30d?.projected_revenue || 0).toFixed(2)"></p>
                                <p class="text-[9px] text-white/40">Receita Projetada</p>
                            </div>
                            <div>
                                <p class="text-sm font-bold" :class="revenueData?.projection_30d?.trend_direction === 'growing' ? 'text-emerald-400' : revenueData?.projection_30d?.trend_direction === 'declining' ? 'text-red-400' : 'text-yellow-400'" x-text="revenueData?.projection_30d?.trend_direction === 'growing' ? 'Crescendo' : revenueData?.projection_30d?.trend_direction === 'declining' ? 'Declinando' : 'Estavel'"></p>
                                <p class="text-[9px] text-white/40" x-text="'Momentum: ' + (revenueData?.projection_30d?.momentum_factor || 1) + 'x'"></p>
                            </div>
                        </div>
                    </div>

                    <!-- Meta Info -->
                    <div class="flex flex-wrap gap-2 text-[10px] text-white/30">
                        <span x-text="revenueData?.video_count + ' videos analisados'"></span>
                        <span>|</span>
                        <span x-text="'Nicho: ' + (revenueData?.niche_detected || 'geral')"></span>
                        <span>|</span>
                        <span x-text="revenueData?.total_views?.toLocaleString() + ' views totais'"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ===================== SENTIMENTO TAB ===================== -->
    <div x-show="tab==='sentiment'" class="space-y-4">
        <div class="glass-card rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="heart" class="w-5 h-5 text-pink-400"></i> Sentimento vs Viralidade
                </h2>
                <p class="text-xs text-white/40 mt-1">Correlacao entre emocao do conteudo e performance viral</p>
            </div>
            <div class="p-5">
                <div class="flex gap-3 mb-4">
                    <input type="text" x-model="sentimentKeyword" placeholder="Keyword..." class="flex-1 bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:border-pink-500 outline-none" @keydown.enter="loadSentimentVirality()">
                    <button @click="loadSentimentVirality()" :disabled="sentimentLoading || !sentimentKeyword" class="px-4 py-2 rounded-lg bg-pink-600 hover:bg-pink-500 disabled:opacity-50 text-white text-sm font-bold transition">
                        <template x-if="!sentimentLoading">Analisar</template>
                        <template x-if="sentimentLoading"><div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div></template>
                    </button>
                </div>

                <div x-show="sentimentData" class="space-y-4">
                    <!-- EVI Score -->
                    <div class="flex items-center gap-4 rounded-xl p-4" :class="(sentimentData?.emotional_virality_index || 0) > 20 ? 'bg-pink-500/10 border border-pink-500/20' : 'bg-white/5'">
                        <div class="text-center">
                            <p class="text-3xl font-black" :class="(sentimentData?.emotional_virality_index||0) > 20 ? 'text-pink-400' : (sentimentData?.emotional_virality_index||0) > 0 ? 'text-yellow-400' : 'text-white/40'" x-text="(sentimentData?.emotional_virality_index || 0).toFixed(1)"></p>
                            <p class="text-[10px] text-white/40">EVI Score</p>
                        </div>
                        <div>
                            <p class="text-sm font-bold text-white/70" x-text="sentimentData?.evi_label"></p>
                            <p class="text-[10px] text-white/40" x-text="sentimentData?.video_count + ' videos analisados'"></p>
                        </div>
                    </div>

                    <!-- Sentiment Distribution -->
                    <div class="grid grid-cols-3 gap-3">
                        <div class="bg-emerald-500/10 rounded-xl p-4 text-center">
                            <p class="text-lg font-bold text-emerald-400" x-text="sentimentData?.sentiment_distribution?.positive?.count || 0"></p>
                            <p class="text-[9px] text-white/40">Positivos</p>
                            <p class="text-[10px] text-emerald-400" x-text="'Avg Score: ' + (sentimentData?.sentiment_distribution?.positive?.avg_viral_score || 0)"></p>
                        </div>
                        <div class="bg-white/5 rounded-xl p-4 text-center">
                            <p class="text-lg font-bold text-white/40" x-text="sentimentData?.sentiment_distribution?.neutral?.count || 0"></p>
                            <p class="text-[9px] text-white/40">Neutros</p>
                            <p class="text-[10px] text-white/30" x-text="'Avg Score: ' + (sentimentData?.sentiment_distribution?.neutral?.avg_viral_score || 0)"></p>
                        </div>
                        <div class="bg-red-500/10 rounded-xl p-4 text-center">
                            <p class="text-lg font-bold text-red-400" x-text="sentimentData?.sentiment_distribution?.negative?.count || 0"></p>
                            <p class="text-[9px] text-white/40">Negativos</p>
                            <p class="text-[10px] text-red-400" x-text="'Avg Score: ' + (sentimentData?.sentiment_distribution?.negative?.avg_viral_score || 0)"></p>
                        </div>
                    </div>

                    <!-- Sentiment Bar Chart -->
                    <div class="bg-white/5 rounded-xl p-4">
                        <canvas id="sentimentChart" style="max-height: 250px;"></canvas>
                    </div>

                    <!-- Top Viral by Sentiment -->
                    <div>
                        <p class="text-xs text-white/50 font-bold mb-2">TOP VIDEOS POR SENTIMENTO</p>
                        <div class="space-y-1">
                            <template x-for="item in (sentimentData?.top_viral_sentiments || []).slice(0, 5)" :key="item.title">
                                <div class="bg-white/5 rounded-lg p-2 flex items-center justify-between text-xs">
                                    <span class="text-white/70 truncate flex-1 mr-2" x-text="item.title"></span>
                                    <div class="flex items-center gap-2 shrink-0">
                                        <span class="px-2 py-0.5 rounded-full text-[9px]" :class="item.sentiment_label === 'positive' ? 'bg-emerald-500/20 text-emerald-400' : item.sentiment_label === 'negative' ? 'bg-red-500/20 text-red-400' : 'bg-white/10 text-white/40'" x-text="item.sentiment_label"></span>
                                        <span class="text-brand-400 font-bold" x-text="item.viral_score"></span>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>
{% endblock %}

{% block scripts %}
<script>
function trendsApp() {
    return {
        tab: 'niches',
        platform: '{{ platform or "" }}',

        // Data
        alerts: [],
        niches: {},
        formats: [],
        creators: [],
        crossPlatform: [],
        bestTime: null,
        bestPlatform: null,

        // Saturation tool
        saturationKeyword: '',
        saturationResult: null,
        saturationLoading: false,

        // Timeline tool
        timelineKeyword: '',
        timelineResult: null,
        timelineLoading: false,

        // Best platform search
        platformKeyword: '',

        // Micro-trends
        microTrends: [],
        microTrendsLoading: false,

        // Algorithm changes
        algoData: null,
        algoLoading: false,

        // Music patterns
        musicData: null,
        musicLoading: false,

        // Global map
        globalMapData: null,
        globalMapLoading: false,

        // Weekly report
        weeklyReport: null,
        reportLoading: false,

        // STEPPS
        steppsKeyword: '',
        steppsData: null,
        steppsLoading: false,

        // Revenue
        revenueKeyword: '',
        revenuePlatform: 'tiktok',
        revenueData: null,
        revenueLoading: false,

        // Sentiment Virality
        sentimentKeyword: '',
        sentimentData: null,
        sentimentLoading: false,

        // Telegram
        telegramToken: '',
        telegramChatId: '',

        init() {
            this.loadAll();
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            this.initCharts();
        },

        async loadAll() {
            const p = this.platform ? '&platform=' + this.platform : '';
            // Load all data in parallel
            const [alertsRes, nichesRes, formatsRes, creatorsRes, crossRes, timeRes, platRes] = await Promise.allSettled([
                fetch('/api/trend-intelligence/alerts?hours=48').then(r => r.json()),
                fetch('/api/trend-intelligence/niches?days=7' + p).then(r => r.json()),
                fetch('/api/trend-intelligence/formats?days=7' + p).then(r => r.json()),
                fetch('/api/trend-intelligence/creators?days=7' + p + '&limit=20').then(r => r.json()),
                fetch('/api/trend-intelligence/cross-platform?days=7').then(r => r.json()),
                fetch('/api/trend-intelligence/best-time?days=14' + p).then(r => r.json()),
                fetch('/api/trend-intelligence/best-platform?days=14').then(r => r.json()),
            ]);

            if (alertsRes.status === 'fulfilled') this.alerts = alertsRes.value.alerts || [];
            if (nichesRes.status === 'fulfilled') this.niches = nichesRes.value || {};
            if (formatsRes.status === 'fulfilled') this.formats = (formatsRes.value.formats || []).filter(f => f.format !== 'other');
            if (creatorsRes.status === 'fulfilled') this.creators = creatorsRes.value.creators || [];
            if (crossRes.status === 'fulfilled') this.crossPlatform = crossRes.value.trends || [];
            if (timeRes.status === 'fulfilled') this.bestTime = timeRes.value;
            if (platRes.status === 'fulfilled') this.bestPlatform = platRes.value;

            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async checkSaturation() {
            if (!this.saturationKeyword) return;
            this.saturationLoading = true;
            try {
                const res = await fetch('/api/trend-intelligence/saturation?keyword=' + encodeURIComponent(this.saturationKeyword));
                this.saturationResult = await res.json();
            } catch(e) { showToast('Erro ao verificar saturacao', 'error'); }
            this.saturationLoading = false;
        },

        async loadTimeline() {
            if (!this.timelineKeyword) return;
            this.timelineLoading = true;
            try {
                const res = await fetch('/api/trend-intelligence/timeline?keyword=' + encodeURIComponent(this.timelineKeyword) + '&days=30');
                this.timelineResult = await res.json();
            } catch(e) { showToast('Erro ao carregar timeline', 'error'); }
            this.timelineLoading = false;
        },

        async loadBestPlatform() {
            try {
                const kw = this.platformKeyword ? '&keyword=' + encodeURIComponent(this.platformKeyword) : '';
                const res = await fetch('/api/trend-intelligence/best-platform?days=14' + kw);
                this.bestPlatform = await res.json();
            } catch(e) { showToast('Erro', 'error'); }
        },

        async loadMicroTrends() {
            this.microTrendsLoading = true;
            try {
                const r = await fetch('/api/trend-intelligence/micro-trends?hours=48');
                const d = await r.json();
                this.microTrends = d.trends || [];
            } catch(e) { showToast('Erro ao carregar micro-trends', 'error'); }
            this.microTrendsLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async loadAlgorithm() {
            this.algoLoading = true;
            try {
                const r = await fetch('/api/trend-intelligence/algorithm-changes?days=14');
                this.algoData = await r.json();
            } catch(e) { showToast('Erro ao detectar mudancas', 'error'); }
            this.algoLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async loadMusic() {
            this.musicLoading = true;
            try {
                const p = this.platform ? '&platform=' + this.platform : '';
                const r = await fetch('/api/trend-intelligence/music-patterns?days=7' + p);
                this.musicData = await r.json();
            } catch(e) { showToast('Erro ao carregar padroes musicais', 'error'); }
            this.musicLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async loadGlobalMap() {
            this.globalMapLoading = true;
            try {
                const r = await fetch('/api/trend-intelligence/global-map?days=7');
                this.globalMapData = await r.json();
            } catch(e) { showToast('Erro ao carregar mapa global', 'error'); }
            this.globalMapLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async loadWeeklyReport() {
            this.reportLoading = true;
            try {
                const r = await fetch('/api/trend-intelligence/weekly-report');
                this.weeklyReport = await r.json();
            } catch(e) { showToast('Erro ao gerar relatorio', 'error'); }
            this.reportLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async sendTelegramReport() {
            const token = prompt('Bot Token do Telegram:');
            const chatId = prompt('Chat ID do Telegram:');
            if (!token || !chatId) return;
            try {
                const params = new URLSearchParams({ bot_token: token, chat_id: chatId });
                const r = await fetch('/api/trend-intelligence/telegram-alert?' + params, { method: 'POST' });
                const d = await r.json();
                if (d.success) showToast('Alerta enviado via Telegram!', 'success');
                else showToast(d.error || 'Erro ao enviar', 'error');
            } catch(e) { showToast('Erro de conexao', 'error'); }
        },

        // ── STEPPS ──
        async loadStepps() {
            if (!this.steppsKeyword) return;
            this.steppsLoading = true;
            this.steppsData = null;
            try {
                const params = new URLSearchParams({ keyword: this.steppsKeyword, days: '7' });
                const r = await fetch('/api/trend-intelligence/stepps?' + params);
                this.steppsData = await r.json();
                this.renderSteppsChart();
            } catch(e) { showToast('Erro ao analisar STEPPS', 'error'); }
            this.steppsLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        renderSteppsChart() {
            const ctx = document.getElementById('steppsChart');
            if (!ctx || !this.steppsData?.breakdown) return;
            if (this._steppsChart) this._steppsChart.destroy();
            const b = this.steppsData.breakdown;
            this._steppsChart = new Chart(ctx, {
                type: 'radar',
                data: {
                    labels: ['Social Currency', 'Triggers', 'Emotion', 'Public', 'Practical Value', 'Stories'],
                    datasets: [{
                        label: 'STEPPS Score',
                        data: [b.social_currency, b.triggers, b.emotion, b.public, b.practical_value, b.stories],
                        backgroundColor: 'rgba(99, 102, 241, 0.2)',
                        borderColor: 'rgba(99, 102, 241, 0.8)',
                        borderWidth: 2,
                        pointBackgroundColor: 'rgba(99, 102, 241, 1)',
                    }]
                },
                options: {
                    responsive: true,
                    scales: { r: { beginAtZero: true, max: 100, grid: { color: 'rgba(255,255,255,0.05)' }, angleLines: { color: 'rgba(255,255,255,0.05)' }, pointLabels: { color: 'rgba(255,255,255,0.5)', font: { size: 10 } }, ticks: { display: false } } },
                    plugins: { legend: { display: false } },
                }
            });
        },

        // ── Revenue ──
        async loadRevenue() {
            if (!this.revenueKeyword) return;
            this.revenueLoading = true;
            this.revenueData = null;
            try {
                const params = new URLSearchParams({ keyword: this.revenueKeyword, platform: this.revenuePlatform, days: '14' });
                const r = await fetch('/api/trend-intelligence/revenue-prediction?' + params);
                this.revenueData = await r.json();
            } catch(e) { showToast('Erro ao calcular receita', 'error'); }
            this.revenueLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        // ── Sentiment Virality ──
        async loadSentimentVirality() {
            if (!this.sentimentKeyword) return;
            this.sentimentLoading = true;
            this.sentimentData = null;
            try {
                const params = new URLSearchParams({ keyword: this.sentimentKeyword, days: '7' });
                const r = await fetch('/api/trend-intelligence/sentiment-virality?' + params);
                this.sentimentData = await r.json();
                this.renderSentimentChart();
            } catch(e) { showToast('Erro ao analisar sentimento', 'error'); }
            this.sentimentLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        renderSentimentChart() {
            const ctx = document.getElementById('sentimentChart');
            if (!ctx || !this.sentimentData?.sentiment_distribution) return;
            if (this._sentimentChart) this._sentimentChart.destroy();
            const d = this.sentimentData.sentiment_distribution;
            this._sentimentChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: ['Positivo', 'Neutro', 'Negativo'],
                    datasets: [
                        {
                            label: 'Quantidade',
                            data: [d.positive?.count || 0, d.neutral?.count || 0, d.negative?.count || 0],
                            backgroundColor: ['rgba(52, 211, 153, 0.5)', 'rgba(156, 163, 175, 0.3)', 'rgba(248, 113, 113, 0.5)'],
                            borderColor: ['rgba(52, 211, 153, 0.8)', 'rgba(156, 163, 175, 0.5)', 'rgba(248, 113, 113, 0.8)'],
                            borderWidth: 1, borderRadius: 6, yAxisID: 'y',
                        },
                        {
                            label: 'Viral Score Medio',
                            data: [d.positive?.avg_viral_score || 0, d.neutral?.avg_viral_score || 0, d.negative?.avg_viral_score || 0],
                            type: 'line',
                            borderColor: 'rgba(244, 114, 182, 0.8)',
                            backgroundColor: 'rgba(244, 114, 182, 0.2)',
                            borderWidth: 2, pointRadius: 5, yAxisID: 'y1',
                        },
                    ]
                },
                options: {
                    responsive: true,
                    scales: {
                        y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.05)' }, title: { display: true, text: 'Quantidade', color: 'rgba(255,255,255,0.4)' } },
                        y1: { beginAtZero: true, position: 'right', grid: { display: false }, title: { display: true, text: 'Viral Score', color: 'rgba(244,114,182,0.6)' } },
                    },
                    plugins: { legend: { labels: { color: 'rgba(255,255,255,0.5)' } } },
                }
            });
        },

        fmtNum(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();
        },

        initCharts() {
            document.addEventListener('DOMContentLoaded', () => {
                Chart.defaults.color = 'rgba(255,255,255,0.5)';
                Chart.defaults.borderColor = 'rgba(255,255,255,0.05)';

                const durEl = document.getElementById('durationChart');
                if (durEl) {
                    const durData = {{ patterns.duration.buckets | tojson }};
                    new Chart(durEl, {
                        type: 'bar',
                        data: { labels: Object.keys(durData), datasets: [{ label: 'Videos', data: Object.values(durData), backgroundColor: ['#7c3aed', '#8b5cf6', '#a78bfa', '#c4b5fd', '#ddd6fe', '#ede9fe'], borderRadius: 8 }] },
                        options: { responsive: true, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.05)' } }, x: { grid: { display: false } } } }
                    });
                }

                const scoreEl = document.getElementById('scoreChart');
                if (scoreEl) {
                    const scoreData = {{ patterns.score_distribution | tojson }};
                    new Chart(scoreEl, {
                        type: 'bar',
                        data: { labels: Object.keys(scoreData), datasets: [{ label: 'Videos', data: Object.values(scoreData), backgroundColor: ['#6b7280', '#22c55e', '#3b82f6', '#f97316', '#ef4444'], borderRadius: 8 }] },
                        options: { responsive: true, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.05)' } }, x: { grid: { display: false } } } }
                    });
                }
            });
        },
    };
}
</script>
{% endblock %}
