{% extends "base.html" %}
{% block title %}EngageBot - Viral Social Pro{% endblock %}
{% block nav_engage %}active{% endblock %}
{% block page_title %}EngageBot{% endblock %}
{% block page_subtitle %}Automacao Inteligente de Engajamento{% endblock %}

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

    <!-- TABS -->
    <div class="flex gap-2 mb-6 overflow-x-auto pb-1">
        <button class="tab-btn" :class="activeTab === 'auto-reply' && 'active'" @click="activeTab = 'auto-reply'">
            <i data-lucide="reply" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Auto-Reply
        </button>
        <button class="tab-btn" :class="activeTab === 'classifier' && 'active'" @click="activeTab = 'classifier'">
            <i data-lucide="tags" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Classificador
        </button>
        <button class="tab-btn" :class="activeTab === 'health' && 'active'" @click="activeTab = 'health'">
            <i data-lucide="heart-pulse" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Saude da Comunidade
        </button>
        <button class="tab-btn" :class="activeTab === 'faq' && 'active'" @click="activeTab = 'faq'">
            <i data-lucide="help-circle" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> FAQ Detector
        </button>
        <button class="tab-btn" :class="activeTab === 'welcome-dm' && 'active'" @click="activeTab = 'welcome-dm'">
            <i data-lucide="mail" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Welcome DM
        </button>
        <button class="tab-btn" :class="activeTab === 'analytics' && 'active'" @click="activeTab = 'analytics'; loadAnalytics()">
            <i data-lucide="bar-chart-3" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Analytics
        </button>
    </div>

    <!-- ================================================================== -->
    <!-- TAB 1: AUTO-REPLY                                                   -->
    <!-- ================================================================== -->
    <div x-show="activeTab === 'auto-reply'" x-transition>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- Form -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                    <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center">
                        <i data-lucide="reply" class="w-5 h-5"></i>
                    </div>
                    Gerar Resposta com IA
                </h3>
                <div class="space-y-4">
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Comentario do seguidor *</label>
                        <textarea x-model="comment" rows="3"
                                  placeholder="Cole o comentario que deseja responder..."
                                  class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none resize-none"></textarea>
                    </div>
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Titulo do video (opcional)</label>
                        <input x-model="videoTitle" type="text"
                               placeholder="Ex: 5 dicas para viralizar no TikTok"
                               class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="text-xs text-white/50 mb-1 block">Tom</label>
                            <select x-model="tone"
                                    class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                                <option value="friendly">Amigavel</option>
                                <option value="professional">Profissional</option>
                                <option value="humorous">Humoristico</option>
                                <option value="empathetic">Empatico</option>
                            </select>
                        </div>
                        <div>
                            <label class="text-xs text-white/50 mb-1 block">Idioma</label>
                            <select x-model="replyLanguage"
                                    class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                                <option value="pt">Portugues</option>
                                <option value="en">English</option>
                                <option value="es">Espanol</option>
                            </select>
                        </div>
                    </div>
                    <button @click="generateReply()" :disabled="replyLoading || !comment.trim()"
                            class="w-full py-3 rounded-xl gradient-brand text-white font-bold text-sm hover:opacity-90 transition disabled:opacity-40">
                        <span x-show="!replyLoading" class="flex items-center justify-center gap-2">
                            <i data-lucide="sparkles" class="w-4 h-4"></i> Gerar Resposta
                        </span>
                        <span x-show="replyLoading" class="flex items-center justify-center gap-2">
                            <svg class="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                            Gerando...
                        </span>
                    </button>
                </div>
            </div>

            <!-- Results -->
            <div class="space-y-4">
                <!-- Reply Result -->
                <template x-if="replyResult">
                    <div class="glass-card rounded-2xl p-5 animate-fade-up">
                        <h4 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2">
                            <i data-lucide="check-circle" class="w-4 h-4 text-accent-green"></i> Resposta Gerada
                            <span class="ml-auto text-xs text-white/30" x-show="replyResult.tone_match">Tom: <span class="text-brand-300" x-text="replyResult.tone_match"></span></span>
                        </h4>
                        <!-- Main reply -->
                        <div class="bg-dark-700 rounded-xl p-4 mb-3 border border-brand-500/20">
                            <p class="text-sm text-white/90 leading-relaxed" x-text="replyResult.reply"></p>
                            <button @click="copyToClipboard(replyResult.reply)" class="mt-2 flex items-center gap-1 text-[11px] text-brand-300 hover:text-brand-200 transition">
                                <i data-lucide="copy" class="w-3 h-3"></i> Copiar
                            </button>
                        </div>
                        <!-- Alternatives -->
                        <template x-if="replyResult.alternative_replies?.length > 0">
                            <div>
                                <p class="text-xs text-white/40 mb-2">Alternativas:</p>
                                <template x-for="(alt, idx) in replyResult.alternative_replies" :key="idx">
                                    <div class="bg-dark-800 rounded-xl p-3 mb-2 border border-white/5">
                                        <p class="text-xs text-white/70 leading-relaxed" x-text="alt"></p>
                                        <button @click="copyToClipboard(alt)" class="mt-1.5 flex items-center gap-1 text-[10px] text-brand-300 hover:text-brand-200 transition">
                                            <i data-lucide="copy" class="w-3 h-3"></i> Copiar
                                        </button>
                                    </div>
                                </template>
                            </div>
                        </template>
                        <!-- Confidence -->
                        <div class="mt-3 flex items-center gap-2" x-show="replyResult.confidence != null">
                            <span class="text-[10px] text-white/30">Confianca:</span>
                            <div class="flex-1 h-1.5 bg-dark-800 rounded-full overflow-hidden">
                                <div class="h-full rounded-full transition-all duration-500"
                                     :style="'width:' + (replyResult.confidence * 100) + '%; background:' + (replyResult.confidence > 0.7 ? '#10b981' : replyResult.confidence > 0.4 ? '#f97316' : '#ef4444')"></div>
                            </div>
                            <span class="text-[10px] text-white/40" x-text="Math.round(replyResult.confidence * 100) + '%'"></span>
                        </div>
                    </div>
                </template>

                <!-- Keyword Triggers (auto-detected from the comment) -->
                <template x-if="triggerResults?.length > 0">
                    <div class="glass-card rounded-2xl p-5 animate-fade-up-delay">
                        <h4 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2">
                            <i data-lucide="zap" class="w-4 h-4 text-yellow-400"></i> Triggers Detectados
                        </h4>
                        <div class="space-y-2">
                            <template x-for="(t, i) in triggerResults" :key="i">
                                <div class="flex items-center gap-3 bg-dark-700 rounded-xl p-3">
                                    <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold bg-yellow-500/10 text-yellow-400 border border-yellow-500/20" x-text="t.keyword"></span>
                                    <span class="text-xs text-white/60" x-text="t.label || t.action"></span>
                                    <span class="ml-auto text-[10px] text-white/30" x-text="t.confidence ? Math.round(t.confidence * 100) + '%' : ''"></span>
                                </div>
                            </template>
                        </div>
                    </div>
                </template>

                <!-- Empty state -->
                <template x-if="!replyResult && !triggerResults?.length">
                    <div class="glass-card rounded-2xl p-12 text-center">
                        <i data-lucide="message-circle" class="w-12 h-12 text-white/15 mx-auto mb-3"></i>
                        <p class="text-white/30 text-sm">Digite um comentario e gere uma resposta com IA.</p>
                        <p class="text-white/20 text-xs mt-1">O EngageBot analisa o sentimento e gera respostas no tom ideal.</p>
                    </div>
                </template>
            </div>
        </div>
    </div>

    <!-- ================================================================== -->
    <!-- TAB 2: COMMENT CLASSIFIER                                           -->
    <!-- ================================================================== -->
    <div x-show="activeTab === 'classifier'" x-transition>
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Input -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                    <div class="w-10 h-10 rounded-xl gradient-ocean flex items-center justify-center">
                        <i data-lucide="tags" class="w-5 h-5"></i>
                    </div>
                    Classificar Comentarios
                </h3>
                <div class="space-y-4">
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Cole os comentarios (um por linha)</label>
                        <textarea x-model="classifyComments" rows="12"
                                  placeholder="Amei esse video! Muito bom!&#10;Quanto custa o produto?&#10;Esse video eh lixo, nao presta&#10;Clique no link na bio para ganhar dinheiro&#10;Como faz isso? Me ensina!&#10;Deveria ter mais exemplos praticos"
                                  class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none resize-none font-mono leading-relaxed"></textarea>
                    </div>
                    <button @click="classifyAllComments()" :disabled="classifyLoading || !classifyComments.trim()"
                            class="w-full py-3 rounded-xl gradient-ocean text-white font-bold text-sm hover:opacity-90 transition disabled:opacity-40">
                        <span x-show="!classifyLoading" class="flex items-center justify-center gap-2">
                            <i data-lucide="scan" class="w-4 h-4"></i> Classificar
                        </span>
                        <span x-show="classifyLoading" class="flex items-center justify-center gap-2">
                            <svg class="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                            Classificando...
                        </span>
                    </button>
                </div>
            </div>

            <!-- Results -->
            <div class="lg:col-span-2 space-y-4">
                <!-- Summary cards -->
                <template x-if="classifyResults?.summary">
                    <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 animate-fade-up">
                        <div class="glass-card rounded-xl p-3 text-center border-l-2 border-accent-green">
                            <p class="text-lg font-bold text-accent-green" x-text="classifyResults.summary.positive"></p>
                            <p class="text-[10px] text-white/40">Positivos</p>
                        </div>
                        <div class="glass-card rounded-xl p-3 text-center border-l-2 border-accent-red">
                            <p class="text-lg font-bold text-accent-red" x-text="classifyResults.summary.negative"></p>
                            <p class="text-[10px] text-white/40">Negativos</p>
                        </div>
                        <div class="glass-card rounded-xl p-3 text-center border-l-2 border-yellow-400">
                            <p class="text-lg font-bold text-yellow-400" x-text="classifyResults.summary.spam"></p>
                            <p class="text-[10px] text-white/40">Spam</p>
                        </div>
                        <div class="glass-card rounded-xl p-3 text-center border-l-2 border-accent-cyan">
                            <p class="text-lg font-bold text-accent-cyan" x-text="classifyResults.summary.questions"></p>
                            <p class="text-[10px] text-white/40">Perguntas</p>
                        </div>
                    </div>
                </template>

                <!-- Individual results -->
                <template x-if="classifyResults?.results?.length > 0">
                    <div class="glass-card rounded-2xl p-5 animate-fade-up-delay">
                        <h4 class="text-sm font-bold text-white/80 mb-3">Resultados Individuais</h4>
                        <div class="space-y-2 max-h-[500px] overflow-y-auto pr-1">
                            <template x-for="(r, i) in classifyResults.results" :key="i">
                                <div class="bg-dark-700 rounded-xl p-3 flex items-start gap-3 border-l-2"
                                     :class="classifyBorderColor(r.label)">
                                    <div class="flex-1 min-w-0">
                                        <p class="text-xs text-white/70 leading-relaxed" x-text="r.text"></p>
                                        <div class="flex items-center gap-2 mt-2 flex-wrap">
                                            <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold"
                                                  :class="classifyLabelClass(r.label)" x-text="classifyLabelText(r.label)"></span>
                                            <span class="text-[10px] text-white/30">Score: <span :style="'color:' + (r.sentiment_score > 0 ? '#10b981' : r.sentiment_score < 0 ? '#ef4444' : '#6b7280')" x-text="r.sentiment_score"></span></span>
                                            <span class="text-[10px] text-white/30" x-text="Math.round(r.confidence * 100) + '% confianca'"></span>
                                            <span x-show="r.is_question" class="px-1.5 py-0.5 rounded text-[9px] bg-accent-cyan/10 text-accent-cyan border border-accent-cyan/20">Pergunta</span>
                                            <span x-show="r.is_spam" class="px-1.5 py-0.5 rounded text-[9px] bg-yellow-500/10 text-yellow-400 border border-yellow-500/20">Spam</span>
                                            <span x-show="r.is_hate" class="px-1.5 py-0.5 rounded text-[9px] bg-accent-red/10 text-accent-red border border-accent-red/20">Ofensivo</span>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>
                </template>

                <!-- Empty state -->
                <template x-if="!classifyResults">
                    <div class="glass-card rounded-2xl p-12 text-center">
                        <i data-lucide="tags" class="w-12 h-12 text-white/15 mx-auto mb-3"></i>
                        <p class="text-white/30 text-sm">Cole comentarios para classificar automaticamente.</p>
                        <p class="text-white/20 text-xs mt-1">Detecta sentimento, spam, hate speech e perguntas.</p>
                    </div>
                </template>
            </div>
        </div>
    </div>

    <!-- ================================================================== -->
    <!-- TAB 3: COMMUNITY HEALTH                                             -->
    <!-- ================================================================== -->
    <div x-show="activeTab === 'health'" x-transition>
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Input -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                    <div class="w-10 h-10 rounded-xl gradient-success flex items-center justify-center">
                        <i data-lucide="heart-pulse" class="w-5 h-5"></i>
                    </div>
                    Analisar Saude
                </h3>
                <div class="space-y-4">
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Cole comentarios da sua comunidade (um por linha)</label>
                        <textarea x-model="healthComments" rows="12"
                                  placeholder="Amei o video! Conteudo incrivel!&#10;Quanto custa esse produto?&#10;Adorei as dicas, parabens!&#10;Esse video eh muito chato&#10;Clique no link pra ganhar dinheiro&#10;Como faz isso? Tutorial por favor!&#10;Poderia ter mais exemplos&#10;Show demais! Conteudo top!&#10;Nao consigo usar o app&#10;Sensacional, melhor video do mes"
                                  class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none resize-none font-mono leading-relaxed"></textarea>
                    </div>
                    <button @click="analyzeHealth()" :disabled="healthLoading || !healthComments.trim()"
                            class="w-full py-3 rounded-xl gradient-success text-white font-bold text-sm hover:opacity-90 transition disabled:opacity-40">
                        <span x-show="!healthLoading" class="flex items-center justify-center gap-2">
                            <i data-lucide="activity" class="w-4 h-4"></i> Analisar Saude
                        </span>
                        <span x-show="healthLoading" class="flex items-center justify-center gap-2">
                            <svg class="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                            Analisando...
                        </span>
                    </button>
                </div>
            </div>

            <!-- Results -->
            <div class="lg:col-span-2 space-y-4">
                <template x-if="healthResult">
                    <div>
                        <!-- Score Gauge -->
                        <div class="glass-card rounded-2xl p-6 text-center mb-4 animate-fade-up">
                            <div class="inline-flex flex-col items-center">
                                <div class="relative w-40 h-40 mb-4">
                                    <svg class="w-full h-full transform -rotate-90" viewBox="0 0 120 120">
                                        <circle cx="60" cy="60" r="52" fill="none" stroke="rgba(255,255,255,0.05)" stroke-width="10"/>
                                        <circle cx="60" cy="60" r="52" fill="none"
                                                :stroke="healthScoreColor(healthResult.score)"
                                                stroke-width="10"
                                                stroke-linecap="round"
                                                :stroke-dasharray="(healthResult.score / 100 * 326.7) + ' 326.7'"
                                                style="transition: stroke-dasharray 1s ease-out;"/>
                                    </svg>
                                    <div class="absolute inset-0 flex flex-col items-center justify-center">
                                        <span class="text-3xl font-extrabold" :style="'color:' + healthScoreColor(healthResult.score)" x-text="healthResult.score"></span>
                                        <span class="text-xs text-white/40">de 100</span>
                                    </div>
                                </div>
                                <span class="px-4 py-1.5 rounded-xl text-sm font-bold"
                                      :style="'background:' + healthScoreColor(healthResult.score) + '20; color:' + healthScoreColor(healthResult.score)"
                                      x-text="healthResult.label"></span>
                            </div>
                        </div>

                        <!-- Metrics Cards -->
                        <div class="grid grid-cols-1 sm:grid-cols-3 gap-3 mb-4 animate-fade-up">
                            <div class="glass-card rounded-xl p-4 text-center">
                                <div class="flex items-center justify-center gap-2 mb-2">
                                    <i data-lucide="shield-alert" class="w-4 h-4 text-accent-red"></i>
                                    <span class="text-xs text-white/50">Toxicidade</span>
                                </div>
                                <p class="text-2xl font-extrabold text-accent-red" x-text="(healthResult.toxicity_pct != null ? healthResult.toxicity_pct : (healthResult.factors?.spam_rate != null ? (100 - healthResult.factors.spam_rate) : '--')) + '%'"></p>
                            </div>
                            <div class="glass-card rounded-xl p-4 text-center">
                                <div class="flex items-center justify-center gap-2 mb-2">
                                    <i data-lucide="star" class="w-4 h-4 text-accent-cyan"></i>
                                    <span class="text-xs text-white/50">Qualidade Engajamento</span>
                                </div>
                                <p class="text-2xl font-extrabold text-accent-cyan" x-text="(healthResult.engagement_quality != null ? healthResult.engagement_quality : (healthResult.factors?.engagement || '--')) + '/100'"></p>
                            </div>
                            <div class="glass-card rounded-xl p-4 text-center">
                                <div class="flex items-center justify-center gap-2 mb-2">
                                    <i data-lucide="smile" class="w-4 h-4 text-accent-green"></i>
                                    <span class="text-xs text-white/50">Sentimento Positivo</span>
                                </div>
                                <p class="text-2xl font-extrabold text-accent-green" x-text="(healthResult.positive_pct != null ? healthResult.positive_pct : (healthResult.factors?.sentiment || '--')) + '%'"></p>
                            </div>
                        </div>

                        <!-- Sentiment Distribution -->
                        <div class="glass-card rounded-2xl p-5 mb-4 animate-fade-up" x-show="healthResult.sentiment_distribution || healthResult.factors">
                            <h4 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                                <i data-lucide="pie-chart" class="w-4 h-4 text-brand-400"></i> Distribuicao de Sentimento
                            </h4>
                            <template x-if="healthResult.sentiment_distribution">
                                <div class="space-y-3">
                                    <template x-for="(value, label) in healthResult.sentiment_distribution" :key="label">
                                        <div>
                                            <div class="flex items-center justify-between mb-1">
                                                <span class="text-xs text-white/60 capitalize" x-text="label"></span>
                                                <span class="text-xs font-bold" :style="'color:' + (label === 'positive' || label === 'positivo' ? '#10b981' : label === 'negative' || label === 'negativo' ? '#ef4444' : '#6b7280')" x-text="value + '%'"></span>
                                            </div>
                                            <div class="h-2 bg-dark-800 rounded-full overflow-hidden">
                                                <div class="h-full rounded-full transition-all duration-700"
                                                     :style="'width:' + value + '%; background:' + (label === 'positive' || label === 'positivo' ? '#10b981' : label === 'negative' || label === 'negativo' ? '#ef4444' : '#6b7280')"></div>
                                            </div>
                                        </div>
                                    </template>
                                </div>
                            </template>
                        </div>

                        <!-- Factors Breakdown -->
                        <div class="glass-card rounded-2xl p-5 mb-4 animate-fade-up-delay" x-show="healthResult.factors">
                            <h4 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                                <i data-lucide="sliders-horizontal" class="w-4 h-4 text-brand-400"></i> Fatores de Saude
                            </h4>
                            <div class="space-y-4">
                                <template x-for="(value, key) in healthResult.factors" :key="key">
                                    <div>
                                        <div class="flex items-center justify-between mb-1">
                                            <span class="text-xs text-white/60" x-text="healthFactorLabel(key)"></span>
                                            <span class="text-xs font-bold" :style="'color:' + healthScoreColor(value)" x-text="value + '/100'"></span>
                                        </div>
                                        <div class="h-2 bg-dark-800 rounded-full overflow-hidden">
                                            <div class="h-full rounded-full transition-all duration-700"
                                                 :style="'width:' + value + '%; background:' + healthScoreColor(value)"></div>
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </div>

                        <!-- Recommendations -->
                        <div class="glass-card rounded-2xl p-5 animate-fade-up-delay" x-show="healthResult.recommendations?.length > 0">
                            <h4 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-yellow-400"></i> Recomendacoes
                            </h4>
                            <div class="space-y-2">
                                <template x-for="(rec, i) in healthResult.recommendations" :key="i">
                                    <div class="flex items-start gap-3 bg-dark-700 rounded-xl p-3">
                                        <div class="w-6 h-6 rounded-lg bg-yellow-500/10 flex items-center justify-center flex-shrink-0 mt-0.5">
                                            <span class="text-[10px] font-bold text-yellow-400" x-text="i + 1"></span>
                                        </div>
                                        <p class="text-xs text-white/70 leading-relaxed" x-text="rec"></p>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>
                </template>

                <!-- Empty state -->
                <template x-if="!healthResult">
                    <div class="glass-card rounded-2xl p-12 text-center">
                        <i data-lucide="heart-pulse" class="w-12 h-12 text-white/15 mx-auto mb-3"></i>
                        <p class="text-white/30 text-sm">Cole comentarios para analisar a saude da sua comunidade.</p>
                        <p class="text-white/20 text-xs mt-1">Score de 0 a 100 baseado em sentimento, spam, diversidade e engajamento.</p>
                    </div>
                </template>
            </div>
        </div>
    </div>

    <!-- ================================================================== -->
    <!-- TAB 4: FAQ DETECTOR                                                 -->
    <!-- ================================================================== -->
    <div x-show="activeTab === 'faq'" x-transition>
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Input -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                    <div class="w-10 h-10 rounded-xl gradient-fire flex items-center justify-center">
                        <i data-lucide="help-circle" class="w-5 h-5"></i>
                    </div>
                    Detectar FAQs
                </h3>
                <div class="space-y-4">
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Cole comentarios (um por linha) - minimo 10 para melhores resultados</label>
                        <textarea x-model="faqComments" rows="10"
                                  placeholder="Quanto custa?&#10;Como faz pra comprar?&#10;Onde posso encontrar?&#10;Nao consigo baixar o app&#10;O app travou de novo&#10;Nao funciona no meu celular&#10;Qual o preco?&#10;Tem desconto?&#10;Quando sai a nova versao?&#10;O video esta muito confuso"
                                  class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none resize-none font-mono leading-relaxed"></textarea>
                    </div>
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Frequencia minima para FAQ</label>
                        <input x-model.number="faqMinFreq" type="number" min="2" max="20" value="2"
                               class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                    </div>
                    <button @click="detectFaqs()" :disabled="faqLoading || !faqComments.trim()"
                            class="w-full py-3 rounded-xl gradient-fire text-white font-bold text-sm hover:opacity-90 transition disabled:opacity-40">
                        <span x-show="!faqLoading" class="flex items-center justify-center gap-2">
                            <i data-lucide="search" class="w-4 h-4"></i> Detectar FAQs
                        </span>
                        <span x-show="faqLoading" class="flex items-center justify-center gap-2">
                            <svg class="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                            Detectando...
                        </span>
                    </button>

                    <!-- Pain Points section -->
                    <div class="pt-4 border-t border-white/5">
                        <h4 class="text-xs font-bold text-white/50 mb-2 flex items-center gap-1">
                            <i data-lucide="alert-triangle" class="w-3.5 h-3.5 text-accent-orange"></i> Detectar Pain Points
                        </h4>
                        <p class="text-[10px] text-white/30 mb-3">Analisa os mesmos comentarios para encontrar problemas recorrentes da audiencia.</p>
                        <button @click="detectPainPoints()" :disabled="painLoading || !faqComments.trim()"
                                class="w-full py-2.5 rounded-xl glass-card text-white/80 font-semibold text-sm hover:text-white transition border border-accent-orange/30 disabled:opacity-40">
                            <span x-show="!painLoading" class="flex items-center justify-center gap-2">
                                <i data-lucide="alert-triangle" class="w-4 h-4"></i> Detectar Pain Points
                            </span>
                            <span x-show="painLoading" class="flex items-center justify-center gap-2">
                                <svg class="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                                Detectando...
                            </span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Results -->
            <div class="lg:col-span-2 space-y-4">
                <!-- FAQs -->
                <template x-if="faqResults?.length > 0">
                    <div class="glass-card rounded-2xl p-5 animate-fade-up">
                        <div class="flex items-center justify-between mb-4">
                            <h4 class="text-sm font-bold text-white/80 flex items-center gap-2">
                                <i data-lucide="help-circle" class="w-4 h-4 text-accent-cyan"></i>
                                Perguntas Frequentes Detectadas
                                <span class="text-xs text-white/30" x-text="faqResults.length + ' FAQs'"></span>
                            </h4>
                            <button @click="generateFaqContent()" :disabled="faqContentLoading || !faqResults?.length"
                                    class="px-4 py-2 rounded-xl gradient-brand text-white text-xs font-bold disabled:opacity-40 hover:opacity-90 transition flex items-center gap-1.5">
                                <i data-lucide="sparkles" class="w-3.5 h-3.5" :class="faqContentLoading && 'animate-spin'"></i>
                                <span x-text="faqContentLoading ? 'Gerando...' : 'Gerar Ideias de Conteudo'"></span>
                            </button>
                        </div>
                        <div class="space-y-3">
                            <template x-for="(faq, i) in faqResults" :key="i">
                                <div class="bg-dark-700 rounded-xl p-4 border border-accent-cyan/10">
                                    <div class="flex items-start justify-between mb-2">
                                        <p class="text-sm font-semibold text-white/90" x-text="faq.question"></p>
                                        <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold bg-accent-cyan/10 text-accent-cyan flex-shrink-0 ml-2" x-text="faq.frequency + 'x'"></span>
                                    </div>
                                    <p class="text-xs text-accent-green/70 mb-2 italic" x-show="faq.suggested_answer" x-text="'Sugestao: ' + faq.suggested_answer"></p>
                                    <div x-show="faq.sample_comments?.length > 0">
                                        <p class="text-[10px] text-white/30 mb-1">Exemplos:</p>
                                        <div class="flex flex-wrap gap-1">
                                            <template x-for="(s, j) in faq.sample_comments?.slice(0, 3)" :key="j">
                                                <span class="px-2 py-0.5 rounded text-[10px] bg-dark-800 text-white/40 truncate max-w-[200px]" x-text="s"></span>
                                            </template>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>
                </template>

                <!-- Pain Points -->
                <template x-if="painResults?.length > 0">
                    <div class="glass-card rounded-2xl p-5 animate-fade-up-delay">
                        <h4 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                            <i data-lucide="alert-triangle" class="w-4 h-4 text-accent-orange"></i>
                            Pain Points Detectados
                            <span class="ml-auto text-xs text-white/30" x-text="painResults.length + ' problemas'"></span>
                        </h4>
                        <div class="space-y-3">
                            <template x-for="(pp, i) in painResults" :key="i">
                                <div class="bg-dark-700 rounded-xl p-4 border border-accent-orange/10">
                                    <div class="flex items-center gap-3 mb-2">
                                        <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold bg-accent-red/10 text-accent-red" x-text="pp.pain_point"></span>
                                        <span class="text-[10px] text-white/30" x-text="pp.frequency + ' mencoes'"></span>
                                        <span class="text-[10px] ml-auto" :style="'color:' + (pp.sentiment_avg > 0 ? '#10b981' : '#ef4444')" x-text="'Sent: ' + pp.sentiment_avg"></span>
                                    </div>
                                    <p class="text-xs text-accent-green/70 mb-2" x-show="pp.content_idea">
                                        <i data-lucide="lightbulb" class="w-3 h-3 inline-block mr-1"></i>
                                        <span x-text="pp.content_idea"></span>
                                    </p>
                                    <div class="flex flex-wrap gap-1" x-show="pp.sample_comments?.length > 0">
                                        <template x-for="(s, j) in pp.sample_comments?.slice(0, 3)" :key="j">
                                            <span class="px-2 py-0.5 rounded text-[10px] bg-dark-800 text-white/40 truncate max-w-[200px]" x-text="s"></span>
                                        </template>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>
                </template>

                <!-- Content Ideas from FAQs -->
                <template x-if="faqContent?.length > 0">
                    <div class="glass-card rounded-2xl p-5 animate-fade-up">
                        <h4 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-brand-400"></i>
                            Ideias de Conteudo Geradas
                        </h4>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                            <template x-for="(idea, i) in faqContent" :key="i">
                                <div class="bg-dark-700 rounded-xl p-4 border border-brand-500/10 hover:border-brand-500/30 transition">
                                    <h5 class="text-sm font-bold text-white/90 mb-1" x-text="idea.title"></h5>
                                    <p class="text-xs text-white/50 mb-2" x-text="idea.hook || idea.description"></p>
                                    <div class="flex items-center gap-2">
                                        <span x-show="idea.format" class="px-2 py-0.5 rounded text-[10px] font-medium bg-brand-500/10 text-brand-300" x-text="idea.format"></span>
                                        <span x-show="idea.estimated_engagement" class="px-2 py-0.5 rounded text-[10px] font-medium"
                                              :class="idea.estimated_engagement === 'alto' ? 'bg-accent-green/10 text-accent-green' : idea.estimated_engagement === 'medio' ? 'bg-yellow-500/10 text-yellow-400' : 'bg-white/5 text-white/40'"
                                              x-text="idea.estimated_engagement"></span>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </div>
                </template>

                <!-- Empty state -->
                <template x-if="!faqResults?.length && !painResults?.length && !faqContent?.length">
                    <div class="glass-card rounded-2xl p-12 text-center">
                        <i data-lucide="help-circle" class="w-12 h-12 text-white/15 mx-auto mb-3"></i>
                        <p class="text-white/30 text-sm">Cole comentarios para detectar FAQs e pain points.</p>
                        <p class="text-white/20 text-xs mt-1">Encontra padroes recorrentes e gera ideias de conteudo.</p>
                    </div>
                </template>
            </div>
        </div>
    </div>

    <!-- ================================================================== -->
    <!-- TAB 5: WELCOME DM                                                   -->
    <!-- ================================================================== -->
    <div x-show="activeTab === 'welcome-dm'" x-transition>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- Form -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                    <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center">
                        <i data-lucide="mail" class="w-5 h-5"></i>
                    </div>
                    Gerar DM de Boas-vindas
                </h3>
                <p class="text-xs text-white/40 mb-4">Crie mensagens personalizadas de boas-vindas para novos seguidores. Aumente a conexao com sua audiencia desde o primeiro contato.</p>
                <div class="space-y-4">
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Seu nome de criador *</label>
                        <input x-model="creatorName" type="text" placeholder="Ex: @seuusuario"
                               class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                    </div>
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Nome do novo seguidor (opcional)</label>
                        <input x-model="followerName" type="text" placeholder="Ex: Maria Silva"
                               class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                    </div>
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Nicho (opcional)</label>
                        <input x-model="dmNiche" type="text" placeholder="Ex: Fitness, Marketing Digital, Culinaria..."
                               class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                    </div>
                    <button @click="generateDM()" :disabled="dmLoading || !creatorName.trim()"
                            class="w-full py-3 rounded-xl gradient-brand text-white font-bold text-sm hover:opacity-90 transition disabled:opacity-40">
                        <span x-show="!dmLoading" class="flex items-center justify-center gap-2">
                            <i data-lucide="send" class="w-4 h-4"></i> Gerar DM Personalizada
                        </span>
                        <span x-show="dmLoading" class="flex items-center justify-center gap-2">
                            <svg class="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                            Gerando...
                        </span>
                    </button>
                </div>

                <!-- Quick Templates -->
                <div class="mt-6 pt-6 border-t border-white/5">
                    <h4 class="text-xs font-bold text-white/50 mb-3">Templates Rapidos</h4>
                    <div class="space-y-2">
                        <button @click="dmNiche = 'fitness'; creatorName = creatorName || 'Coach'" class="w-full text-left glass-light rounded-xl p-3 hover:border-brand-400/30 transition">
                            <p class="text-xs font-bold text-white/70">Fitness & Saude</p>
                            <p class="text-[10px] text-white/30">DM para seguidores de conteudo fitness</p>
                        </button>
                        <button @click="dmNiche = 'marketing digital'; creatorName = creatorName || 'Expert'" class="w-full text-left glass-light rounded-xl p-3 hover:border-brand-400/30 transition">
                            <p class="text-xs font-bold text-white/70">Marketing Digital</p>
                            <p class="text-[10px] text-white/30">DM para nicho de negocios online</p>
                        </button>
                        <button @click="dmNiche = 'culinaria'; creatorName = creatorName || 'Chef'" class="w-full text-left glass-light rounded-xl p-3 hover:border-brand-400/30 transition">
                            <p class="text-xs font-bold text-white/70">Culinaria & Receitas</p>
                            <p class="text-[10px] text-white/30">DM para amantes de gastronomia</p>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Result -->
            <div class="space-y-4">
                <template x-if="dmResult">
                    <div class="glass-card rounded-2xl p-5 animate-fade-up">
                        <h4 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2">
                            <i data-lucide="mail" class="w-4 h-4 text-accent-pink"></i> DM de Boas-vindas Gerada
                            <span class="ml-auto text-xs text-white/30" x-show="dmResult.tone">Tom: <span class="text-brand-300" x-text="dmResult.tone"></span></span>
                        </h4>
                        <div class="bg-dark-700 rounded-xl p-4 border border-accent-pink/20">
                            <p class="text-sm text-white/90 leading-relaxed whitespace-pre-wrap" x-text="dmResult.message"></p>
                            <div class="flex items-center gap-3 mt-3">
                                <button @click="copyToClipboard(dmResult.message)" class="flex items-center gap-1 text-[11px] text-brand-300 hover:text-brand-200 transition">
                                    <i data-lucide="copy" class="w-3 h-3"></i> Copiar
                                </button>
                                <span x-show="dmResult.has_cta" class="px-2 py-0.5 rounded-lg text-[10px] font-medium bg-accent-green/10 text-accent-green border border-accent-green/20">CTA Incluso</span>
                                <span x-show="dmResult.personalized" class="px-2 py-0.5 rounded-lg text-[10px] font-medium bg-brand-500/10 text-brand-300 border border-brand-500/20">Personalizada</span>
                            </div>
                        </div>

                        <!-- Tips -->
                        <div class="mt-4 glass-light rounded-xl p-3" x-show="dmResult.tips?.length > 0">
                            <h5 class="text-[10px] font-bold text-white/40 uppercase tracking-wider mb-2">Dicas de envio</h5>
                            <ul class="space-y-1">
                                <template x-for="(tip, i) in dmResult.tips" :key="i">
                                    <li class="text-[11px] text-white/50 flex items-start gap-1.5">
                                        <i data-lucide="check" class="w-3 h-3 text-accent-green mt-0.5 flex-shrink-0"></i>
                                        <span x-text="tip"></span>
                                    </li>
                                </template>
                            </ul>
                        </div>

                        <!-- Generate another -->
                        <button @click="generateDM()" :disabled="dmLoading" class="mt-4 w-full py-2.5 rounded-xl glass-card text-white/70 font-semibold text-xs hover:text-white transition border border-white/10">
                            <i data-lucide="refresh-cw" class="w-3.5 h-3.5 inline-block mr-1" :class="dmLoading && 'animate-spin'"></i>
                            Gerar outra variacao
                        </button>
                    </div>
                </template>

                <!-- Empty state -->
                <template x-if="!dmResult">
                    <div class="glass-card rounded-2xl p-12 text-center">
                        <i data-lucide="mail" class="w-12 h-12 text-white/15 mx-auto mb-3"></i>
                        <p class="text-white/30 text-sm">Gere DMs personalizadas de boas-vindas para novos seguidores.</p>
                        <p class="text-white/20 text-xs mt-1">Preencha os campos e clique em "Gerar DM Personalizada".</p>
                    </div>
                </template>
            </div>
        </div>
    </div>

    <!-- ================================================================== -->
    <!-- TAB 6: ANALYTICS                                                    -->
    <!-- ================================================================== -->
    <div x-show="activeTab === 'analytics'" x-transition>

        <!-- Period Selector -->
        <div class="flex items-center gap-3 mb-6">
            <label class="text-xs text-white/50">Periodo:</label>
            <select x-model="analyticsDays" @change="loadAnalytics()"
                    class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                <option value="7">7 dias</option>
                <option value="14">14 dias</option>
                <option value="30">30 dias</option>
            </select>
            <button @click="loadAnalytics()" class="px-3 py-2 rounded-xl glass-card text-xs text-white/60 hover:text-white transition">
                <i data-lucide="refresh-cw" class="w-3.5 h-3.5 inline-block mr-1"></i> Atualizar
            </button>
        </div>

        <!-- Loading -->
        <template x-if="analyticsLoading">
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                <template x-for="i in 4">
                    <div class="skeleton h-28 rounded-2xl"></div>
                </template>
            </div>
        </template>

        <!-- KPI Cards -->
        <template x-if="!analyticsLoading && analytics">
            <div>
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center">
                                <i data-lucide="message-circle" class="w-5 h-5"></i>
                            </div>
                            <span class="text-xs text-white/40">Comentarios</span>
                        </div>
                        <p class="stat-number text-white" x-text="formatNumber(analytics.total_comments)"></p>
                        <p class="text-xs text-white/30 mt-1">
                            Media: <span class="text-brand-300" x-text="analytics.avg_per_video?.comments || 0"></span>/video
                        </p>
                    </div>
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl gradient-fire flex items-center justify-center">
                                <i data-lucide="heart" class="w-5 h-5"></i>
                            </div>
                            <span class="text-xs text-white/40">Likes</span>
                        </div>
                        <p class="stat-number text-accent-pink" x-text="formatNumber(analytics.total_likes)"></p>
                        <p class="text-xs text-white/30 mt-1">
                            Media: <span class="text-accent-pink" x-text="analytics.avg_per_video?.likes || 0"></span>/video
                        </p>
                    </div>
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl gradient-ocean flex items-center justify-center">
                                <i data-lucide="share-2" class="w-5 h-5"></i>
                            </div>
                            <span class="text-xs text-white/40">Compartilhamentos</span>
                        </div>
                        <p class="stat-number text-accent-cyan" x-text="formatNumber(analytics.total_shares)"></p>
                        <p class="text-xs text-white/30 mt-1">
                            Media: <span class="text-accent-cyan" x-text="analytics.avg_per_video?.shares || 0"></span>/video
                        </p>
                    </div>
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl gradient-success flex items-center justify-center">
                                <i data-lucide="eye" class="w-5 h-5"></i>
                            </div>
                            <span class="text-xs text-white/40">Views Totais</span>
                        </div>
                        <p class="stat-number text-accent-green" x-text="formatNumber(analytics.total_views)"></p>
                        <p class="text-xs text-white/30 mt-1">
                            <span x-text="analytics.total_videos || 0"></span> videos analisados
                        </p>
                    </div>
                </div>

                <!-- Charts Row -->
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                    <!-- Sentiment 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="pie-chart" class="w-4 h-4 text-brand-400"></i> Sentimento dos Titulos
                        </h3>
                        <div class="relative" style="height: 250px;">
                            <canvas id="sentimentChart"></canvas>
                        </div>
                    </div>

                    <!-- Peak Hours 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="clock" class="w-4 h-4 text-accent-cyan"></i> Horarios de Pico
                        </h3>
                        <div class="relative" style="height: 250px;">
                            <canvas id="peakHoursChart"></canvas>
                        </div>
                    </div>
                </div>

                <!-- Platform Breakdown -->
                <div class="glass-card rounded-2xl p-5 mb-6" x-show="analytics.platform_breakdown && Object.keys(analytics.platform_breakdown).length > 0">
                    <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                        <i data-lucide="layers" class="w-4 h-4 text-accent-orange"></i> Breakdown por Plataforma
                    </h3>
                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                        <template x-for="(data, platform) in analytics.platform_breakdown" :key="platform">
                            <div class="glass-light rounded-xl p-4">
                                <div class="flex items-center gap-2 mb-3">
                                    <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold uppercase"
                                          :class="platform === 'tiktok' ? 'badge-tiktok' : platform === 'youtube' ? 'badge-youtube' : 'badge-instagram'"
                                          x-text="platform"></span>
                                    <span class="text-xs text-white/40" x-text="data.videos + ' videos'"></span>
                                </div>
                                <div class="grid grid-cols-2 gap-2 text-center">
                                    <div>
                                        <p class="text-sm font-bold text-white" x-text="formatNumber(data.views)"></p>
                                        <p class="text-[10px] text-white/30">Views</p>
                                    </div>
                                    <div>
                                        <p class="text-sm font-bold text-accent-pink" x-text="formatNumber(data.likes)"></p>
                                        <p class="text-[10px] text-white/30">Likes</p>
                                    </div>
                                    <div>
                                        <p class="text-sm font-bold text-accent-cyan" x-text="formatNumber(data.comments)"></p>
                                        <p class="text-[10px] text-white/30">Comments</p>
                                    </div>
                                    <div>
                                        <p class="text-sm font-bold text-accent-green" x-text="formatNumber(data.shares)"></p>
                                        <p class="text-[10px] text-white/30">Shares</p>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>

                <!-- Top Videos -->
                <div class="glass-card rounded-2xl p-5" x-show="analytics.top_videos_by_engagement?.length > 0">
                    <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-yellow-400"></i> Top Videos por Engajamento
                    </h3>
                    <div class="overflow-x-auto">
                        <table class="w-full text-sm">
                            <thead>
                                <tr class="text-white/40 text-xs border-b border-white/5">
                                    <th class="text-left py-2 pr-4">Video</th>
                                    <th class="text-right py-2 px-2">Views</th>
                                    <th class="text-right py-2 px-2">Likes</th>
                                    <th class="text-right py-2 px-2">Comments</th>
                                    <th class="text-right py-2 px-2">Shares</th>
                                    <th class="text-right py-2 pl-2">Score</th>
                                </tr>
                            </thead>
                            <tbody>
                                <template x-for="v in analytics.top_videos_by_engagement" :key="v.id">
                                    <tr class="border-b border-white/5 hover:bg-white/5 transition">
                                        <td class="py-2.5 pr-4">
                                            <div class="flex items-center gap-2">
                                                <span class="px-1.5 py-0.5 rounded text-[9px] font-bold uppercase"
                                                      :class="v.platform === 'tiktok' ? 'badge-tiktok' : v.platform === 'youtube' ? 'badge-youtube' : 'badge-instagram'"
                                                      x-text="v.platform"></span>
                                                <span class="text-white/70 truncate max-w-[200px]" x-text="v.title"></span>
                                            </div>
                                        </td>
                                        <td class="text-right py-2.5 px-2 text-white/60" x-text="formatNumber(v.views)"></td>
                                        <td class="text-right py-2.5 px-2 text-accent-pink" x-text="formatNumber(v.likes)"></td>
                                        <td class="text-right py-2.5 px-2 text-accent-cyan" x-text="formatNumber(v.comments)"></td>
                                        <td class="text-right py-2.5 px-2 text-accent-green" x-text="formatNumber(v.shares)"></td>
                                        <td class="text-right py-2.5 pl-2">
                                            <span class="px-2 py-0.5 rounded-lg text-xs font-bold" :style="'color:' + scoreColor(v.viral_score)" x-text="v.viral_score"></span>
                                        </td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </template>

        <!-- Empty state -->
        <template x-if="!analyticsLoading && !analytics">
            <div class="glass-card rounded-2xl p-12 text-center">
                <i data-lucide="bar-chart-3" class="w-12 h-12 text-white/20 mx-auto mb-4"></i>
                <p class="text-white/40 text-sm">Nenhum dado de engajamento disponivel.</p>
                <p class="text-white/25 text-xs mt-1">Colete videos primeiro para ver as analiticas.</p>
            </div>
        </template>
    </div>

