{% extends "base.html" %}
{% block title %}Inteligencia Viral - Viral Social Pro{% endblock %}
{% block nav_intelligence %}active{% endblock %}
{% block mnav_intelligence %}active{% endblock %}
{% block page_title %}Inteligencia Viral{% endblock %}
{% block page_subtitle %}Padroes virais, gerador de roteiros e probabilidade de viralizacao{% endblock %}

{% block content %}
<div x-data="intelligenceApp()" class="space-y-6 animate-fade-up">

    <!-- Tabs -->
    <div class="flex items-center gap-2 overflow-x-auto pb-1 scrollbar-hide">
        <button class="tab-btn" :class="activeTab === 'patterns' && 'active'" @click="activeTab = 'patterns'">
            <span class="flex items-center gap-2"><i data-lucide="bar-chart-3" class="w-4 h-4"></i> Padroes Virais</span>
        </button>
        <button class="tab-btn" :class="activeTab === 'scripts' && 'active'" @click="activeTab = 'scripts'">
            <span class="flex items-center gap-2"><i data-lucide="file-text" class="w-4 h-4"></i> Gerador de Roteiros</span>
        </button>
        <button class="tab-btn" :class="activeTab === 'probability' && 'active'" @click="activeTab = 'probability'">
            <span class="flex items-center gap-2"><i data-lucide="target" class="w-4 h-4"></i> Probabilidade Viral</span>
        </button>
        <button class="tab-btn" :class="activeTab === 'heatmap' && 'active'" @click="activeTab = 'heatmap'">
            <span class="flex items-center gap-2"><i data-lucide="grid-3x3" class="w-4 h-4"></i> Heatmap de Engajamento</span>
        </button>
    </div>

    <!-- ============================================================ -->
    <!-- TAB 1: PADROES VIRAIS -->
    <!-- ============================================================ -->
    <div x-show="activeTab === 'patterns'" x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 translate-y-2" x-transition:enter-end="opacity-100 translate-y-0">

        <!-- Filters & Analyze -->
        <div class="glass-card rounded-2xl p-5 mb-6">
            <div class="flex flex-wrap items-center gap-4">
                <div class="flex items-center gap-2">
                    <label class="text-xs text-white/40">Plataforma:</label>
                    <select x-model="patternPlatform" class="bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 outline-none">
                        <option value="all">Todas</option>
                        <option value="tiktok">TikTok</option>
                        <option value="instagram">Instagram</option>
                        <option value="youtube">YouTube</option>
                    </select>
                </div>
                <div class="flex items-center gap-2">
                    <label class="text-xs text-white/40">Periodo:</label>
                    <select x-model="patternDays" class="bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 outline-none">
                        <option value="7">7 dias</option>
                        <option value="14">14 dias</option>
                        <option value="30">30 dias</option>
                    </select>
                </div>
                <button @click="analyzePatterns()" :disabled="patternsLoading" class="flex items-center gap-2 px-5 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-50">
                    <i data-lucide="sparkles" class="w-4 h-4" :class="patternsLoading && 'animate-spin'"></i>
                    <span x-text="patternsLoading ? 'Analisando...' : 'Analisar Padroes'"></span>
                </button>
            </div>
        </div>

        <!-- Results -->
        <div x-show="patternsData" x-transition>

            <!-- Duration Analysis -->
            <div class="glass-card rounded-2xl p-5 mb-4">
                <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                    <i data-lucide="clock" class="w-4 h-4 text-brand-400"></i> Analise de Duracao
                </h3>
                <div x-show="patternsData?.duration" class="space-y-4">
                    <div class="flex items-center gap-4 mb-4">
                        <div class="p-3 rounded-xl bg-white/[0.03] border border-white/5">
                            <p class="text-xs text-white/40 mb-1">Faixa Ideal</p>
                            <p class="text-lg font-bold text-brand-300" x-text="patternsData?.duration?.ideal_range || '--'"></p>
                        </div>
                    </div>
                    <div class="space-y-2">
                        <template x-for="bucket in (patternsData?.duration?.distribution || [])" :key="bucket.label">
                            <div class="flex items-center gap-3">
                                <span class="text-xs text-white/50 w-24 flex-shrink-0" x-text="bucket.label"></span>
                                <div class="flex-1 h-6 bg-white/5 rounded-lg overflow-hidden">
                                    <div class="h-full rounded-lg transition-all duration-500" :style="'width:' + bucket.percent + '%; background: linear-gradient(90deg, #7c3aed, #ec4899);'" :title="bucket.count + ' videos'"></div>
                                </div>
                                <span class="text-xs text-white/40 w-12 text-right" x-text="bucket.count"></span>
                            </div>
                        </template>
                    </div>
                </div>
            </div>

            <!-- Top Formats + Chart -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-4">
                <!-- Top Formats -->
                <div class="glass-card rounded-2xl p-5">
                    <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                        <i data-lucide="layout-list" class="w-4 h-4 text-brand-400"></i> Formatos em Alta
                    </h3>
                    <div class="space-y-3">
                        <template x-for="(fmt, idx) in (patternsData?.top_formats || [])" :key="fmt.name">
                            <div class="flex items-center gap-3">
                                <span class="w-6 h-6 rounded-lg flex items-center justify-center text-xs font-bold" :class="idx < 3 ? 'gradient-brand text-white' : 'bg-white/5 text-white/40'" x-text="idx + 1"></span>
                                <span class="text-sm text-white/80 flex-1 capitalize" x-text="fmt.name"></span>
                                <div class="w-24 h-2 bg-white/5 rounded-full overflow-hidden">
                                    <div class="h-full rounded-full gradient-brand" :style="'width:' + fmt.percent + '%'"></div>
                                </div>
                                <span class="text-xs text-white/40 w-10 text-right" x-text="fmt.count"></span>
                            </div>
                        </template>
                    </div>
                    <div x-show="!patternsData?.top_formats?.length" class="text-center py-6 text-white/30 text-sm">Nenhum formato encontrado</div>
                </div>

                <!-- Formats Bar Chart -->
                <div class="glass-card rounded-2xl p-5">
                    <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                        <i data-lucide="bar-chart-3" class="w-4 h-4 text-brand-400"></i> Distribuicao de Formatos
                    </h3>
                    <canvas id="formatsChart" height="220"></canvas>
                </div>
            </div>

            <!-- Top Hashtags -->
            <div class="glass-card rounded-2xl p-5 mb-4">
                <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                    <i data-lucide="hash" class="w-4 h-4 text-brand-400"></i> Top 20 Hashtags Virais
                </h3>
                <div class="flex flex-wrap gap-2">
                    <template x-for="tag in (patternsData?.top_hashtags || [])" :key="tag.name">
                        <span class="px-3 py-1.5 rounded-xl text-sm font-medium glass-light text-brand-300 hover:text-brand-200 hover:border-brand-400/30 cursor-default transition" :title="tag.count + ' videos'">
                            #<span x-text="tag.name"></span>
                            <span class="text-white/20 text-xs ml-1" x-text="tag.count"></span>
                        </span>
                    </template>
                </div>
                <div x-show="!patternsData?.top_hashtags?.length" class="text-center py-6 text-white/30 text-sm">Nenhuma hashtag encontrada</div>
            </div>

            <!-- Best Hours + Engagement Stats -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
                <!-- Best Posting Hours -->
                <div class="glass-card rounded-2xl p-5">
                    <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                        <i data-lucide="calendar-clock" class="w-4 h-4 text-brand-400"></i> Melhores Horarios para Postar
                    </h3>
                    <canvas id="hoursChart" height="220"></canvas>
                </div>

                <!-- Avg Engagement Stats -->
                <div class="glass-card rounded-2xl p-5">
                    <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                        <i data-lucide="activity" class="w-4 h-4 text-brand-400"></i> Engajamento Medio
                    </h3>
                    <div class="grid grid-cols-2 gap-4">
                        <div class="p-4 rounded-xl bg-white/[0.03] border border-white/5 text-center">
                            <i data-lucide="eye" class="w-5 h-5 text-brand-400 mx-auto mb-2"></i>
                            <p class="text-xs text-white/40 mb-1">Views Medio</p>
                            <p class="text-xl font-bold text-white" x-text="formatNumber(patternsData?.avg_engagement?.views || 0)"></p>
                        </div>
                        <div class="p-4 rounded-xl bg-white/[0.03] border border-white/5 text-center">
                            <i data-lucide="heart" class="w-5 h-5 text-accent-pink mx-auto mb-2"></i>
                            <p class="text-xs text-white/40 mb-1">Likes Medio</p>
                            <p class="text-xl font-bold text-accent-pink" x-text="formatNumber(patternsData?.avg_engagement?.likes || 0)"></p>
                        </div>
                        <div class="p-4 rounded-xl bg-white/[0.03] border border-white/5 text-center">
                            <i data-lucide="message-circle" class="w-5 h-5 text-accent-cyan mx-auto mb-2"></i>
                            <p class="text-xs text-white/40 mb-1">Comentarios Medio</p>
                            <p class="text-xl font-bold text-accent-cyan" x-text="formatNumber(patternsData?.avg_engagement?.comments || 0)"></p>
                        </div>
                        <div class="p-4 rounded-xl bg-white/[0.03] border border-white/5 text-center">
                            <i data-lucide="percent" class="w-5 h-5 text-accent-green mx-auto mb-2"></i>
                            <p class="text-xs text-white/40 mb-1">Taxa de Engajamento</p>
                            <p class="text-xl font-bold text-accent-green" x-text="(patternsData?.avg_engagement?.rate || 0).toFixed(2) + '%'"></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Empty state -->
        <div x-show="!patternsData && !patternsLoading" class="glass-card rounded-2xl p-12 text-center">
            <i data-lucide="bar-chart-3" class="w-12 h-12 text-white/10 mx-auto mb-4"></i>
            <p class="text-white/40 text-sm">Clique em "Analisar Padroes" para descobrir insights sobre conteudo viral</p>
        </div>
    </div>

    <!-- ============================================================ -->
    <!-- TAB 2: GERADOR DE ROTEIROS -->
    <!-- ============================================================ -->
    <div x-show="activeTab === 'scripts'" x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 translate-y-2" x-transition:enter-end="opacity-100 translate-y-0">

        <!-- Input Form -->
        <div class="glass-card rounded-2xl p-5 mb-6">
            <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                <i data-lucide="pen-tool" class="w-4 h-4 text-brand-400"></i> Configurar Roteiro
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
                <div>
                    <label class="text-xs text-white/40 mb-1 block">Topico *</label>
                    <input x-model="scriptTopic" type="text" placeholder="Ex: receitas fitness, skincare..." class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 outline-none">
                </div>
                <div>
                    <label class="text-xs text-white/40 mb-1 block">Plataforma</label>
                    <select x-model="scriptPlatform" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 outline-none">
                        <option value="tiktok">TikTok</option>
                        <option value="instagram">Instagram</option>
                        <option value="youtube">YouTube</option>
                    </select>
                </div>
                <div>
                    <label class="text-xs text-white/40 mb-1 block">Estilo</label>
                    <select x-model="scriptStyle" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 outline-none">
                        <option value="tutorial">Tutorial</option>
                        <option value="pov">POV</option>
                        <option value="curiosity">Curiosidade</option>
                        <option value="tips">Dicas</option>
                        <option value="review">Review</option>
                    </select>
                </div>
                <div class="flex items-end">
                    <button @click="generateScript()" :disabled="scriptLoading || !scriptTopic.trim()" class="w-full flex items-center justify-center gap-2 px-5 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-50">
                        <i data-lucide="wand-2" class="w-4 h-4" :class="scriptLoading && 'animate-spin'"></i>
                        <span x-text="scriptLoading ? 'Gerando...' : 'Gerar Roteiro'"></span>
                    </button>
                </div>
            </div>
        </div>

        <!-- Generated Script Result -->
        <div x-show="scriptData" x-transition class="space-y-4">

            <!-- Hook Options -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                    <i data-lucide="zap" class="w-4 h-4 text-accent-orange"></i> Opcoes de Hook
                </h3>
                <div class="space-y-2">
                    <template x-for="(hook, idx) in (scriptData?.hooks || [])" :key="idx">
                        <div class="p-3 rounded-xl bg-white/[0.03] border border-white/5 flex items-start gap-3 hover:border-brand-400/20 transition cursor-pointer" @click="copyText(hook)">
                            <span class="w-6 h-6 rounded-lg gradient-fire flex items-center justify-center text-xs font-bold flex-shrink-0" x-text="idx + 1"></span>
                            <p class="text-sm text-white/80 flex-1" x-text="hook"></p>
                            <i data-lucide="copy" class="w-4 h-4 text-white/20 flex-shrink-0 hover:text-white/60"></i>
                        </div>
                    </template>
                </div>
            </div>

            <!-- Script Structure -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                    <i data-lucide="list-ordered" class="w-4 h-4 text-brand-400"></i> Estrutura do Roteiro
                </h3>
                <div class="space-y-3">
                    <template x-for="(step, idx) in (scriptData?.structure || [])" :key="idx">
                        <div class="flex items-start gap-3">
                            <div class="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0 text-xs font-bold" :class="{
                                'gradient-brand': step.phase === 'hook',
                                'gradient-fire': step.phase === 'problem',
                                'gradient-ocean': step.phase === 'solution',
                                'gradient-success': step.phase === 'proof',
                                'bg-brand-600': step.phase === 'cta'
                            }">
                                <span x-text="idx + 1"></span>
                            </div>
                            <div class="flex-1 p-3 rounded-xl bg-white/[0.02] border border-white/5">
                                <p class="text-xs text-brand-300 font-semibold uppercase mb-1" x-text="step.phase"></p>
                                <p class="text-sm text-white/70 leading-relaxed" x-text="step.content"></p>
                                <p x-show="step.duration" class="text-xs text-white/30 mt-1" x-text="step.duration"></p>
                            </div>
                        </div>
                    </template>
                </div>
            </div>

            <!-- Hashtags + Caption -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
                <!-- Recommended Hashtags -->
                <div class="glass-card rounded-2xl p-5">
                    <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                        <i data-lucide="hash" class="w-4 h-4 text-brand-400"></i> Hashtags Recomendadas
                    </h3>
                    <div class="flex flex-wrap gap-2">
                        <template x-for="tag in (scriptData?.hashtags || [])" :key="tag">
                            <span class="px-3 py-1.5 rounded-xl text-sm font-medium glass-light text-brand-300 hover:text-brand-200 cursor-pointer transition" @click="copyText('#' + tag)" :title="'Copiar #' + tag">
                                #<span x-text="tag"></span>
                            </span>
                        </template>
                    </div>
                    <button x-show="scriptData?.hashtags?.length" @click="copyText(scriptData.hashtags.map(t => '#' + t).join(' '))" class="mt-3 text-xs text-brand-400 hover:text-brand-300 flex items-center gap-1">
                        <i data-lucide="copy" class="w-3 h-3"></i> Copiar todas
                    </button>
                </div>

                <!-- Caption Template -->
                <div class="glass-card rounded-2xl p-5">
                    <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                        <i data-lucide="type" class="w-4 h-4 text-brand-400"></i> Modelo de Legenda
                    </h3>
                    <div class="relative">
                        <div class="p-4 rounded-xl bg-white/[0.03] border border-white/5 text-sm text-white/70 leading-relaxed whitespace-pre-wrap" x-text="scriptData?.caption || 'Nenhuma legenda gerada'"></div>
                        <button x-show="scriptData?.caption" @click="copyText(scriptData.caption)" class="absolute top-2 right-2 p-1.5 rounded-lg hover:bg-white/10 transition" title="Copiar legenda">
                            <i data-lucide="copy" class="w-4 h-4 text-white/30 hover:text-white/60"></i>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Tips -->
            <div x-show="scriptData?.tips?.length" class="glass-card rounded-2xl p-5">
                <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                    <i data-lucide="lightbulb" class="w-4 h-4 text-accent-orange"></i> Dicas para Viralizacao
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <template x-for="(tip, idx) in (scriptData?.tips || [])" :key="idx">
                        <div class="flex items-start gap-3 p-3 rounded-xl bg-white/[0.02] border border-white/5">
                            <i data-lucide="check-circle" class="w-4 h-4 text-accent-green flex-shrink-0 mt-0.5"></i>
                            <p class="text-sm text-white/60" x-text="tip"></p>
                        </div>
                    </template>
                </div>
            </div>
        </div>

        <!-- Empty state -->
        <div x-show="!scriptData && !scriptLoading" class="glass-card rounded-2xl p-12 text-center">
            <i data-lucide="file-text" class="w-12 h-12 text-white/10 mx-auto mb-4"></i>
            <p class="text-white/40 text-sm">Preencha o topico e clique em "Gerar Roteiro" para criar um roteiro otimizado</p>
        </div>
    </div>

    <!-- ============================================================ -->
    <!-- TAB 3: PROBABILIDADE VIRAL -->
    <!-- ============================================================ -->
    <div x-show="activeTab === 'probability'" x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 translate-y-2" x-transition:enter-end="opacity-100 translate-y-0">

        <!-- Input Form -->
        <div class="glass-card rounded-2xl p-5 mb-6">
            <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                <i data-lucide="calculator" class="w-4 h-4 text-brand-400"></i> Calcular Probabilidade de Viralizacao
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-4">
                <div>
                    <label class="text-xs text-white/40 mb-1 block">Titulo do Video *</label>
                    <input x-model="viralTitle" type="text" placeholder="Ex: 5 truques que ninguem te contou..." class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 outline-none">
                </div>
                <div>
                    <label class="text-xs text-white/40 mb-1 block">Hashtags (separadas por virgula)</label>
                    <input x-model="viralHashtags" type="text" placeholder="Ex: fitness, receita, viral" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 outline-none">
                </div>
                <div>
                    <label class="text-xs text-white/40 mb-1 block">Plataforma</label>
                    <select x-model="viralPlatform" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 outline-none">
                        <option value="tiktok">TikTok</option>
                        <option value="instagram">Instagram</option>
                        <option value="youtube">YouTube</option>
                    </select>
                </div>
                <div>
                    <label class="text-xs text-white/40 mb-1 block">Duracao (segundos)</label>
                    <input x-model="viralDuration" type="number" placeholder="Ex: 30" min="1" max="3600" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 outline-none">
                </div>
                <div>
                    <label class="text-xs text-white/40 mb-1 block">Horario de Postagem</label>
                    <input x-model="viralHour" type="number" placeholder="Ex: 18" min="0" max="23" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 outline-none">
                </div>
                <div class="flex items-end">
                    <button @click="calculateProbability()" :disabled="probLoading || !viralTitle.trim()" class="w-full flex items-center justify-center gap-2 px-5 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-50">
                        <i data-lucide="calculator" class="w-4 h-4" :class="probLoading && 'animate-spin'"></i>
                        <span x-text="probLoading ? 'Calculando...' : 'Calcular'"></span>
                    </button>
                </div>
            </div>
        </div>

        <!-- Probability Result -->
        <div x-show="probData" x-transition class="space-y-4">

            <!-- Score Display -->
            <div class="glass-card rounded-2xl p-8 text-center">
                <p class="text-xs text-white/40 uppercase tracking-wider mb-3">Probabilidade de Viralizacao</p>
                <div class="inline-flex items-center justify-center w-32 h-32 rounded-full mb-4 relative" :style="'background: conic-gradient(' + probScoreColor(probData?.score) + ' ' + (probData?.score || 0) * 3.6 + 'deg, rgba(255,255,255,0.05) 0deg); padding: 6px;'">
                    <div class="w-full h-full rounded-full bg-dark-900 flex items-center justify-center">
                        <span class="text-4xl font-extrabold" :style="'color:' + probScoreColor(probData?.score)" x-text="(probData?.score || 0)"></span>
                    </div>
                </div>
                <p class="text-lg font-bold mb-1" :style="'color:' + probScoreColor(probData?.score)" x-text="probData?.verdict || ''"></p>
                <p class="text-sm text-white/40" x-text="probData?.verdict_detail || ''"></p>
            </div>

            <!-- Factors -->
            <div x-show="probData?.factors?.length" class="glass-card rounded-2xl p-5">
                <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                    <i data-lucide="list-checks" class="w-4 h-4 text-brand-400"></i> Fatores Analisados
                </h3>
                <div class="space-y-3">
                    <template x-for="factor in (probData?.factors || [])" :key="factor.name">
                        <div class="flex items-center gap-4 p-3 rounded-xl bg-white/[0.02] border border-white/5">
                            <div class="flex-shrink-0">
                                <div class="w-10 h-10 rounded-xl flex items-center justify-center text-sm font-bold" :class="{
                                    'bg-accent-green/20 text-accent-green': factor.impact === 'positive',
                                    'bg-accent-red/20 text-accent-red': factor.impact === 'negative',
                                    'bg-accent-orange/20 text-accent-orange': factor.impact === 'neutral' || factor.impact === 'warning'
                                }">
                                    <i :data-lucide="factor.impact === 'positive' ? 'check' : (factor.impact === 'negative' ? 'x' : 'minus')" class="w-5 h-5"></i>
                                </div>
                            </div>
                            <div class="flex-1">
                                <p class="text-sm font-semibold text-white/80" x-text="factor.name"></p>
                                <p class="text-xs text-white/40" x-text="factor.detail"></p>
                            </div>
                            <span class="text-xs font-semibold px-2 py-1 rounded-lg" :class="{
                                'bg-accent-green/10 text-accent-green': factor.impact === 'positive',
                                'bg-accent-red/10 text-accent-red': factor.impact === 'negative',
                                'bg-accent-orange/10 text-accent-orange': factor.impact === 'neutral' || factor.impact === 'warning'
                            }" x-text="factor.impact === 'positive' ? 'Positivo' : (factor.impact === 'negative' ? 'Negativo' : 'Neutro')"></span>
                        </div>
                    </template>
                </div>
            </div>

            <!-- Suggestions -->
            <div x-show="probData?.suggestions?.length" class="glass-card rounded-2xl p-5">
                <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                    <i data-lucide="sparkles" class="w-4 h-4 text-accent-orange"></i> Sugestoes de Melhoria
                </h3>
                <div class="space-y-2">
                    <template x-for="(sug, idx) in (probData?.suggestions || [])" :key="idx">
                        <div class="flex items-start gap-3 p-3 rounded-xl bg-white/[0.02] border border-white/5">
                            <i data-lucide="arrow-up-right" class="w-4 h-4 text-brand-400 flex-shrink-0 mt-0.5"></i>
                            <p class="text-sm text-white/60" x-text="sug"></p>
                        </div>
                    </template>
                </div>
            </div>
        </div>

        <!-- Empty state -->
        <div x-show="!probData && !probLoading" class="glass-card rounded-2xl p-12 text-center">
            <i data-lucide="target" class="w-12 h-12 text-white/10 mx-auto mb-4"></i>
            <p class="text-white/40 text-sm">Preencha os dados do video e calcule a probabilidade de viralizacao</p>
        </div>
    </div>

    <!-- ============================================================ -->
    <!-- TAB 4: HEATMAP DE ENGAJAMENTO -->
    <!-- ============================================================ -->
    <div x-show="activeTab === 'heatmap'" x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 translate-y-2" x-transition:enter-end="opacity-100 translate-y-0">

        <!-- Filters -->
        <div class="glass-card rounded-2xl p-5 mb-6">
            <div class="flex flex-wrap items-center gap-4">
                <div class="flex items-center gap-2">
                    <label class="text-xs text-white/40">Plataforma:</label>
                    <select x-model="heatmapPlatform" class="bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 outline-none">
                        <option value="all">Todas</option>
                        <option value="tiktok">TikTok</option>
                        <option value="instagram">Instagram</option>
                        <option value="youtube">YouTube</option>
                    </select>
                </div>
                <div class="flex items-center gap-2">
                    <label class="text-xs text-white/40">Nicho:</label>
                    <input x-model="heatmapNiche" type="text" placeholder="Ex: fitness" class="bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 outline-none w-36">
                </div>
                <div class="flex items-center gap-2">
                    <label class="text-xs text-white/40">Periodo:</label>
                    <select x-model="heatmapDays" class="bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 outline-none">
                        <option value="7">7 dias</option>
                        <option value="14">14 dias</option>
                        <option value="30">30 dias</option>
                    </select>
                </div>
                <button @click="generateHeatmap()" :disabled="heatmapLoading" class="flex items-center gap-2 px-5 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-50">
                    <i data-lucide="grid-3x3" class="w-4 h-4" :class="heatmapLoading && 'animate-spin'"></i>
                    <span x-text="heatmapLoading ? 'Gerando...' : 'Gerar Heatmap'"></span>
                </button>
            </div>
        </div>

        <!-- Heatmap Grid -->
        <div x-show="heatmapData" x-transition class="space-y-4">
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                    <i data-lucide="grid-3x3" class="w-4 h-4 text-brand-400"></i> Heatmap de Engajamento por Dia/Hora
                </h3>
                <div class="overflow-x-auto">
                    <table class="w-full text-xs" style="min-width: 700px;">
                        <thead>
                            <tr>
                                <th class="text-left py-2 px-1 text-white/40 w-12">Dia</th>
                                <template x-for="h in 24" :key="h">
                                    <th class="text-center py-2 px-0.5 text-white/30 font-normal" x-text="(h - 1) + 'h'" style="min-width: 28px;"></th>
                                </template>
                            </tr>
                        </thead>
                        <tbody>
                            <template x-for="(dayName, dayIdx) in heatmapDayNames" :key="dayIdx">
                                <tr>
                                    <td class="py-1 px-1 text-white/50 font-medium" x-text="dayName"></td>
                                    <template x-for="hour in 24" :key="hour">
                                        <td class="py-1 px-0.5">
                                            <div class="w-full h-7 rounded-md cursor-pointer transition-all hover:scale-110 hover:z-10 relative group"
                                                 :style="'background-color:' + heatmapCellColor(dayIdx, hour - 1)"
                                                 :title="dayName + ' ' + (hour - 1) + ':00 - ' + formatNumber(getHeatmapValue(dayIdx, hour - 1)) + ' views'">
                                                <div class="hidden group-hover:flex absolute bottom-full left-1/2 -translate-x-1/2 mb-1 px-2 py-1 rounded-lg bg-dark-900 border border-white/10 text-white/80 text-xs whitespace-nowrap z-20">
                                                    <span x-text="dayName + ' ' + (hour - 1) + ':00'"></span>
                                                    <span class="ml-1 text-brand-300" x-text="formatNumber(getHeatmapValue(dayIdx, hour - 1)) + ' views'"></span>
                                                </div>
                                            </div>
                                        </td>
                                    </template>
                                </tr>
                            </template>
                        </tbody>
                    </table>
                </div>
                <!-- Color Legend -->
                <div class="flex items-center gap-3 mt-4 justify-center">
                    <span class="text-xs text-white/30">Menos views</span>
                    <div class="flex gap-0.5">
                        <div class="w-6 h-3 rounded-sm" style="background-color: rgba(124,58,237,0.05);"></div>
                        <div class="w-6 h-3 rounded-sm" style="background-color: rgba(124,58,237,0.2);"></div>
                        <div class="w-6 h-3 rounded-sm" style="background-color: rgba(124,58,237,0.4);"></div>
                        <div class="w-6 h-3 rounded-sm" style="background-color: rgba(124,58,237,0.6);"></div>
                        <div class="w-6 h-3 rounded-sm" style="background-color: rgba(124,58,237,0.85);"></div>
                    </div>
                    <span class="text-xs text-white/30">Mais views</span>
                </div>
            </div>

            <!-- Top 10 Best Slots -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                    <i data-lucide="trophy" class="w-4 h-4 text-accent-orange"></i> Top 10 Melhores Horarios
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <template x-for="(slot, idx) in (heatmapData?.top_slots || []).slice(0, 10)" :key="idx">
                        <div class="flex items-center gap-3 p-3 rounded-xl bg-white/[0.02] border border-white/5">
                            <span class="w-7 h-7 rounded-lg flex items-center justify-center text-xs font-bold flex-shrink-0" :class="idx < 3 ? 'gradient-brand text-white' : 'bg-white/5 text-white/40'" x-text="idx + 1"></span>
                            <div class="flex-1">
                                <p class="text-sm font-semibold text-white/80" x-text="slot.day + ' as ' + slot.hour + ':00'"></p>
                                <p class="text-xs text-white/40" x-text="formatNumber(slot.avg_views) + ' views medias'"></p>
                            </div>
                            <div class="w-16 h-1.5 bg-white/5 rounded-full overflow-hidden">
                                <div class="h-full rounded-full gradient-brand" :style="'width:' + (slot.avg_views / (heatmapData?.max_views || 1) * 100) + '%'"></div>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>

        <!-- Empty state -->
        <div x-show="!heatmapData && !heatmapLoading" class="glass-card rounded-2xl p-12 text-center">
            <i data-lucide="grid-3x3" class="w-12 h-12 text-white/10 mx-auto mb-4"></i>
            <p class="text-white/40 text-sm">Configure os filtros e gere o heatmap para descobrir os melhores horarios</p>
        </div>
    </div>

