{% extends "base.html" %}
{% block title %}DarkFactory - Viral Social Pro{% endblock %}
{% block nav_dark_factory %}active{% endblock %}
{% block page_title %}DarkFactory{% endblock %}
{% block page_subtitle %}Pipeline de Videos Faceless com IA{% endblock %}

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

    <!-- TABS -->
    <div class="flex gap-2 mb-6 overflow-x-auto pb-1">
        <button class="tab-btn" :class="activeTab === 'pipeline' && 'active'" @click="activeTab = 'pipeline'">
            <i data-lucide="play-circle" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Pipeline Creator
        </button>
        <button class="tab-btn" :class="activeTab === 'script' && 'active'" @click="activeTab = 'script'">
            <i data-lucide="file-text" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Script Generator
        </button>
        <button class="tab-btn" :class="activeTab === 'batch' && 'active'" @click="activeTab = 'batch'">
            <i data-lucide="layers" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Batch Production
        </button>
        <button class="tab-btn" :class="activeTab === 'history' && 'active'" @click="activeTab = 'history'; loadHistory()">
            <i data-lucide="history" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Pipeline History
        </button>
        <button class="tab-btn" :class="activeTab === 'stats' && 'active'" @click="activeTab = 'stats'; loadStats()">
            <i data-lucide="bar-chart-3" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Estatisticas
        </button>
    </div>

    <!-- ============================================================ -->
    <!-- TAB: PIPELINE CREATOR                                        -->
    <!-- ============================================================ -->
    <div x-show="activeTab === 'pipeline'" x-transition>
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

            <!-- Pipeline 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="clapperboard" class="w-5 h-5"></i>
                    </div>
                    Novo Pipeline
                </h3>
                <div class="space-y-4">
                    <!-- Topic -->
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Topico do Video *</label>
                        <input x-model="topic" type="text"
                               placeholder="Ex: A verdade sobre o Triangulo das Bermudas"
                               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>

                    <!-- Niche -->
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Nicho</label>
                        <select x-model="niche"
                                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="curiosidades">Curiosidades</option>
                            <option value="financas">Financas</option>
                            <option value="tecnologia">Tecnologia</option>
                            <option value="saude">Saude</option>
                            <option value="educacao">Educacao</option>
                            <option value="motivacao">Motivacao</option>
                            <option value="historia">Historia</option>
                            <option value="ciencia">Ciencia</option>
                            <option value="psicologia">Psicologia</option>
                            <option value="negocios">Negocios</option>
                        </select>
                    </div>

                    <!-- Duration Slider -->
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Duracao: <span class="text-brand-300 font-bold" x-text="duration + ' min'"></span></label>
                        <input x-model.number="duration" type="range" min="5" max="30" step="1" class="w-full accent-brand-500">
                        <div class="flex items-center justify-between text-[10px] text-white/30 mt-0.5">
                            <span>5 min</span>
                            <span>30 min</span>
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-3">
                        <!-- Voice -->
                        <div>
                            <label class="text-xs text-white/50 mb-1 block">Voz</label>
                            <select x-model="voice"
                                    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-BR-AntonioNeural">Antonio (PT-BR, Masc)</option>
                                <option value="pt-BR-FranciscaNeural">Francisca (PT-BR, Fem)</option>
                                <option value="pt-BR-ThalitaNeural">Thalita (PT-BR, Fem)</option>
                                <option value="en-US-GuyNeural">Guy (EN-US, Masc)</option>
                                <option value="en-US-JennyNeural">Jenny (EN-US, Fem)</option>
                                <option value="es-ES-AlvaroNeural">Alvaro (ES-ES, Masc)</option>
                            </select>
                        </div>

                        <!-- Style -->
                        <div>
                            <label class="text-xs text-white/50 mb-1 block">Estilo Visual</label>
                            <select x-model="style"
                                    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="cinematic">Cinematico</option>
                                <option value="informativo">Informativo</option>
                                <option value="storytelling">Storytelling</option>
                                <option value="dramatico">Dramatico</option>
                            </select>
                        </div>
                    </div>

                    <!-- Start Button -->
                    <button @click="startPipeline()" :disabled="pipelineLoading || !topic.trim()"
                            class="w-full py-3 rounded-xl gradient-brand text-white font-bold text-sm disabled:opacity-50 transition flex items-center justify-center gap-2">
                        <i data-lucide="play" class="w-4 h-4" :class="pipelineLoading && 'animate-spin'"></i>
                        <span x-text="pipelineLoading ? 'Iniciando pipeline...' : 'Iniciar Pipeline Completo'"></span>
                    </button>
                </div>

                <!-- Cost Estimate -->
                <div class="mt-5 glass-light rounded-xl p-4">
                    <h4 class="text-xs font-bold text-white/50 mb-2 flex items-center gap-1">
                        <i data-lucide="calculator" class="w-3 h-3"></i> Estimativa de Custo
                    </h4>
                    <div class="flex items-center justify-between">
                        <span class="text-xs text-white/40">Pipeline completo</span>
                        <span class="text-lg font-bold text-accent-green">R$ 0,00</span>
                    </div>
                    <p class="text-[10px] text-white/30 mt-1">100% local: Ollama + edge-tts + Pexels gratuito</p>
                    <button @click="loadCostEstimate()" class="mt-2 text-xs text-brand-400 hover:text-brand-300 transition">
                        Ver detalhes do custo
                    </button>
                    <div x-show="costEstimate" x-transition class="mt-2 space-y-1">
                        <template x-for="(cost, key) in (costEstimate?.costs || {})" :key="key">
                            <div class="flex items-center justify-between text-[10px]">
                                <span class="text-white/40" x-text="cost.service"></span>
                                <span class="text-accent-green font-bold">$<span x-text="cost.cost_usd?.toFixed(2)"></span></span>
                            </div>
                        </template>
                        <div x-show="costEstimate?.savings_usd" class="border-t border-white/5 pt-1 mt-1">
                            <div class="flex items-center justify-between text-[10px]">
                                <span class="text-white/50">Economia vs alternativas pagas</span>
                                <span class="text-accent-green font-bold">$<span x-text="costEstimate?.savings_usd?.toFixed(2)"></span></span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Niche Info (loads from API) -->
                <div class="mt-5" x-show="niches">
                    <h4 class="text-xs font-bold text-white/50 mb-2 flex items-center gap-1">
                        <i data-lucide="info" class="w-3 h-3"></i> Info do Nicho
                    </h4>
                    <template x-if="getCurrentNicheInfo()">
                        <div class="glass-light rounded-xl p-3 space-y-1">
                            <div class="flex items-center justify-between text-[10px]">
                                <span class="text-white/40">RPM Estimado</span>
                                <span class="text-accent-green font-bold">$<span x-text="getCurrentNicheInfo()?.rpm?.toFixed(1)"></span></span>
                            </div>
                            <div class="flex items-center justify-between text-[10px]">
                                <span class="text-white/40">Duracao Media</span>
                                <span class="text-white/60" x-text="getCurrentNicheInfo()?.avg_length"></span>
                            </div>
                            <div class="flex items-center justify-between text-[10px]">
                                <span class="text-white/40">Estilo</span>
                                <span class="text-white/60" x-text="getCurrentNicheInfo()?.style"></span>
                            </div>
                        </div>
                    </template>
                </div>
            </div>

            <!-- Pipeline Progress / Active Pipelines -->
            <div class="lg:col-span-2">
                <div class="flex items-center justify-between mb-4">
                    <h3 class="text-lg font-bold text-white/90 flex items-center gap-2">
                        <i data-lucide="activity" class="w-5 h-5 text-brand-400"></i> Pipelines Ativos
                    </h3>
                    <button @click="refreshPipelines()" class="text-xs text-white/40 hover:text-white/70 flex items-center gap-1 transition">
                        <i data-lucide="refresh-cw" class="w-3 h-3" :class="refreshingPipelines && 'animate-spin'"></i> Atualizar
                    </button>
                </div>

                <!-- Empty State -->
                <div x-show="activePipelines.length === 0 && !pipelineLoading" class="glass-card rounded-2xl p-12 text-center">
                    <i data-lucide="clapperboard" class="w-16 h-16 text-white/10 mx-auto mb-3"></i>
                    <p class="text-sm text-white/30 mb-1">Nenhum pipeline ativo</p>
                    <p class="text-xs text-white/20">Preencha o formulario e clique em "Iniciar Pipeline" para comecar</p>
                </div>

                <!-- Pipeline Result (just started) -->
                <div x-show="pipelineResult" x-transition class="glass-card rounded-2xl p-5 mb-4 border border-accent-green/20">
                    <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="check-circle" class="w-5 h-5"></i>
                        </div>
                        <div>
                            <p class="text-sm font-bold text-white/90">Pipeline Iniciado!</p>
                            <p class="text-[10px] text-white/40" x-text="'ID: ' + (pipelineResult?.pipeline_id || '')"></p>
                        </div>
                    </div>
                    <div class="grid grid-cols-3 gap-2">
                        <div class="glass-light rounded-lg p-2 text-center">
                            <p class="text-[10px] text-white/40">Status</p>
                            <p class="text-xs font-bold text-accent-green" x-text="pipelineResult?.status"></p>
                        </div>
                        <div class="glass-light rounded-lg p-2 text-center">
                            <p class="text-[10px] text-white/40">Duracao</p>
                            <p class="text-xs font-bold text-white/70" x-text="(pipelineResult?.duration_minutes || 0) + ' min'"></p>
                        </div>
                        <div class="glass-light rounded-lg p-2 text-center">
                            <p class="text-[10px] text-white/40">Tempo Est.</p>
                            <p class="text-xs font-bold text-white/70" x-text="'~' + (pipelineResult?.estimated_time_minutes || 0) + ' min'"></p>
                        </div>
                    </div>
                    <div class="flex flex-wrap gap-1 mt-3">
                        <template x-for="stage in (pipelineResult?.stages || [])" :key="stage">
                            <span class="px-2 py-0.5 rounded text-[10px] glass-light text-brand-300" x-text="stage"></span>
                        </template>
                    </div>
                </div>

                <!-- Active Pipeline Cards -->
                <div class="space-y-4">
                    <template x-for="pipe in activePipelines" :key="pipe.id">
                        <div class="glass-card rounded-2xl p-5 animate-fade-up">
                            <!-- Header -->
                            <div class="flex items-start justify-between mb-3">
                                <div class="flex-1 min-w-0">
                                    <h4 class="text-sm font-bold text-white/90 truncate" x-text="pipe.topic"></h4>
                                    <div class="flex items-center gap-2 mt-1">
                                        <span class="px-2 py-0.5 rounded text-[10px] font-bold"
                                              :class="pipe.niche === 'financas' ? 'bg-accent-green/20 text-accent-green' :
                                                       pipe.niche === 'tecnologia' ? 'bg-accent-cyan/20 text-accent-cyan' :
                                                       pipe.niche === 'saude' ? 'bg-accent-pink/20 text-accent-pink' :
                                                       'bg-brand-500/20 text-brand-300'"
                                              x-text="pipe.niche"></span>
                                        <span class="text-[10px] text-white/30" x-text="pipe.style || ''"></span>
                                        <span class="text-[10px] text-white/20" x-text="pipe.elapsed_formatted || pipe.created_at"></span>
                                    </div>
                                </div>
                                <span class="px-2 py-1 rounded-lg text-[10px] font-bold"
                                      :class="pipe.status === 'completed' ? 'bg-accent-green/20 text-accent-green' :
                                               pipe.status === 'failed' ? 'bg-accent-red/20 text-accent-red' :
                                               'bg-accent-orange/20 text-accent-orange animate-pulse'"
                                      x-text="pipe.status === 'completed' ? 'Concluido' :
                                              pipe.status === 'failed' ? 'Falhou' :
                                              pipe.status === 'started' ? 'Em andamento' : pipe.status"></span>
                            </div>

                            <!-- Progress Bar -->
                            <div class="mb-3">
                                <div class="flex items-center justify-between mb-1">
                                    <span class="text-[10px] text-white/40" x-text="'Etapa: ' + (pipe.current_stage || 'Aguardando')"></span>
                                    <span class="text-[10px] text-white/50 font-bold" x-text="(pipe.progress || 0) + '%'"></span>
                                </div>
                                <div class="w-full h-2 bg-dark-700 rounded-full overflow-hidden">
                                    <div class="h-full rounded-full transition-all duration-500"
                                         :class="pipe.status === 'completed' ? 'gradient-success' :
                                                  pipe.status === 'failed' ? 'gradient-fire' : 'gradient-brand'"
                                         :style="'width:' + (pipe.progress || 0) + '%'"></div>
                                </div>
                            </div>

                            <!-- Stage Indicators -->
                            <div class="flex items-center gap-1 flex-wrap">
                                <template x-for="(stage, stageName) in (pipe.stages || {})" :key="stageName">
                                    <div class="flex items-center gap-1 px-2 py-1 rounded-lg text-[10px]"
                                         :class="stage.status === 'completed' ? 'bg-accent-green/10 text-accent-green' :
                                                  stage.status === 'running' ? 'bg-accent-orange/10 text-accent-orange' :
                                                  stage.status === 'failed' ? 'bg-accent-red/10 text-accent-red' :
                                                  'bg-white/5 text-white/30'">
                                        <i :data-lucide="stage.status === 'completed' ? 'check-circle' :
                                                          stage.status === 'running' ? 'loader' :
                                                          stage.status === 'failed' ? 'x-circle' : 'circle'"
                                           class="w-3 h-3" :class="stage.status === 'running' && 'animate-spin'"></i>
                                        <span x-text="stageName"></span>
                                    </div>
                                </template>
                            </div>

                            <!-- Expand Details (for completed) -->
                            <template x-if="pipe.status === 'completed'">
                                <details class="mt-3">
                                    <summary class="text-xs text-brand-400 cursor-pointer hover:text-brand-300 transition">
                                        Ver resultados do pipeline
                                    </summary>
                                    <div class="mt-3 space-y-2">
                                        <template x-for="(stage, stageName) in (pipe.stages || {})" :key="stageName + '_detail'">
                                            <div x-show="stage.result" class="glass-light rounded-xl p-3">
                                                <h5 class="text-[10px] font-bold text-white/50 uppercase mb-1" x-text="stageName"></h5>
                                                <template x-if="stageName === 'script' && stage.result">
                                                    <div>
                                                        <p class="text-xs text-white/70 font-bold" x-text="stage.result?.title"></p>
                                                        <p class="text-[10px] text-white/40 mt-1" x-text="stage.result?.intro_hook"></p>
                                                        <p class="text-[10px] text-white/30 mt-1" x-text="(stage.result?.word_count || 0) + ' palavras | ~' + (stage.result?.estimated_duration_minutes || 0) + ' min'"></p>
                                                    </div>
                                                </template>
                                                <template x-if="stageName === 'narration' && stage.result">
                                                    <div>
                                                        <p class="text-[10px] text-white/40" x-text="'Voz: ' + (stage.result?.voice || 'N/A') + ' | Duracao: ' + (stage.result?.duration_formatted || 'N/A')"></p>
                                                        <p class="text-[10px] text-white/30" x-text="'Arquivo: ' + (stage.result?.filename || 'N/A')"></p>
                                                    </div>
                                                </template>
                                                <template x-if="stageName === 'footage' && stage.result">
                                                    <div>
                                                        <p class="text-[10px] text-white/40" x-text="(stage.result?.total_found || 0) + ' clips encontrados via ' + (stage.result?.source || 'N/A')"></p>
                                                    </div>
                                                </template>
                                                <template x-if="stageName === 'thumbnail' && stage.result">
                                                    <div>
                                                        <p class="text-xs text-white/70 font-bold" x-text="stage.result?.overlay_text"></p>
                                                        <p class="text-[10px] text-white/40" x-text="stage.result?.mood"></p>
                                                    </div>
                                                </template>
                                                <template x-if="stageName === 'seo' && stage.result">
                                                    <div>
                                                        <p class="text-xs text-white/70 font-bold" x-text="stage.result?.seo_title"></p>
                                                        <div class="flex flex-wrap gap-1 mt-1">
                                                            <template x-for="tag in (stage.result?.tags || []).slice(0, 8)" :key="tag">
                                                                <span class="px-1.5 py-0.5 rounded text-[9px] glass-light text-brand-300" x-text="tag"></span>
                                                            </template>
                                                        </div>
                                                    </div>
                                                </template>
                                            </div>
                                        </template>
                                    </div>
                                </details>
                            </template>

                            <!-- Error display -->
                            <div x-show="pipe.error" class="mt-3 glass-light rounded-xl p-3 border-l-2 border-accent-red">
                                <p class="text-[10px] text-accent-red" x-text="pipe.error"></p>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- ============================================================ -->
    <!-- TAB: SCRIPT GENERATOR                                        -->
    <!-- ============================================================ -->
    <div x-show="activeTab === 'script'" x-transition>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">

            <!-- Script 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-ocean flex items-center justify-center">
                        <i data-lucide="file-text" class="w-5 h-5"></i>
                    </div>
                    Gerar Roteiro Faceless
                </h3>
                <div class="space-y-4">
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Topico *</label>
                        <input x-model="scriptTopic" type="text"
                               placeholder="Ex: Os misterios nao resolvidos do oceano profundo"
                               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">Nicho</label>
                            <select x-model="scriptNiche"
                                    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="curiosidades">Curiosidades</option>
                                <option value="financas">Financas</option>
                                <option value="tecnologia">Tecnologia</option>
                                <option value="saude">Saude</option>
                                <option value="educacao">Educacao</option>
                                <option value="motivacao">Motivacao</option>
                                <option value="historia">Historia</option>
                                <option value="ciencia">Ciencia</option>
                                <option value="psicologia">Psicologia</option>
                                <option value="negocios">Negocios</option>
                            </select>
                        </div>
                        <div>
                            <label class="text-xs text-white/50 mb-1 block">Duracao (min)</label>
                            <input x-model.number="scriptDuration" type="number" min="5" max="30"
                                   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>
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Estilo de Narracao</label>
                        <select x-model="scriptStyle"
                                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="cinematic">Cinematico</option>
                            <option value="informativo">Informativo</option>
                            <option value="storytelling">Storytelling</option>
                            <option value="dramatico">Dramatico</option>
                        </select>
                    </div>
                    <button @click="generateScript()" :disabled="scriptLoading || !scriptTopic.trim()"
                            class="w-full py-3 rounded-xl gradient-brand text-white font-bold text-sm disabled:opacity-50 transition flex items-center justify-center gap-2">
                        <i data-lucide="sparkles" class="w-4 h-4" :class="scriptLoading && 'animate-spin'"></i>
                        <span x-text="scriptLoading ? 'Gerando roteiro...' : 'Gerar Roteiro com IA'"></span>
                    </button>
                </div>

                <!-- SEO Generator (show after script is generated) -->
                <div class="mt-5 border-t border-white/5 pt-5" x-show="scriptResult">
                    <h4 class="text-xs font-bold text-white/50 mb-3 flex items-center gap-1">
                        <i data-lucide="search" class="w-3 h-3"></i> Gerar SEO
                    </h4>
                    <button @click="generateSeo()" :disabled="seoLoading"
                            class="w-full py-2 rounded-xl glass-card text-white/70 text-xs font-bold hover:text-white hover:border-brand-400/30 transition disabled:opacity-50">
                        <span x-text="seoLoading ? 'Gerando SEO...' : 'Gerar Metadados SEO'"></span>
                    </button>
                </div>

                <!-- Thumbnail Prompt Generator -->
                <div class="mt-4" x-show="scriptResult">
                    <h4 class="text-xs font-bold text-white/50 mb-3 flex items-center gap-1">
                        <i data-lucide="image" class="w-3 h-3"></i> Gerar Prompt de Thumbnail
                    </h4>
                    <button @click="generateThumbnail()" :disabled="thumbLoading"
                            class="w-full py-2 rounded-xl glass-card text-white/70 text-xs font-bold hover:text-white hover:border-brand-400/30 transition disabled:opacity-50">
                        <span x-text="thumbLoading ? 'Gerando...' : 'Gerar Prompt de Thumbnail'"></span>
                    </button>
                </div>
            </div>

            <!-- Script Preview -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                    <i data-lucide="eye" class="w-5 h-5 text-brand-400"></i> Preview do Roteiro
                </h3>

                <!-- Empty State -->
                <div x-show="!scriptResult && !scriptLoading" class="text-center py-16">
                    <i data-lucide="file-text" class="w-16 h-16 text-white/10 mx-auto mb-3"></i>
                    <p class="text-sm text-white/30">Preencha o formulario e clique em "Gerar" para criar seu roteiro faceless</p>
                </div>

                <!-- Loading Skeleton -->
                <div x-show="scriptLoading" class="space-y-3">
                    <div class="skeleton h-6 w-3/4"></div>
                    <div class="skeleton h-4 w-full"></div>
                    <div class="skeleton h-4 w-5/6"></div>
                    <div class="skeleton h-20 w-full"></div>
                    <div class="skeleton h-20 w-full"></div>
                    <div class="skeleton h-20 w-full"></div>
                </div>

                <!-- Generated Script -->
                <div x-show="scriptResult && !scriptLoading" x-transition>
                    <!-- Title -->
                    <div class="mb-4">
                        <h4 class="text-base font-bold text-white/90" x-text="scriptResult?.title"></h4>
                        <div class="flex items-center gap-3 mt-1 text-[10px] text-white/40">
                            <span x-text="(scriptResult?.word_count || 0) + ' palavras'"></span>
                            <span>|</span>
                            <span x-text="'~' + (scriptResult?.estimated_duration_minutes || 0) + ' min'"></span>
                            <span>|</span>
                            <span x-text="scriptResult?.niche"></span>
                        </div>
                    </div>

                    <!-- Hook -->
                    <div class="mb-4">
                        <div class="flex items-center gap-2 mb-1">
                            <span class="px-2 py-0.5 rounded text-[10px] font-bold gradient-fire text-white">HOOK</span>
                        </div>
                        <div class="glass-light rounded-xl p-3 text-sm text-white/80 border-l-2 border-accent-orange"
                             x-text="scriptResult?.intro_hook"></div>
                    </div>

                    <!-- Sections -->
                    <div class="space-y-3 mb-4">
                        <template x-for="section in (scriptResult?.sections || [])" :key="section.number">
                            <div class="glass-light rounded-xl p-3">
                                <div class="flex items-center gap-2 mb-2">
                                    <span class="w-6 h-6 rounded-lg gradient-brand flex items-center justify-center text-[10px] font-bold"
                                          x-text="section.number"></span>
                                    <span class="text-xs font-bold text-white/70" x-text="section.subtitle"></span>
                                    <span class="text-[10px] text-white/30 ml-auto" x-text="section.duration_seconds + 's'"></span>
                                </div>
                                <p class="text-xs text-white/60 leading-relaxed" x-text="section.narration"></p>
                                <div class="mt-2 flex items-start gap-1">
                                    <i data-lucide="video" class="w-3 h-3 text-brand-400 mt-0.5 flex-shrink-0"></i>
                                    <p class="text-[10px] text-brand-300/60" x-text="section.visual_direction"></p>
                                </div>
                            </div>
                        </template>
                    </div>

                    <!-- Outro -->
                    <div class="mb-4" x-show="scriptResult?.outro">
                        <div class="flex items-center gap-2 mb-1">
                            <span class="px-2 py-0.5 rounded text-[10px] font-bold gradient-success text-white">OUTRO</span>
                        </div>
                        <div class="glass-light rounded-xl p-3 text-sm text-white/80 border-l-2 border-accent-green"
                             x-text="scriptResult?.outro"></div>
                    </div>

                    <!-- Tags -->
                    <div class="flex flex-wrap gap-1 mb-4">
                        <template x-for="tag in (scriptResult?.tags || [])" :key="tag">
                            <span class="px-2 py-0.5 rounded text-[10px] glass-light text-brand-300" x-text="tag"></span>
                        </template>
                    </div>

                    <!-- Full Script (collapsible) -->
                    <details class="glass-light rounded-xl p-3 mb-4">
                        <summary class="text-xs font-bold text-white/50 cursor-pointer">Ver roteiro completo</summary>
                        <pre class="text-xs text-white/60 whitespace-pre-wrap mt-2 leading-relaxed" x-text="scriptResult?.full_script"></pre>
                    </details>

                    <!-- SEO Result -->
                    <div x-show="seoResult" x-transition class="glass-light rounded-xl p-4 mb-4 border-l-2 border-brand-400">
                        <h5 class="text-xs font-bold text-white/60 mb-2 flex items-center gap-1">
                            <i data-lucide="search" class="w-3 h-3"></i> SEO Otimizado
                        </h5>
                        <p class="text-xs text-white/80 font-bold" x-text="seoResult?.seo_title"></p>
                        <div x-show="seoResult?.seo_title_alternatives" class="mt-2">
                            <p class="text-[10px] text-white/40 mb-1">Alternativas:</p>
                            <template x-for="alt in (seoResult?.seo_title_alternatives || [])" :key="alt">
                                <p class="text-[10px] text-white/50" x-text="'- ' + alt"></p>
                            </template>
                        </div>
                        <div class="flex flex-wrap gap-1 mt-2">
                            <template x-for="tag in (seoResult?.tags || []).slice(0, 10)" :key="tag">
                                <span class="px-1.5 py-0.5 rounded text-[9px] bg-brand-500/15 text-brand-300" x-text="tag"></span>
                            </template>
                        </div>
                        <details class="mt-2">
                            <summary class="text-[10px] text-white/40 cursor-pointer">Ver descricao completa</summary>
                            <pre class="text-[10px] text-white/50 whitespace-pre-wrap mt-1 leading-relaxed" x-text="seoResult?.description"></pre>
                        </details>
                    </div>

                    <!-- Thumbnail Result -->
                    <div x-show="thumbnailResult" x-transition class="glass-light rounded-xl p-4 mb-4 border-l-2 border-accent-pink">
                        <h5 class="text-xs font-bold text-white/60 mb-2 flex items-center gap-1">
                            <i data-lucide="image" class="w-3 h-3"></i> Thumbnail
                        </h5>
                        <p class="text-sm text-white/80 font-bold" x-text="thumbnailResult?.overlay_text"></p>
                        <p class="text-[10px] text-white/40 mt-1" x-text="'Mood: ' + (thumbnailResult?.mood || '')"></p>
                        <p class="text-[10px] text-white/40" x-text="'Composicao: ' + (thumbnailResult?.composition || '')"></p>
                        <div x-show="thumbnailResult?.color_scheme" class="flex items-center gap-2 mt-2">
                            <template x-for="(hex, name) in (thumbnailResult?.color_scheme || {})" :key="name">
                                <div class="flex items-center gap-1">
                                    <div class="w-4 h-4 rounded" :style="'background:' + hex"></div>
                                    <span class="text-[9px] text-white/30" x-text="name"></span>
                                </div>
                            </template>
                        </div>
                        <details class="mt-2">
                            <summary class="text-[10px] text-white/40 cursor-pointer">Ver prompt para IA de imagem</summary>
                            <p class="text-[10px] text-accent-cyan/70 mt-1 leading-relaxed" x-text="thumbnailResult?.ai_image_prompt"></p>
                        </details>
                    </div>

                    <!-- Actions -->
                    <div class="flex gap-2 flex-wrap">
                        <button @click="copyScript()" class="px-4 py-2 rounded-xl gradient-brand text-white text-xs font-bold flex items-center gap-1">
                            <i data-lucide="copy" class="w-3 h-3"></i> Copiar Roteiro
                        </button>
                        <button @click="generateScript()" class="px-4 py-2 rounded-xl glass-card text-white/70 text-xs font-bold hover:text-white">
                            Regenerar
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ============================================================ -->
    <!-- TAB: BATCH PRODUCTION                                        -->
    <!-- ============================================================ -->
    <div x-show="activeTab === 'batch'" x-transition>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">

            <!-- Batch 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-fire flex items-center justify-center">
                        <i data-lucide="layers" class="w-5 h-5"></i>
                    </div>
                    Producao em Lote
                </h3>
                <p class="text-xs text-white/40 mb-4">Insira um topico por linha para criar multiplos pipelines de uma vez.</p>

                <div class="space-y-4">
                    <!-- Topics textarea -->
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Topicos (um por linha) *</label>
                        <textarea x-model="batchTopics" rows="8"
                                  placeholder="A verdade sobre o Triangulo das Bermudas&#10;10 fatos surpreendentes sobre o espaco&#10;Historia do Egito Antigo&#10;Misterios do oceano profundo&#10;Como o cerebro humano funciona"
                                  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>
                        <p class="text-[10px] text-white/30 mt-1">
                            <span x-text="batchTopics.split('\\n').filter(t => t.trim()).length"></span> topico(s) detectado(s)
                        </p>
                    </div>

                    <div class="grid grid-cols-2 gap-3">
                        <!-- Niche -->
                        <div>
                            <label class="text-xs text-white/50 mb-1 block">Nicho</label>
                            <select x-model="niche"
                                    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="curiosidades">Curiosidades</option>
                                <option value="financas">Financas</option>
                                <option value="tecnologia">Tecnologia</option>
                                <option value="saude">Saude</option>
                                <option value="educacao">Educacao</option>
                                <option value="motivacao">Motivacao</option>
                                <option value="historia">Historia</option>
                                <option value="ciencia">Ciencia</option>
                                <option value="psicologia">Psicologia</option>
                                <option value="negocios">Negocios</option>
                            </select>
                        </div>
                        <!-- Duration -->
                        <div>
                            <label class="text-xs text-white/50 mb-1 block">Duracao (min)</label>
                            <input x-model.number="duration" type="number" min="5" max="30"
                                   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>

                    <!-- Start Batch Button -->
                    <button @click="startBatch()" :disabled="batchLoading || !batchTopics.trim()"
                            class="w-full py-3 rounded-xl gradient-brand text-white font-bold text-sm disabled:opacity-50 transition flex items-center justify-center gap-2">
                        <i data-lucide="rocket" class="w-4 h-4" :class="batchLoading && 'animate-spin'"></i>
                        <span x-text="batchLoading ? 'Iniciando lote...' : 'Iniciar Producao em Lote'"></span>
                    </button>
                </div>
            </div>

            <!-- Batch Status -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                    <i data-lucide="activity" class="w-5 h-5 text-brand-400"></i> Status do Lote
                </h3>

                <!-- Empty State -->
                <div x-show="!batchResult && !batchLoading" class="text-center py-16">
                    <i data-lucide="layers" class="w-16 h-16 text-white/10 mx-auto mb-3"></i>
                    <p class="text-sm text-white/30">Nenhuma producao em lote iniciada</p>
                    <p class="text-xs text-white/20 mt-1">Insira topicos e clique em "Iniciar" para comecar</p>
                </div>

                <!-- Loading -->
                <div x-show="batchLoading" class="text-center py-12">
                    <div class="w-12 h-12 rounded-full gradient-brand mx-auto mb-3 animate-pulse-glow flex items-center justify-center">
                        <i data-lucide="loader" class="w-6 h-6 animate-spin"></i>
                    </div>
                    <p class="text-sm text-white/50">Iniciando pipelines em lote...</p>
                </div>

                <!-- Batch Result -->
                <div x-show="batchResult && !batchLoading" x-transition>
                    <div class="glass-light rounded-xl p-4 mb-4 border-l-2 border-accent-green">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-xl gradient-success flex items-center justify-center flex-shrink-0">
                                <i data-lucide="check-circle" class="w-5 h-5"></i>
                            </div>
                            <div>
                                <p class="text-sm font-bold text-white/90">Lote Iniciado!</p>
                                <p class="text-[10px] text-white/40" x-text="(batchResult?.total_queued || 0) + ' pipelines na fila'"></p>
                            </div>
                        </div>
                    </div>

                    <!-- Pipeline IDs -->
                    <div class="space-y-2">
                        <template x-for="(pipeId, idx) in (batchResult?.pipeline_ids || [])" :key="pipeId">
                            <div class="glass-light rounded-xl p-3 flex items-center justify-between">
                                <div class="flex items-center gap-2">
                                    <span class="w-6 h-6 rounded-lg gradient-brand flex items-center justify-center text-[10px] font-bold" x-text="idx + 1"></span>
                                    <span class="text-xs text-white/60 font-mono" x-text="pipeId"></span>
                                </div>
                                <span class="px-2 py-0.5 rounded text-[10px] bg-accent-orange/20 text-accent-orange">Aguardando</span>
                            </div>
                        </template>
                    </div>

                    <!-- Go to History -->
                    <button @click="activeTab = 'history'; loadHistory()"
                            class="mt-4 w-full py-2 rounded-xl glass-card text-brand-400 text-xs font-bold hover:text-brand-300 transition flex items-center justify-center gap-1">
                        <i data-lucide="history" class="w-3 h-3"></i> Ver no Pipeline History
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- ============================================================ -->
    <!-- TAB: PIPELINE HISTORY                                        -->
    <!-- ============================================================ -->
    <div x-show="activeTab === 'history'" x-transition>
        <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-bold text-white/90 flex items-center gap-2">
                <i data-lucide="history" class="w-5 h-5 text-brand-400"></i> Historico de Pipelines
            </h3>
            <div class="flex items-center gap-3">
                <!-- Status Filter -->
                <select x-model="historyFilter"
                        class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-xs text-white/80 focus:border-brand-400 focus:outline-none">
                    <option value="all">Todos</option>
                    <option value="pending">Pendente</option>
                    <option value="started">Em andamento</option>
                    <option value="completed">Concluido</option>
                    <option value="failed">Falhou</option>
                </select>
                <button @click="loadHistory()" class="text-xs text-white/40 hover:text-white/70 flex items-center gap-1 transition">
                    <i data-lucide="refresh-cw" class="w-3 h-3" :class="historyLoading && 'animate-spin'"></i> Atualizar
                </button>
            </div>
        </div>

        <!-- Loading -->
        <div x-show="historyLoading" class="space-y-3">
            <template x-for="i in 5" :key="i">
                <div class="glass-card rounded-xl p-4">
                    <div class="skeleton h-5 w-1/2 mb-2"></div>
                    <div class="skeleton h-3 w-3/4"></div>
                </div>
            </template>
        </div>

        <!-- Empty State -->
        <div x-show="filteredPipelines.length === 0 && !historyLoading" class="glass-card rounded-2xl p-12 text-center">
            <i data-lucide="inbox" class="w-16 h-16 text-white/10 mx-auto mb-3"></i>
            <p class="text-sm text-white/30">Nenhum pipeline encontrado</p>
            <p class="text-xs text-white/20 mt-1">Inicie um pipeline na aba "Pipeline Creator" para comecar</p>
        </div>

        <!-- Pipeline List -->
        <div x-show="!historyLoading" class="space-y-3">
            <template x-for="pipe in filteredPipelines" :key="pipe.id">
                <div class="glass-card rounded-xl p-4 cursor-pointer" @click="togglePipelineDetails(pipe.id)">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-3 flex-1 min-w-0">
                            <!-- Status Icon -->
                            <div class="w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0"
                                 :class="pipe.status === 'completed' ? 'bg-accent-green/15' :
                                          pipe.status === 'failed' ? 'bg-accent-red/15' :
                                          pipe.status === 'started' ? 'bg-accent-orange/15' :
                                          'bg-white/5'">
                                <i :data-lucide="pipe.status === 'completed' ? 'check-circle' :
                                                  pipe.status === 'failed' ? 'x-circle' :
                                                  pipe.status === 'started' ? 'loader' : 'clock'"
                                   class="w-5 h-5"
                                   :class="pipe.status === 'completed' ? 'text-accent-green' :
                                            pipe.status === 'failed' ? 'text-accent-red' :
                                            pipe.status === 'started' ? 'text-accent-orange animate-spin' :
                                            'text-white/30'"></i>
                            </div>
                            <div class="min-w-0">
                                <h4 class="text-sm font-bold text-white/90 truncate" x-text="pipe.topic"></h4>
                                <div class="flex items-center gap-2 mt-0.5">
                                    <span class="px-2 py-0.5 rounded text-[10px] font-bold bg-brand-500/20 text-brand-300" x-text="pipe.niche"></span>
                                    <span class="text-[10px] text-white/30" x-text="pipe.created_at"></span>
                                    <span class="text-[10px] text-white/20" x-text="pipe.duration_minutes ? pipe.duration_minutes + ' min' : ''"></span>
                                </div>
                            </div>
                        </div>
                        <div class="flex items-center gap-3">
                            <!-- Progress -->
                            <div class="hidden md:flex items-center gap-2 w-32">
                                <div class="flex-1 h-1.5 bg-dark-700 rounded-full overflow-hidden">
                                    <div class="h-full rounded-full transition-all"
                                         :class="pipe.status === 'completed' ? 'gradient-success' :
                                                  pipe.status === 'failed' ? 'gradient-fire' : 'gradient-brand'"
                                         :style="'width:' + (pipe.progress || 0) + '%'"></div>
                                </div>
                                <span class="text-[10px] text-white/40 font-bold w-8 text-right" x-text="(pipe.progress || 0) + '%'"></span>
                            </div>
                            <!-- Status Badge -->
                            <span class="px-2 py-1 rounded-lg text-[10px] font-bold whitespace-nowrap"
                                  :class="pipe.status === 'completed' ? 'bg-accent-green/20 text-accent-green' :
                                           pipe.status === 'failed' ? 'bg-accent-red/20 text-accent-red' :
                                           pipe.status === 'started' ? 'bg-accent-orange/20 text-accent-orange' :
                                           'bg-white/10 text-white/40'"
                                  x-text="pipe.status === 'completed' ? 'Concluido' :
                                          pipe.status === 'failed' ? 'Falhou' :
                                          pipe.status === 'started' ? 'Em andamento' :
                                          pipe.status === 'pending' ? 'Pendente' : pipe.status"></span>
                            <!-- Expand arrow -->
                            <i data-lucide="chevron-down" class="w-4 h-4 text-white/20 transition-transform"
                               :class="expandedPipeline === pipe.id && 'rotate-180'"></i>
                        </div>
                    </div>

                    <!-- Expanded Details -->
                    <div x-show="expandedPipeline === pipe.id" x-transition class="mt-4 border-t border-white/5 pt-4" @click.stop>
                        <!-- Stage Indicators -->
                        <div class="flex items-center gap-1 flex-wrap mb-3">
                            <template x-for="(stage, stageName) in (pipe.stages || {})" :key="stageName">
                                <div class="flex items-center gap-1 px-2 py-1 rounded-lg text-[10px]"
                                     :class="stage.status === 'completed' ? 'bg-accent-green/10 text-accent-green' :
                                              stage.status === 'running' ? 'bg-accent-orange/10 text-accent-orange' :
                                              stage.status === 'failed' ? 'bg-accent-red/10 text-accent-red' :
                                              'bg-white/5 text-white/30'">
                                    <i :data-lucide="stage.status === 'completed' ? 'check-circle' :
                                                      stage.status === 'running' ? 'loader' :
                                                      stage.status === 'failed' ? 'x-circle' : 'circle'"
                                       class="w-3 h-3" :class="stage.status === 'running' && 'animate-spin'"></i>
                                    <span x-text="stageName"></span>
                                </div>
                            </template>
                        </div>

                        <!-- Stage Results -->
                        <div class="space-y-2">
                            <template x-for="(stage, stageName) in (pipe.stages || {})" :key="stageName + '_hist'">
                                <div x-show="stage.result" class="glass-light rounded-xl p-3">
                                    <h5 class="text-[10px] font-bold text-white/50 uppercase mb-1" x-text="stageName"></h5>
                                    <template x-if="stageName === 'script' && stage.result">
                                        <div>
                                            <p class="text-xs text-white/70 font-bold" x-text="stage.result?.title"></p>
                                            <p class="text-[10px] text-white/40 mt-1" x-text="stage.result?.intro_hook"></p>
                                            <p class="text-[10px] text-white/30 mt-1" x-text="(stage.result?.word_count || 0) + ' palavras | ~' + (stage.result?.estimated_duration_minutes || 0) + ' min'"></p>
                                        </div>
                                    </template>
                                    <template x-if="stageName === 'narration' && stage.result">
                                        <div>
                                            <p class="text-[10px] text-white/40" x-text="'Voz: ' + (stage.result?.voice || 'N/A') + ' | Duracao: ' + (stage.result?.duration_formatted || 'N/A')"></p>
                                        </div>
                                    </template>
                                    <template x-if="stageName === 'footage' && stage.result">
                                        <div>
                                            <p class="text-[10px] text-white/40" x-text="(stage.result?.total_found || 0) + ' clips encontrados via ' + (stage.result?.source || 'N/A')"></p>
                                        </div>
                                    </template>
                                    <template x-if="stageName === 'thumbnail' && stage.result">
                                        <div>
                                            <p class="text-xs text-white/70 font-bold" x-text="stage.result?.overlay_text"></p>
                                            <p class="text-[10px] text-white/40" x-text="stage.result?.mood"></p>
                                        </div>
                                    </template>
                                    <template x-if="stageName === 'seo' && stage.result">
                                        <div>
                                            <p class="text-xs text-white/70 font-bold" x-text="stage.result?.seo_title"></p>
                                            <div class="flex flex-wrap gap-1 mt-1">
                                                <template x-for="tag in (stage.result?.tags || []).slice(0, 8)" :key="tag">
                                                    <span class="px-1.5 py-0.5 rounded text-[9px] glass-light text-brand-300" x-text="tag"></span>
                                                </template>
                                            </div>
                                        </div>
                                    </template>
                                </div>
                            </template>
                        </div>

                        <!-- Error display -->
                        <div x-show="pipe.error" class="mt-3 glass-light rounded-xl p-3 border-l-2 border-accent-red">
                            <p class="text-[10px] text-accent-red font-bold mb-1">Erro:</p>
                            <p class="text-[10px] text-accent-red/80" x-text="pipe.error"></p>
                        </div>
                    </div>
                </div>
            </template>
        </div>
    </div>

    <!-- ============================================================ -->
    <!-- TAB: STATISTICS                                              -->
    <!-- ============================================================ -->
    <div x-show="activeTab === 'stats'" x-transition>
        <!-- Loading -->
        <div x-show="statsLoading" class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
            <template x-for="i in 4" :key="i">
                <div class="glass-card rounded-2xl p-5">
                    <div class="skeleton h-8 w-16 mb-2"></div>
                    <div class="skeleton h-4 w-24"></div>
                </div>
            </template>
        </div>

        <div x-show="!statsLoading">
            <!-- Overview Cards -->
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
                <div class="glass-card rounded-2xl p-5 text-center">
                    <p class="stat-number text-gradient" x-text="stats?.total_pipelines || 0"></p>
                    <p class="text-xs text-white/40 mt-1">Total Pipelines</p>
                </div>
                <div class="glass-card rounded-2xl p-5 text-center">
                    <p class="stat-number text-accent-green" x-text="stats?.completed || 0"></p>
                    <p class="text-xs text-white/40 mt-1">Concluidos</p>
                </div>
                <div class="glass-card rounded-2xl p-5 text-center">
                    <p class="stat-number text-accent-orange" x-text="stats?.running || 0"></p>
                    <p class="text-xs text-white/40 mt-1">Em Andamento</p>
                </div>
                <div class="glass-card rounded-2xl p-5 text-center">
                    <p class="stat-number text-accent-red" x-text="stats?.failed || 0"></p>
                    <p class="text-xs text-white/40 mt-1">Falhas</p>
                </div>
            </div>

            <!-- Second Row -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <!-- Success Rate -->
                <div class="glass-card rounded-2xl p-5">
                    <h4 class="text-xs font-bold text-white/50 mb-3 flex items-center gap-2">
                        <i data-lucide="target" class="w-4 h-4 text-brand-400"></i> Taxa de Sucesso
                    </h4>
                    <div class="flex items-center gap-4">
                        <p class="text-3xl font-bold"
                           :class="(stats?.success_rate || 0) >= 80 ? 'text-accent-green' :
                                    (stats?.success_rate || 0) >= 50 ? 'text-accent-orange' : 'text-accent-red'"
                           x-text="(stats?.success_rate || 0) + '%'"></p>
                        <div class="flex-1">
                            <div class="w-full h-3 bg-dark-700 rounded-full overflow-hidden">
                                <div class="h-full rounded-full gradient-success transition-all"
                                     :style="'width:' + (stats?.success_rate || 0) + '%'"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Content Produced -->
                <div class="glass-card rounded-2xl p-5">
                    <h4 class="text-xs font-bold text-white/50 mb-3 flex items-center gap-2">
                        <i data-lucide="clock" class="w-4 h-4 text-brand-400"></i> Conteudo Produzido
                    </h4>
                    <p class="text-2xl font-bold text-white/90" x-text="stats?.total_content_formatted || '0h 0min'"></p>
                    <p class="text-[10px] text-white/30 mt-1">Tempo medio por pipeline: <span x-text="stats?.avg_pipeline_time_formatted || 'N/A'"></span></p>
                </div>

                <!-- Revenue Estimate -->
                <div class="glass-card rounded-2xl p-5">
                    <h4 class="text-xs font-bold text-white/50 mb-3 flex items-center gap-2">
                        <i data-lucide="dollar-sign" class="w-4 h-4 text-accent-green"></i> Receita Estimada
                    </h4>
                    <p class="text-2xl font-bold text-accent-green">R$ <span x-text="(stats?.estimated_total_revenue_brl || 0).toLocaleString('pt-BR', {minimumFractionDigits: 2})"></span></p>
                    <div class="flex items-center justify-between mt-2">
                        <span class="text-[10px] text-white/30">Custo total</span>
                        <span class="text-xs font-bold text-accent-green">R$ 0,00</span>
                    </div>
                    <div class="flex items-center justify-between mt-1">
                        <span class="text-[10px] text-white/30">Margem de lucro</span>
                        <span class="text-xs font-bold text-accent-green" x-text="stats?.profit_margin || '100%'"></span>
                    </div>
                </div>
            </div>

            <!-- Stage Stats -->
            <div class="glass-card rounded-2xl p-5 mb-6">
                <h4 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                    <i data-lucide="git-branch" class="w-4 h-4 text-brand-400"></i> Performance por Etapa
                </h4>
                <div class="grid grid-cols-2 md:grid-cols-5 gap-3">
                    <template x-for="(stage, name) in (stats?.stage_stats || {})" :key="name">
                        <div class="glass-light rounded-xl p-3 text-center">
                            <p class="text-xs font-bold text-white/60 capitalize mb-2" x-text="name"></p>
                            <div class="flex items-center justify-center gap-2 text-[10px]">
                                <span class="text-accent-green" x-text="stage.completed + ' ok'"></span>
                                <span class="text-white/20">|</span>
                                <span class="text-accent-red" x-text="stage.failed + ' err'"></span>
                            </div>
                            <div class="w-full h-1.5 bg-dark-700 rounded-full overflow-hidden mt-2">
                                <div class="h-full rounded-full gradient-success"
                                     :style="'width:' + (stage.total > 0 ? (stage.completed / stage.total * 100) : 0) + '%'"></div>
                            </div>
                        </div>
                    </template>
                </div>
            </div>

            <!-- Niche Distribution Chart + Table -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                <!-- Chart -->
                <div class="glass-card rounded-2xl p-5">
                    <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 por Nicho
                    </h4>
                    <div class="relative" style="height: 280px;">
                        <canvas id="nicheChart"></canvas>
                    </div>
                </div>

                <!-- Niche Table -->
                <div class="glass-card rounded-2xl p-5">
                    <h4 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                        <i data-lucide="list" class="w-4 h-4 text-brand-400"></i> Detalhes por Nicho
                    </h4>
                    <div x-show="Object.keys(stats?.niche_distribution || {}).length === 0" class="text-center py-8">
                        <p class="text-xs text-white/30">Nenhum pipeline executado ainda</p>
                    </div>
                    <div class="space-y-2">
                        <template x-for="(count, nicheName) in (stats?.niche_distribution || {})" :key="nicheName">
                            <div class="glass-light rounded-xl p-3 flex items-center justify-between">
                                <div class="flex items-center gap-2">
                                    <span class="w-3 h-3 rounded-full" :style="'background:' + getNicheColor(nicheName)"></span>
                                    <span class="text-xs font-bold text-white/70 capitalize" x-text="nicheName.replace('_', ' ')"></span>
                                </div>
                                <div class="flex items-center gap-3">
                                    <span class="text-sm font-bold text-gradient" x-text="count"></span>
                                    <span class="text-[10px] text-white/30">videos</span>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
            </div>

            <!-- System Info -->
            <div class="glass-light rounded-xl p-4">
                <div class="flex items-center justify-between flex-wrap gap-4">
                    <div class="flex items-center gap-4 text-[10px] text-white/30">
                        <span>Nichos disponiveis: <strong class="text-white/50" x-text="stats?.available_niches || 0"></strong></span>
                        <span>Vozes disponiveis: <strong class="text-white/50" x-text="stats?.available_voices || 0"></strong></span>
                    </div>
                    <button @click="loadStats()" class="text-xs text-brand-400 hover:text-brand-300 flex items-center gap-1 transition">
                        <i data-lucide="refresh-cw" class="w-3 h-3"></i> Atualizar
                    </button>
                </div>
            </div>
        </div>
    </div>