</div>
{% endblock %}

{% block scripts %}
<script>
function engageBot() {
    return {
        activeTab: 'auto-reply',

        // Auto-Reply
        comment: '',
        videoTitle: '',
        tone: 'friendly',
        replyLanguage: 'pt',
        replyLoading: false,
        replyResult: null,
        triggerResults: [],

        // Classifier
        classifyComments: '',
        classifyLoading: false,
        classifyResults: null,

        // Community Health
        healthComments: '',
        healthLoading: false,
        healthResult: null,

        // FAQ Detector
        faqComments: '',
        faqMinFreq: 2,
        faqLoading: false,
        faqResults: null,
        faqContent: null,
        faqContentLoading: false,
        painResults: [],
        painLoading: false,

        // Welcome DM
        creatorName: '',
        followerName: '',
        dmNiche: '',
        dmLoading: false,
        dmResult: null,

        // Analytics
        analytics: null,
        analyticsLoading: false,
        analyticsDays: 7,
        sentimentChart: null,
        peakHoursChart: null,

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

        // ── Auto-Reply ───────────────────────────────

        async generateReply() {
            if (!this.comment.trim()) return;
            this.replyLoading = true;
            this.replyResult = null;
            this.triggerResults = [];

            try {
                const [replyRes, triggerRes] = await Promise.all([
                    fetch('/api/engage/auto-reply', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            comment: this.comment,
                            video_title: this.videoTitle,
                            tone: this.tone,
                            language: this.replyLanguage,
                        }),
                    }),
                    fetch('/api/engage/keyword-triggers', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ text: this.comment }),
                    }),
                ]);

                this.replyResult = await replyRes.json();
                const triggerData = await triggerRes.json();
                this.triggerResults = Array.isArray(triggerData) ? triggerData : (triggerData.triggers || []);

                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
                showToast('Resposta gerada com sucesso!', 'success');
            } catch (e) {
                console.error('Reply error:', e);
                showToast('Erro ao gerar resposta', 'error');
            }
            this.replyLoading = false;
        },

        // ── Classifier ──────────────────────────────

        async classifyAllComments() {
            if (!this.classifyComments.trim()) return;
            this.classifyLoading = true;
            this.classifyResults = null;

            try {
                const comments = this.classifyComments.split('\n').filter(c => c.trim());
                const r = await fetch('/api/engage/batch-classify', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ comments }),
                });
                this.classifyResults = await r.json();
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
                showToast(`${comments.length} comentarios classificados!`, 'success');
            } catch (e) {
                console.error('Classify error:', e);
                showToast('Erro ao classificar', 'error');
            }
            this.classifyLoading = false;
        },

        classifyBorderColor(label) {
            const map = {
                positive: 'border-accent-green',
                negative: 'border-accent-red',
                neutral: 'border-white/10',
                spam: 'border-yellow-400',
                hate: 'border-accent-red',
                question: 'border-accent-cyan',
                feedback: 'border-brand-400',
            };
            return map[label] || 'border-white/10';
        },

        classifyLabelClass(label) {
            const map = {
                positive: 'bg-accent-green/10 text-accent-green',
                negative: 'bg-accent-red/10 text-accent-red',
                neutral: 'bg-white/5 text-white/40',
                spam: 'bg-yellow-500/10 text-yellow-400',
                hate: 'bg-accent-red/15 text-accent-red',
                question: 'bg-accent-cyan/10 text-accent-cyan',
                feedback: 'bg-brand-500/10 text-brand-300',
            };
            return map[label] || 'bg-white/5 text-white/40';
        },

        classifyLabelText(label) {
            const map = {
                positive: 'Positivo',
                negative: 'Negativo',
                neutral: 'Neutro',
                spam: 'Spam',
                hate: 'Ofensivo',
                question: 'Pergunta',
                feedback: 'Feedback',
            };
            return map[label] || label;
        },

        // ── Community Health ─────────────────────────

        async analyzeHealth() {
            if (!this.healthComments.trim()) return;
            this.healthLoading = true;
            this.healthResult = null;

            try {
                const comments = this.healthComments.split('\n').filter(c => c.trim());
                const r = await fetch('/api/engage/community-health', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ comments }),
                });
                this.healthResult = await r.json();
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
                showToast('Analise de saude concluida!', 'success');
            } catch (e) {
                console.error('Health error:', e);
                showToast('Erro na analise de saude', 'error');
            }
            this.healthLoading = false;
        },

        healthScoreColor(score) {
            if (score >= 80) return '#10b981';
            if (score >= 60) return '#06b6d4';
            if (score >= 40) return '#f97316';
            if (score >= 20) return '#ef4444';
            return '#6b7280';
        },

        healthFactorLabel(key) {
            const map = {
                sentiment: 'Sentimento da Comunidade',
                spam_rate: 'Protecao contra Spam',
                diversity: 'Diversidade de Interacoes',
                engagement: 'Qualidade do Engajamento',
                question_rate: 'Participacao (Perguntas)',
                toxicity: 'Nivel de Toxicidade',
            };
            return map[key] || key;
        },

        // ── FAQ Detector ────────────────────────────

        async detectFaqs() {
            if (!this.faqComments.trim()) return;
            this.faqLoading = true;
            this.faqResults = [];
            this.faqContent = null;

            try {
                const comments = this.faqComments.split('\n').filter(c => c.trim());
                const r = await fetch('/api/engage/detect-faq', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ comments, min_frequency: this.faqMinFreq }),
                });
                const data = await r.json();
                this.faqResults = Array.isArray(data) ? data : (data.faqs || []);
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
                showToast(`${this.faqResults.length} FAQs detectadas!`, 'success');
            } catch (e) {
                console.error('FAQ error:', e);
                showToast('Erro ao detectar FAQs', 'error');
            }
            this.faqLoading = false;
        },

        async detectPainPoints() {
            if (!this.faqComments.trim()) return;
            this.painLoading = true;
            this.painResults = [];

            try {
                const comments = this.faqComments.split('\n').filter(c => c.trim());
                const r = await fetch('/api/engage/detect-pain-points', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ comments }),
                });
                const data = await r.json();
                this.painResults = Array.isArray(data) ? data : (data.pain_points || []);
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
                showToast(`${this.painResults.length} pain points detectados!`, 'success');
            } catch (e) {
                console.error('Pain points error:', e);
                showToast('Erro ao detectar pain points', 'error');
            }
            this.painLoading = false;
        },

        async generateFaqContent() {
            if (!this.faqResults?.length) return;
            this.faqContentLoading = true;
            this.faqContent = null;

            try {
                const r = await fetch('/api/engage/faq-content', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ faqs: this.faqResults }),
                });
                const data = await r.json();
                this.faqContent = data.content_ideas || data || [];
                if (!Array.isArray(this.faqContent)) this.faqContent = [];
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
                showToast('Ideias de conteudo geradas!', 'success');
            } catch (e) {
                console.error('FAQ content error:', e);
                showToast('Erro ao gerar ideias de conteudo', 'error');
            }
            this.faqContentLoading = false;
        },

        // ── Welcome DM ──────────────────────────────

        async generateDM() {
            if (!this.creatorName.trim()) return;
            this.dmLoading = true;
            this.dmResult = null;

            try {
                const r = await fetch('/api/engage/welcome-dm', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        creator_name: this.creatorName,
                        new_follower: this.followerName,
                        niche: this.dmNiche,
                    }),
                });
                this.dmResult = await r.json();
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
                showToast('DM gerada com sucesso!', 'success');
            } catch (e) {
                console.error('DM error:', e);
                showToast('Erro ao gerar DM', 'error');
            }
            this.dmLoading = false;
        },

        // ── Analytics ────────────────────────────────

        async loadAnalytics() {
            this.analyticsLoading = true;
            try {
                const r = await fetch(`/api/engage/analytics?days=${this.analyticsDays}`);
                this.analytics = await r.json();
                this.$nextTick(() => {
                    this.renderSentimentChart();
                    this.renderPeakHoursChart();
                    if (window.lucide) lucide.createIcons();
                });
            } catch (e) {
                console.error('Analytics error:', e);
                showToast('Erro ao carregar analiticas', 'error');
            }
            this.analyticsLoading = false;
        },

        renderSentimentChart() {
            const ctx = document.getElementById('sentimentChart');
            if (!ctx || !this.analytics?.sentiment_breakdown) return;
            if (this.sentimentChart) this.sentimentChart.destroy();

            const sb = this.analytics.sentiment_breakdown;
            this.sentimentChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['Positivo', 'Negativo', 'Neutro'],
                    datasets: [{
                        data: [sb.positivo || sb.positive || 0, sb.negativo || sb.negative || 0, sb.neutro || sb.neutral || 0],
                        backgroundColor: ['#10b981', '#ef4444', '#6b7280'],
                        borderWidth: 0,
                        hoverOffset: 8,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    cutout: '65%',
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: { color: 'rgba(255,255,255,0.5)', font: { size: 11 }, padding: 16, usePointStyle: true, pointStyleWidth: 8 }
                        }
                    }
                }
            });
        },

        renderPeakHoursChart() {
            const ctx = document.getElementById('peakHoursChart');
            if (!ctx || !this.analytics?.peak_hours?.length) return;
            if (this.peakHoursChart) this.peakHoursChart.destroy();

            const sorted = [...this.analytics.peak_hours].sort((a, b) => a.hour - b.hour);
            this.peakHoursChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: sorted.map(h => h.hour + 'h'),
                    datasets: [{
                        label: 'Videos publicados',
                        data: sorted.map(h => h.count),
                        backgroundColor: 'rgba(124, 58, 237, 0.4)',
                        borderColor: 'rgba(124, 58, 237, 0.8)',
                        borderWidth: 1,
                        borderRadius: 6,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: { color: 'rgba(255,255,255,0.03)' },
                            ticks: { color: 'rgba(255,255,255,0.3)', font: { size: 10 } }
                        },
                        x: {
                            grid: { display: false },
                            ticks: { color: 'rgba(255,255,255,0.3)', font: { size: 10 } }
                        }
                    }
                }
            });
        },

        // ── Utils ────────────────────────────────────

        copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(() => {
                showToast('Copiado!', 'success');
            }).catch(() => {
                const ta = document.createElement('textarea');
                ta.value = text;
                document.body.appendChild(ta);
                ta.select();
                document.execCommand('copy');
                document.body.removeChild(ta);
                showToast('Copiado!', 'success');
            });
        },
    };
}
</script>
{% endblock %}