</div>
{% endblock %}

{% block scripts %}
<script>
function intelligenceApp() {
    return {
        activeTab: 'patterns',

        // Tab 1 - Patterns
        patternPlatform: 'all',
        patternDays: '7',
        patternsLoading: false,
        patternsData: null,
        formatsChart: null,
        hoursChartInstance: null,

        // Tab 2 - Scripts
        scriptTopic: '',
        scriptPlatform: 'tiktok',
        scriptStyle: 'tutorial',
        scriptLoading: false,
        scriptData: null,

        // Tab 3 - Probability
        viralTitle: '',
        viralHashtags: '',
        viralPlatform: 'tiktok',
        viralDuration: '',
        viralHour: '',
        probLoading: false,
        probData: null,

        // Tab 4 - Heatmap
        heatmapPlatform: 'all',
        heatmapNiche: '',
        heatmapDays: '7',
        heatmapLoading: false,
        heatmapData: null,
        heatmapDayNames: ['Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab', 'Dom'],
        heatmapGrid: {},
        heatmapMaxVal: 1,

        // ===== Tab 1: Patterns =====
        async analyzePatterns() {
            this.patternsLoading = true;
            try {
                const params = new URLSearchParams({
                    platform: this.patternPlatform,
                    days: this.patternDays
                });
                const resp = await fetch('/api/patterns/analyze?' + params.toString());
                if (!resp.ok) throw new Error('Erro na API');
                const data = await resp.json();
                this.patternsData = data;
                showToast('Padroes analisados com sucesso!', 'success');
                this.$nextTick(() => {
                    this.renderFormatsChart();
                    this.renderHoursChart();
                    if (window.lucide) lucide.createIcons();
                });
            } catch (e) {
                console.error('Pattern analysis error:', e);
                showToast('Erro ao analisar padroes', 'error');
            } finally {
                this.patternsLoading = false;
            }
        },

        renderFormatsChart() {
            const ctx = document.getElementById('formatsChart');
            if (!ctx || !this.patternsData?.top_formats?.length) return;
            if (this.formatsChart) this.formatsChart.destroy();
            const formats = this.patternsData.top_formats;
            this.formatsChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: formats.map(f => f.name),
                    datasets: [{
                        label: 'Videos',
                        data: formats.map(f => f.count),
                        backgroundColor: formats.map((_, i) => {
                            const colors = [
                                'rgba(124,58,237,0.7)',
                                'rgba(236,72,153,0.7)',
                                'rgba(6,182,212,0.7)',
                                'rgba(249,115,22,0.7)',
                                'rgba(16,185,129,0.7)',
                                'rgba(124,58,237,0.4)',
                                'rgba(236,72,153,0.4)',
                                'rgba(6,182,212,0.4)'
                            ];
                            return colors[i % colors.length];
                        }),
                        borderRadius: 8,
                        borderSkipped: false
                    }]
                },
                options: {
                    responsive: true,
                    indexAxis: 'y',
                    plugins: { legend: { display: false } },
                    scales: {
                        x: {
                            ticks: { color: 'rgba(255,255,255,0.3)', font: { size: 10 } },
                            grid: { color: 'rgba(255,255,255,0.05)' }
                        },
                        y: {
                            ticks: { color: 'rgba(255,255,255,0.5)', font: { size: 11 } },
                            grid: { display: false }
                        }
                    }
                }
            });
        },

        renderHoursChart() {
            const ctx = document.getElementById('hoursChart');
            if (!ctx || !this.patternsData?.best_hours?.length) return;
            if (this.hoursChartInstance) this.hoursChartInstance.destroy();
            const hours = this.patternsData.best_hours;
            this.hoursChartInstance = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: hours.map(h => h.hour + ':00'),
                    datasets: [{
                        label: 'Score Medio',
                        data: hours.map(h => h.avg_score || h.avg_views || 0),
                        borderColor: '#7c3aed',
                        backgroundColor: 'rgba(124,58,237,0.1)',
                        fill: true,
                        tension: 0.4,
                        pointRadius: 3,
                        pointBackgroundColor: '#7c3aed',
                        pointHoverRadius: 6
                    }]
                },
                options: {
                    responsive: true,
                    plugins: { legend: { display: false } },
                    scales: {
                        x: {
                            ticks: { color: 'rgba(255,255,255,0.3)', font: { size: 10 }, maxRotation: 0 },
                            grid: { display: false }
                        },
                        y: {
                            ticks: { color: 'rgba(255,255,255,0.3)', font: { size: 10 } },
                            grid: { color: 'rgba(255,255,255,0.05)' }
                        }
                    }
                }
            });
        },

        // ===== Tab 2: Script Generator =====
        async generateScript() {
            if (!this.scriptTopic.trim()) {
                showToast('Informe um topico para gerar o roteiro', 'warning');
                return;
            }
            this.scriptLoading = true;
            try {
                const params = new URLSearchParams({
                    topic: this.scriptTopic,
                    platform: this.scriptPlatform,
                    style: this.scriptStyle
                });
                const resp = await fetch('/api/patterns/script?' + params.toString());
                if (!resp.ok) throw new Error('Erro na API');
                const data = await resp.json();
                this.scriptData = data;
                showToast('Roteiro gerado com sucesso!', 'success');
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            } catch (e) {
                console.error('Script generation error:', e);
                showToast('Erro ao gerar roteiro', 'error');
            } finally {
                this.scriptLoading = false;
            }
        },

        copyText(text) {
            if (!text) return;
            navigator.clipboard.writeText(text).then(() => {
                showToast('Copiado!', 'success');
            }).catch(() => {
                // Fallback
                const ta = document.createElement('textarea');
                ta.value = text;
                ta.style.position = 'fixed';
                ta.style.opacity = '0';
                document.body.appendChild(ta);
                ta.select();
                document.execCommand('copy');
                document.body.removeChild(ta);
                showToast('Copiado!', 'success');
            });
        },

        // ===== Tab 3: Viral Probability =====
        async calculateProbability() {
            if (!this.viralTitle.trim()) {
                showToast('Informe o titulo do video', 'warning');
                return;
            }
            this.probLoading = true;
            try {
                const params = new URLSearchParams({
                    title: this.viralTitle,
                    hashtags: this.viralHashtags,
                    platform: this.viralPlatform
                });
                if (this.viralDuration) params.set('duration', this.viralDuration);
                if (this.viralHour) params.set('hour', this.viralHour);
                const resp = await fetch('/api/patterns/viral-probability?' + params.toString());
                if (!resp.ok) throw new Error('Erro na API');
                const data = await resp.json();
                this.probData = data;
                showToast('Probabilidade calculada!', 'success');
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            } catch (e) {
                console.error('Probability calc error:', e);
                showToast('Erro ao calcular probabilidade', 'error');
            } finally {
                this.probLoading = false;
            }
        },

        probScoreColor(score) {
            if (!score && score !== 0) return '#6b7280';
            if (score >= 80) return '#10b981';
            if (score >= 60) return '#f97316';
            if (score >= 40) return '#eab308';
            return '#ef4444';
        },

        // ===== Tab 4: Heatmap =====
        async generateHeatmap() {
            this.heatmapLoading = true;
            try {
                const params = new URLSearchParams({
                    platform: this.heatmapPlatform,
                    niche: this.heatmapNiche,
                    days: this.heatmapDays
                });
                const resp = await fetch('/api/engagement/heatmap?' + params.toString());
                if (!resp.ok) throw new Error('Erro na API');
                const data = await resp.json();
                this.heatmapData = data;
                this.processHeatmapData(data);
                showToast('Heatmap gerado com sucesso!', 'success');
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            } catch (e) {
                console.error('Heatmap error:', e);
                showToast('Erro ao gerar heatmap', 'error');
            } finally {
                this.heatmapLoading = false;
            }
        },

        processHeatmapData(data) {
            this.heatmapGrid = {};
            this.heatmapMaxVal = 1;
            const grid = data?.grid || data?.heatmap || [];
            for (const cell of grid) {
                const key = cell.day + '_' + cell.hour;
                const val = cell.avg_views || cell.value || 0;
                this.heatmapGrid[key] = val;
                if (val > this.heatmapMaxVal) this.heatmapMaxVal = val;
            }
        },

        getHeatmapValue(dayIdx, hour) {
            const key = dayIdx + '_' + hour;
            return this.heatmapGrid[key] || 0;
        },

        heatmapCellColor(dayIdx, hour) {
            const val = this.getHeatmapValue(dayIdx, hour);
            if (!val || this.heatmapMaxVal <= 0) return 'rgba(124,58,237,0.03)';
            const intensity = Math.min(val / this.heatmapMaxVal, 1);
            const alpha = 0.05 + intensity * 0.8;
            return 'rgba(124,58,237,' + alpha.toFixed(2) + ')';
        }
    };
}
</script>
{% endblock %}