</div>
{% endblock %}

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

        // Pipeline form
        topic: '',
        niche: 'curiosidades',
        duration: 10,
        voice: 'pt-BR-AntonioNeural',
        style: 'cinematic',
        pipelineLoading: false,
        pipelineResult: null,

        // Script
        scriptTopic: '',
        scriptNiche: 'curiosidades',
        scriptDuration: 10,
        scriptStyle: 'cinematic',
        scriptLoading: false,
        scriptResult: null,

        // SEO / Thumbnail
        seoLoading: false,
        seoResult: null,
        thumbLoading: false,
        thumbnailResult: null,

        // Batch
        batchTopics: '',
        batchLoading: false,
        batchResult: null,

        // History
        pipelines: [],
        historyLoading: false,
        historyFilter: 'all',
        expandedPipeline: null,

        // Stats
        stats: null,
        statsLoading: false,

        // Niches info
        niches: null,

        // Cost estimate
        costEstimate: null,

        // Active pipelines (shown on pipeline tab)
        refreshingPipelines: false,
        refreshInterval: null,

        // Niche chart
        nicheChartInstance: null,

        // Niche color map
        nicheColors: {
            'curiosidades': '#a78bfa',
            'financas': '#10b981',
            'tecnologia': '#06b6d4',
            'saude': '#ec4899',
            'educacao': '#f59e0b',
            'motivacao': '#f97316',
            'historia': '#8b5cf6',
            'ciencia': '#3b82f6',
            'psicologia': '#14b8a6',
            'negocios': '#6366f1',
            'true_crime': '#ef4444',
            'top_listas': '#eab308',
            'misterios': '#7c3aed',
        },

        get activePipelines() {
            return this.pipelines.filter(p => p.status === 'started' || p.status === 'pending');
        },

        get filteredPipelines() {
            if (this.historyFilter === 'all') return this.pipelines;
            return this.pipelines.filter(p => p.status === this.historyFilter);
        },

        async init() {
            this.loadNiches();
            this.refreshPipelines();
            // Auto-refresh pipelines every 5 seconds if any are running
            this.refreshInterval = setInterval(() => {
                const hasRunning = this.pipelines.some(p => p.status === 'started' || p.status === 'pending');
                if (hasRunning) {
                    this.refreshPipelines(true);
                }
            }, 5000);
            this.$nextTick(() => { if (typeof lucide !== 'undefined') lucide.createIcons(); });
        },

        destroy() {
            if (this.refreshInterval) clearInterval(this.refreshInterval);
        },

        // ---- Pipeline Creator ----

        async startPipeline() {
            if (!this.topic.trim() || this.pipelineLoading) return;
            this.pipelineLoading = true;
            this.pipelineResult = null;
            try {
                const r = await fetch('/api/dark-factory/pipeline', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        topic: this.topic,
                        niche: this.niche,
                        duration_minutes: this.duration,
                        voice: this.voice,
                        style: this.style,
                    }),
                });
                const data = await r.json();
                if (r.ok) {
                    this.pipelineResult = data;
                    this.showToast('Pipeline iniciado: ' + data.pipeline_id, 'success');
                    this.topic = '';
                    setTimeout(() => this.refreshPipelines(), 1000);
                } else {
                    this.showToast(data.detail || 'Erro ao iniciar pipeline', 'error');
                }
            } catch (e) {
                this.showToast('Erro de conexao: ' + e.message, 'error');
            }
            this.pipelineLoading = false;
        },

        async refreshPipelines(silent = false) {
            if (!silent) this.refreshingPipelines = true;
            try {
                const r = await fetch('/api/dark-factory/pipelines?limit=50');
                const data = await r.json();
                if (r.ok) {
                    const detailed = [];
                    for (const pipe of (data.pipelines || [])) {
                        try {
                            const dr = await fetch('/api/dark-factory/pipeline/' + pipe.id);
                            if (dr.ok) {
                                detailed.push(await dr.json());
                            } else {
                                detailed.push(pipe);
                            }
                        } catch {
                            detailed.push(pipe);
                        }
                    }
                    this.pipelines = detailed;
                }
            } catch (e) {
                if (!silent) console.error('Error refreshing pipelines:', e);
            }
            this.refreshingPipelines = false;
            this.$nextTick(() => { if (typeof lucide !== 'undefined') lucide.createIcons(); });
        },

        async loadCostEstimate() {
            try {
                const r = await fetch(`/api/dark-factory/cost-estimate?duration_minutes=${this.duration}&footage_clips=10`);
                if (r.ok) {
                    this.costEstimate = await r.json();
                }
            } catch (e) {
                console.error('Cost estimate error:', e);
            }
        },

        async loadNiches() {
            try {
                const r = await fetch('/api/dark-factory/niches');
                if (r.ok) {
                    this.niches = await r.json();
                }
            } catch (e) {
                console.error('Error loading niches:', e);
            }
        },

        getCurrentNicheInfo() {
            if (!this.niches?.niches) return null;
            return this.niches.niches.find(n => n.niche === this.niche);
        },

        // ---- Script Generator ----

        async generateScript() {
            if (!this.scriptTopic.trim() || this.scriptLoading) return;
            this.scriptLoading = true;
            this.scriptResult = null;
            this.seoResult = null;
            this.thumbnailResult = null;
            try {
                const r = await fetch('/api/dark-factory/script', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        topic: this.scriptTopic,
                        niche: this.scriptNiche,
                        duration_minutes: this.scriptDuration,
                        style: this.scriptStyle,
                    }),
                });
                const data = await r.json();
                if (r.ok) {
                    this.scriptResult = data;
                    this.showToast('Roteiro gerado com sucesso!', 'success');
                } else {
                    this.showToast(data.detail || 'Erro ao gerar roteiro', 'error');
                }
            } catch (e) {
                this.showToast('Erro: ' + e.message, 'error');
            }
            this.scriptLoading = false;
            this.$nextTick(() => { if (typeof lucide !== 'undefined') lucide.createIcons(); });
        },

        async generateSeo() {
            if (!this.scriptResult) return;
            this.seoLoading = true;
            try {
                const r = await fetch('/api/dark-factory/seo', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        title: this.scriptResult.title,
                        niche: this.scriptResult.niche || this.scriptNiche,
                        script_summary: this.scriptResult.intro_hook || '',
                    }),
                });
                if (r.ok) {
                    this.seoResult = await r.json();
                    this.showToast('SEO gerado!', 'success');
                }
            } catch (e) {
                this.showToast('Erro ao gerar SEO: ' + e.message, 'error');
            }
            this.seoLoading = false;
            this.$nextTick(() => { if (typeof lucide !== 'undefined') lucide.createIcons(); });
        },

        async generateThumbnail() {
            if (!this.scriptResult) return;
            this.thumbLoading = true;
            try {
                const r = await fetch('/api/dark-factory/thumbnail-prompt', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        title: this.scriptResult.title,
                        niche: this.scriptResult.niche || this.scriptNiche,
                    }),
                });
                if (r.ok) {
                    this.thumbnailResult = await r.json();
                    this.showToast('Prompt de thumbnail gerado!', 'success');
                }
            } catch (e) {
                this.showToast('Erro: ' + e.message, 'error');
            }
            this.thumbLoading = false;
            this.$nextTick(() => { if (typeof lucide !== 'undefined') lucide.createIcons(); });
        },

        copyScript() {
            if (!this.scriptResult?.full_script) return;
            navigator.clipboard.writeText(this.scriptResult.full_script).then(() => {
                this.showToast('Roteiro copiado!', 'success');
            }).catch(() => {
                this.showToast('Erro ao copiar', 'error');
            });
        },

        // ---- Batch Production ----

        async startBatch() {
            const topics = this.batchTopics.split('\n').filter(t => t.trim());
            if (topics.length === 0 || this.batchLoading) return;
            this.batchLoading = true;
            this.batchResult = null;
            try {
                const r = await fetch('/api/dark-factory/batch', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        topics: topics.map(t => t.trim()),
                        niche: this.niche,
                        duration_minutes: this.duration,
                    }),
                });
                const data = await r.json();
                if (r.ok) {
                    this.batchResult = data;
                    this.showToast((data.total_queued || topics.length) + ' pipelines iniciados em lote!', 'success');
                    this.batchTopics = '';
                    setTimeout(() => this.refreshPipelines(), 2000);
                } else {
                    this.showToast(data.detail || 'Erro no lote', 'error');
                }
            } catch (e) {
                this.showToast('Erro: ' + e.message, 'error');
            }
            this.batchLoading = false;
        },

        // ---- Pipeline History ----

        async loadHistory() {
            if (this.historyLoading) return;
            this.historyLoading = true;
            await this.refreshPipelines(true);
            this.historyLoading = false;
            this.$nextTick(() => { if (typeof lucide !== 'undefined') lucide.createIcons(); });
        },

        togglePipelineDetails(pipeId) {
            this.expandedPipeline = this.expandedPipeline === pipeId ? null : pipeId;
            this.$nextTick(() => { if (typeof lucide !== 'undefined') lucide.createIcons(); });
        },

        // ---- Statistics ----

        async loadStats() {
            this.statsLoading = true;
            try {
                const r = await fetch('/api/dark-factory/stats');
                if (r.ok) {
                    this.stats = await r.json();
                    this.$nextTick(() => this.renderNicheChart());
                }
            } catch (e) {
                console.error('Error loading stats:', e);
            }
            this.statsLoading = false;
            this.$nextTick(() => { if (typeof lucide !== 'undefined') lucide.createIcons(); });
        },

        renderNicheChart() {
            const distribution = this.stats?.niche_distribution || {};
            const labels = Object.keys(distribution);
            const data = Object.values(distribution);
            if (labels.length === 0) return;

            const colors = labels.map(n => this.getNicheColor(n));

            const ctx = document.getElementById('nicheChart');
            if (!ctx) return;

            if (this.nicheChartInstance) {
                this.nicheChartInstance.destroy();
            }

            this.nicheChartInstance = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: labels.map(l => l.charAt(0).toUpperCase() + l.slice(1).replace('_', ' ')),
                    datasets: [{
                        data: data,
                        backgroundColor: colors,
                        borderColor: 'rgba(15, 10, 30, 0.8)',
                        borderWidth: 2,
                        hoverOffset: 8,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                color: 'rgba(255,255,255,0.5)',
                                font: { size: 11, family: '"Plus Jakarta Sans", sans-serif' },
                                padding: 12,
                                usePointStyle: true,
                                pointStyleWidth: 8,
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(23, 15, 46, 0.9)',
                            titleColor: '#fff',
                            bodyColor: 'rgba(255,255,255,0.7)',
                            borderColor: 'rgba(124, 58, 237, 0.3)',
                            borderWidth: 1,
                            cornerRadius: 8,
                            padding: 10,
                            titleFont: { family: '"Plus Jakarta Sans", sans-serif', weight: 'bold' },
                            bodyFont: { family: '"Plus Jakarta Sans", sans-serif' },
                        }
                    },
                    cutout: '65%',
                }
            });
        },

        getNicheColor(name) {
            return this.nicheColors[name] || '#7c3aed';
        },

        // ---- Toast ----

        showToast(msg, type = 'info') {
            if (typeof showToast === 'function') {
                showToast(msg, type);
            } else {
                const container = document.getElementById('toastContainer');
                if (!container) return;
                const colors = {
                    success: 'background: rgba(16, 185, 129, 0.9);',
                    error: 'background: rgba(239, 68, 68, 0.9);',
                    info: 'background: rgba(124, 58, 237, 0.9);',
                    warning: 'background: rgba(249, 115, 22, 0.9);',
                };
                const toast = document.createElement('div');
                toast.className = 'toast';
                toast.style.cssText = colors[type] || colors.info;
                toast.textContent = msg;
                container.appendChild(toast);
                setTimeout(() => {
                    toast.style.opacity = '0';
                    toast.style.transform = 'translateY(-10px)';
                    toast.style.transition = 'all 0.3s';
                    setTimeout(() => toast.remove(), 300);
                }, 4000);
            }
        },
    };
}
</script>
{% endblock %}
