{% extends "base.html" %}
{% block title %}PostPilot - Viral Social Pro{% endblock %}
{% block nav_scheduler %}active{% endblock %}
{% block page_title %}PostPilot{% endblock %}
{% block page_subtitle %}Smart Publishing Queue & Automacao{% endblock %}

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

    <!-- TABS -->
    <div class="animate-fade-up mb-6 flex flex-wrap gap-2">
        <template x-for="tab in [
            {id:'queue', label:'Fila Inteligente', icon:'list-ordered'},
            {id:'schedule', label:'Agendamento', icon:'clock'},
            {id:'captions', label:'Legendas IA', icon:'message-square-text'},
            {id:'recycle', label:'Reciclagem', icon:'recycle'},
            {id:'abtest', label:'Teste A/B', icon:'split'},
            {id:'automation', label:'Coleta Auto', icon:'settings'},
        ]" :key="tab.id">
            <button @click="activeTab = tab.id"
                    :class="activeTab === tab.id ? 'gradient-brand text-white' : 'glass-card text-white/60 hover:text-white/90'"
                    class="flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-medium transition">
                <i :data-lucide="tab.icon" class="w-4 h-4"></i>
                <span x-text="tab.label"></span>
            </button>
        </template>
    </div>

    <!-- TAB: Fila Inteligente -->
    <div x-show="activeTab === 'queue'" x-transition>
        <!-- Stats Cards -->
        <div class="grid grid-cols-2 md:grid-cols-4 gap-3 mb-6">
            <div class="glass-card rounded-xl p-4 text-center">
                <i data-lucide="list" class="w-5 h-5 text-brand-300 mx-auto mb-1"></i>
                <p class="stat-number text-brand-300" x-text="queueStats.total_queued || 0"></p>
                <p class="text-xs text-white/40 mt-1">Na Fila</p>
            </div>
            <div class="glass-card rounded-xl p-4 text-center">
                <i data-lucide="clock" class="w-5 h-5 text-accent-cyan mx-auto mb-1"></i>
                <p class="stat-number text-accent-cyan" x-text="queueStats.total_scheduled || 0"></p>
                <p class="text-xs text-white/40 mt-1">Agendados</p>
            </div>
            <div class="glass-card rounded-xl p-4 text-center">
                <i data-lucide="check-circle" class="w-5 h-5 text-accent-green mx-auto mb-1"></i>
                <p class="stat-number text-accent-green" x-text="queueStats.total_published || 0"></p>
                <p class="text-xs text-white/40 mt-1">Publicados</p>
            </div>
            <div class="glass-card rounded-xl p-4 text-center">
                <i data-lucide="target" class="w-5 h-5 text-accent-pink mx-auto mb-1"></i>
                <p class="stat-number text-accent-pink" x-text="queueStats.avg_priority || 0"></p>
                <p class="text-xs text-white/40 mt-1">Prioridade Media</p>
            </div>
        </div>

        <!-- Add to Queue Form -->
        <div class="glass-card rounded-2xl p-5 mb-6">
            <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="plus-circle" class="w-5 h-5"></i>
                </div>
                Adicionar a Fila
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
                <input x-model="newItem.title" placeholder="Titulo do conteudo"
                       class="bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                <select x-model="newItem.platform" class="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="tiktok">TikTok</option>
                    <option value="instagram">Instagram</option>
                    <option value="youtube">YouTube</option>
                    <option value="shorts">Shorts</option>
                </select>
                <select x-model="newItem.content_type" class="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="video">Video</option>
                    <option value="reels">Reels</option>
                    <option value="carrossel">Carrossel</option>
                    <option value="story">Story</option>
                    <option value="shorts">Shorts</option>
                </select>
                <div class="flex gap-2">
                    <input type="number" x-model.number="newItem.priority" min="1" max="10" placeholder="Prioridade"
                           class="w-24 bg-dark-700 border border-white/10 rounded-xl px-3 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                    <button @click="addItem()" :disabled="!newItem.title.trim() || addingItem"
                            class="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl gradient-brand text-white text-sm font-semibold hover:opacity-90 transition disabled:opacity-40">
                        <i data-lucide="plus" class="w-4 h-4"></i> Adicionar
                    </button>
                </div>
            </div>
            <div class="mt-3 flex gap-3">
                <input x-model="newItem.description" placeholder="Descricao (opcional)" class="flex-1 bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                <input type="datetime-local" x-model="newItem.scheduled_time" class="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>

        <!-- Auto-Schedule Button -->
        <div class="flex gap-3 mb-4">
            <button @click="autoSchedule()" :disabled="autoScheduleLoading"
                    class="flex items-center gap-2 px-5 py-2.5 rounded-xl bg-accent-cyan/20 text-accent-cyan text-sm font-semibold hover:bg-accent-cyan/30 transition disabled:opacity-40">
                <template x-if="autoScheduleLoading"><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></template>
                <template x-if="!autoScheduleLoading"><i data-lucide="wand-2" class="w-4 h-4"></i></template>
                Auto-Agendar com IA
            </button>
            <button @click="loadQueue()" class="flex items-center gap-2 px-4 py-2.5 rounded-xl glass-card text-white/60 hover:text-white/90 text-sm transition">
                <i data-lucide="refresh-cw" class="w-4 h-4"></i> Atualizar
            </button>
        </div>

        <!-- Queue Items -->
        <div class="space-y-3">
            <template x-if="queueItems.length === 0">
                <div class="glass-card rounded-xl p-8 text-center">
                    <i data-lucide="inbox" class="w-12 h-12 text-white/20 mx-auto mb-3"></i>
                    <p class="text-white/40">Fila vazia. Adicione conteudo para comecar.</p>
                </div>
            </template>
            <template x-for="item in queueItems" :key="item.id">
                <div class="glass-card rounded-xl p-4 flex items-center gap-4">
                    <div class="flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center text-sm font-bold"
                         :class="item.priority >= 8 ? 'bg-red-500/20 text-red-400' : item.priority >= 5 ? 'bg-yellow-500/20 text-yellow-400' : 'bg-green-500/20 text-green-400'"
                         x-text="item.priority"></div>
                    <div class="flex-1 min-w-0">
                        <p class="text-sm font-semibold text-white/90 truncate" x-text="item.title"></p>
                        <div class="flex items-center gap-2 mt-1">
                            <span class="text-xs px-2 py-0.5 rounded-full bg-brand-500/20 text-brand-300" x-text="item.platform"></span>
                            <span class="text-xs px-2 py-0.5 rounded-full bg-white/10 text-white/50" x-text="item.content_type"></span>
                            <span x-show="item.scheduled_time" class="text-xs text-white/40 flex items-center gap-1">
                                <i data-lucide="clock" class="w-3 h-3"></i>
                                <span x-text="item.scheduled_time"></span>
                            </span>
                            <span x-show="item.auto_scheduled" class="text-xs text-accent-cyan/70">IA</span>
                        </div>
                    </div>
                    <div class="flex items-center gap-2">
                        <button @click="publishItem(item.id)" class="p-2 rounded-lg bg-green-500/20 text-green-400 hover:bg-green-500/30 transition" title="Publicar">
                            <i data-lucide="send" class="w-4 h-4"></i>
                        </button>
                        <button @click="removeItem(item.id)" class="p-2 rounded-lg bg-red-500/20 text-red-400 hover:bg-red-500/30 transition" title="Remover">
                            <i data-lucide="trash-2" class="w-4 h-4"></i>
                        </button>
                    </div>
                </div>
            </template>
        </div>
    </div>

    <!-- TAB: Agendamento -->
    <div x-show="activeTab === 'schedule'" x-transition>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- Best Times -->
            <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="clock" class="w-5 h-5 text-brand-300"></i> Melhores Horarios
                </h3>
                <div class="flex gap-2 mb-4">
                    <select x-model="timePlatform" @change="loadBestTimes()" class="bg-dark-700 border border-white/10 rounded-xl px-4 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                        <option value="">Todas</option>
                        <option value="tiktok">TikTok</option>
                        <option value="instagram">Instagram</option>
                        <option value="youtube">YouTube</option>
                    </select>
                </div>
                <template x-if="bestTimes">
                    <div>
                        <p class="text-sm text-white/60 mb-3" x-text="bestTimes.recommendation"></p>
                        <p class="text-xs text-white/40 mb-2" x-text="bestTimes.total_analyzed + ' videos analisados'"></p>
                        <div class="space-y-2">
                            <template x-for="h in (bestTimes.best_hours || []).slice(0, 6)" :key="h.hour">
                                <div class="flex items-center gap-3">
                                    <span class="text-sm font-mono text-white/80 w-14" x-text="h.label"></span>
                                    <div class="flex-1 bg-dark-700 rounded-full h-3">
                                        <div class="h-3 rounded-full gradient-brand" :style="`width: ${Math.min(h.avg_score, 100)}%`"></div>
                                    </div>
                                    <span class="text-xs text-white/50 w-16" x-text="h.avg_score + ' (' + h.count + ')'"></span>
                                </div>
                            </template>
                        </div>
                    </div>
                </template>
            </div>

            <!-- Weekly Plan -->
            <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="calendar" class="w-5 h-5 text-accent-cyan"></i> Plano Semanal
                </h3>
                <div class="flex gap-2 mb-4">
                    <select x-model.number="postsPerDay" @change="loadWeeklyPlan()" class="bg-dark-700 border border-white/10 rounded-xl px-4 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                        <option value="1">1 post/dia</option>
                        <option value="2">2 posts/dia</option>
                        <option value="3">3 posts/dia</option>
                    </select>
                </div>
                <div class="space-y-2">
                    <template x-for="day in weeklyPlan" :key="day.date">
                        <div class="flex items-center gap-3 p-2 rounded-lg bg-dark-700/50">
                            <span class="text-sm font-semibold text-white/80 w-20" x-text="day.day_name"></span>
                            <div class="flex-1 flex gap-2">
                                <template x-for="slot in day.slots" :key="slot.time">
                                    <span class="text-xs px-2 py-1 rounded-lg bg-brand-500/20 text-brand-300" x-text="slot.time"></span>
                                </template>
                            </div>
                            <span class="text-xs text-white/40" x-text="day.day_score ? day.day_score + ' pts' : '-'"></span>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- TAB: Legendas IA -->
    <div x-show="activeTab === 'captions'" x-transition>
        <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="sparkles" class="w-5 h-5"></i>
                </div>
                Gerar Legenda com IA
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-3 mb-4">
                <input x-model="captionTitle" placeholder="Titulo/tema do conteudo"
                       class="bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                <select x-model="captionPlatform" class="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="tiktok">TikTok</option>
                    <option value="instagram">Instagram</option>
                    <option value="youtube">YouTube</option>
                </select>
                <select x-model="captionTone" class="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="engajante">Engajante</option>
                    <option value="informativo">Informativo</option>
                    <option value="humoristico">Humoristico</option>
                    <option value="inspirador">Inspirador</option>
                    <option value="provocativo">Provocativo</option>
                </select>
                <input x-model="captionNiche" placeholder="Nicho (opcional)"
                       class="bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
            </div>
            <button @click="generateCaption()" :disabled="captionLoading || !captionTitle.trim()"
                    class="flex items-center gap-2 px-6 py-2.5 rounded-xl gradient-brand text-white text-sm font-semibold hover:opacity-90 transition disabled:opacity-40">
                <template x-if="captionLoading"><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></template>
                <template x-if="!captionLoading"><i data-lucide="sparkles" class="w-4 h-4"></i></template>
                Gerar Legenda
            </button>

            <template x-if="captionResult">
                <div class="mt-6 space-y-4">
                    <div class="glass-card rounded-xl p-4">
                        <div class="flex items-center justify-between mb-2">
                            <h4 class="text-sm font-semibold text-white/80">Legenda</h4>
                            <button @click="copyText(captionResult.caption)" class="text-xs text-brand-300 hover:text-brand-200">Copiar</button>
                        </div>
                        <p class="text-sm text-white/70 whitespace-pre-line" x-text="captionResult.caption"></p>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
                        <div class="glass-card rounded-xl p-4">
                            <h4 class="text-xs font-semibold text-white/60 mb-2">Hook</h4>
                            <p class="text-sm text-white/80" x-text="captionResult.hook_line"></p>
                        </div>
                        <div class="glass-card rounded-xl p-4">
                            <h4 class="text-xs font-semibold text-white/60 mb-2">CTA</h4>
                            <p class="text-sm text-white/80" x-text="captionResult.cta"></p>
                        </div>
                        <div class="glass-card rounded-xl p-4">
                            <h4 class="text-xs font-semibold text-white/60 mb-2">Hashtags</h4>
                            <div class="flex flex-wrap gap-1">
                                <template x-for="tag in (captionResult.hashtags || [])" :key="tag">
                                    <span class="text-xs px-2 py-0.5 rounded-full bg-brand-500/20 text-brand-300" x-text="tag"></span>
                                </template>
                            </div>
                        </div>
                    </div>
                </div>
            </template>
        </div>
    </div>

    <!-- TAB: Reciclagem -->
    <div x-show="activeTab === 'recycle'" x-transition>
        <div class="glass-card rounded-2xl p-5 mb-4">
            <h3 class="text-lg font-bold text-white/90 mb-3 flex items-center gap-2">
                <i data-lucide="recycle" class="w-5 h-5 text-accent-green"></i> Reciclagem de Conteudo
            </h3>
            <p class="text-sm text-white/50 mb-4">Conteudos antigos com alto desempenho que podem ser reciclados com novos angulos.</p>
            <button @click="loadRecycling()" :disabled="recycleLoading"
                    class="flex items-center gap-2 px-5 py-2.5 rounded-xl gradient-brand text-white text-sm font-semibold hover:opacity-90 transition disabled:opacity-40">
                <template x-if="recycleLoading"><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></template>
                <template x-if="!recycleLoading"><i data-lucide="search" class="w-4 h-4"></i></template>
                Buscar Sugestoes
            </button>
        </div>

        <div class="space-y-3">
            <template x-for="s in recycleSuggestions" :key="s.video_id">
                <div class="glass-card rounded-xl p-4">
                    <div class="flex items-start gap-4">
                        <div class="flex-1">
                            <p class="text-sm font-semibold text-white/90" x-text="s.title || 'Video #' + s.video_id"></p>
                            <div class="flex items-center gap-3 mt-1">
                                <span class="text-xs text-white/50" x-text="s.platform"></span>
                                <span class="text-xs text-white/50" x-text="formatNumber(s.views) + ' views'"></span>
                                <span class="text-xs text-accent-green" x-text="'Score: ' + s.original_score"></span>
                            </div>
                        </div>
                        <span class="text-xs px-2 py-1 rounded-lg bg-accent-green/20 text-accent-green" x-text="s.estimated_boost + 'x boost'"></span>
                    </div>
                    <div class="mt-3 p-3 rounded-lg bg-dark-700/50">
                        <p class="text-xs text-white/40 mb-1">Angulo sugerido:</p>
                        <p class="text-sm text-white/70" x-text="s.recycle_angle"></p>
                    </div>
                    <button @click="addRecycleToQueue(s)" class="mt-2 text-xs text-brand-300 hover:text-brand-200 flex items-center gap-1">
                        <i data-lucide="plus" class="w-3 h-3"></i> Adicionar a Fila
                    </button>
                </div>
            </template>
        </div>
    </div>

    <!-- TAB: Teste A/B -->
    <div x-show="activeTab === 'abtest'" x-transition>
        <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 bg-accent-pink/20 flex items-center justify-center">
                    <i data-lucide="split" class="w-5 h-5 text-accent-pink"></i>
                </div>
                Teste A/B de Horarios
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-3 mb-4">
                <input x-model="abTitle" placeholder="Titulo do conteudo"
                       class="bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                <select x-model="abPlatform" class="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="tiktok">TikTok</option>
                    <option value="instagram">Instagram</option>
                    <option value="youtube">YouTube</option>
                </select>
                <select x-model.number="abVariations" class="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="2">2 variacoes</option>
                    <option value="3">3 variacoes</option>
                    <option value="4">4 variacoes</option>
                </select>
            </div>
            <button @click="runAbTest()" :disabled="abLoading || !abTitle.trim()"
                    class="flex items-center gap-2 px-6 py-2.5 rounded-xl gradient-brand text-white text-sm font-semibold hover:opacity-90 transition disabled:opacity-40">
                <template x-if="abLoading"><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></template>
                <template x-if="!abLoading"><i data-lucide="play" class="w-4 h-4"></i></template>
                Criar Teste A/B
            </button>

            <template x-if="abResult">
                <div class="mt-6">
                    <h4 class="text-sm font-semibold text-white/80 mb-3" x-text="'Teste: ' + abResult.title"></h4>
                    <p class="text-xs text-white/50 mb-4" x-text="abResult.recommendation"></p>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <template x-for="v in abResult.variations" :key="v.variant">
                            <div class="glass-card rounded-xl p-4">
                                <div class="flex items-center gap-2 mb-2">
                                    <span class="w-8 h-8 rounded-lg gradient-brand flex items-center justify-center text-sm font-bold" x-text="v.variant"></span>
                                    <div>
                                        <p class="text-sm font-semibold text-white/80" x-text="v.scheduled_time"></p>
                                        <p class="text-xs text-white/50" x-text="'Score esperado: ' + v.expected_score"></p>
                                    </div>
                                </div>
                                <p class="text-xs text-white/40" x-text="v.hypothesis"></p>
                            </div>
                        </template>
                    </div>
                </div>
            </template>
        </div>
    </div>

    <!-- TAB: Coleta Automatica -->
    <div x-show="activeTab === 'automation'" x-transition>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div class="glass-card rounded-2xl p-5">
                <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="settings" class="w-5 h-5 text-brand-300"></i> Coleta Automatica
                    </h3>
                    <button @click="config.enabled = !config.enabled; saveConfig()"
                            class="relative w-12 h-6 rounded-full transition"
                            :class="config.enabled ? 'bg-green-500' : 'bg-white/20'">
                        <div class="absolute top-0.5 left-0.5 w-5 h-5 bg-white rounded-full transition-transform"
                             :class="config.enabled ? 'translate-x-6' : ''"></div>
                    </button>
                </div>
                <div class="space-y-4">
                    <div>
                        <label class="block text-xs text-white/50 mb-1">Intervalo</label>
                        <select x-model="config.interval_hours" class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                            <option value="1">1 hora</option><option value="3">3 horas</option>
                            <option value="6">6 horas</option><option value="12">12 horas</option><option value="24">24 horas</option>
                        </select>
                    </div>
                    <div class="space-y-3">
                        <label class="flex items-center gap-2"><input type="checkbox" x-model="config.yt_enabled" class="rounded"><span class="text-sm text-white/80">YouTube</span></label>
                        <div x-show="config.yt_enabled" class="ml-6"><input x-model="config.yt_query" placeholder="Query" class="w-full bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none"></div>
                        <label class="flex items-center gap-2"><input type="checkbox" x-model="config.tt_enabled" class="rounded"><span class="text-sm text-white/80">TikTok</span></label>
                        <div x-show="config.tt_enabled" class="ml-6 space-y-2">
                            <input x-model="config.tt_query" placeholder="Query" class="w-full bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                            <input x-model="config.tt_hashtag" placeholder="Hashtag" class="w-full bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                        </div>
                        <label class="flex items-center gap-2"><input type="checkbox" x-model="config.ig_enabled" class="rounded"><span class="text-sm text-white/80">Instagram</span></label>
                        <div x-show="config.ig_enabled" class="ml-6 space-y-2">
                            <input x-model="config.ig_hashtag" placeholder="Hashtag" class="w-full bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                            <input x-model="config.ig_username" placeholder="Username" class="w-full bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none">
                        </div>
                    </div>
                    <button @click="saveConfig()" class="w-full py-2.5 rounded-xl gradient-brand text-white text-sm font-semibold hover:opacity-90 transition">Salvar</button>
                </div>
            </div>

            <div class="space-y-6">
                <div class="glass-card rounded-2xl p-5">
                    <h3 class="text-lg font-bold text-white/90 mb-3 flex items-center gap-2">
                        <i data-lucide="download" class="w-5 h-5 text-accent-cyan"></i> Exportar
                    </h3>
                    <div class="space-y-2">
                        <a href="/api/export/videos/excel" class="flex items-center gap-3 p-3 rounded-lg bg-dark-700/50 hover:bg-dark-700 transition">
                            <i data-lucide="file-spreadsheet" class="w-5 h-5 text-green-400"></i>
                            <div><p class="text-sm font-medium text-white/80">Relatorio Excel</p><p class="text-xs text-white/40">Videos + Criadores</p></div>
                        </a>
                        <a href="/api/export/videos/csv" class="flex items-center gap-3 p-3 rounded-lg bg-dark-700/50 hover:bg-dark-700 transition">
                            <i data-lucide="file-text" class="w-5 h-5 text-blue-400"></i>
                            <div><p class="text-sm font-medium text-white/80">Videos CSV</p></div>
                        </a>
                        <a href="/api/export/creators/csv" class="flex items-center gap-3 p-3 rounded-lg bg-dark-700/50 hover:bg-dark-700 transition">
                            <i data-lucide="users" class="w-5 h-5 text-purple-400"></i>
                            <div><p class="text-sm font-medium text-white/80">Criadores CSV</p></div>
                        </a>
                    </div>
                </div>
                <div class="glass-card rounded-2xl p-5">
                    <h3 class="text-lg font-bold text-white/90 mb-3 flex items-center gap-2">
                        <i data-lucide="zap" class="w-5 h-5 text-yellow-400"></i> Acoes Rapidas
                    </h3>
                    <div class="space-y-2">
                        <button @click="runNow('youtube')" class="w-full py-2.5 rounded-xl bg-red-500/20 text-red-400 hover:bg-red-500/30 text-sm font-medium transition">Coletar YouTube Agora</button>
                        <button @click="checkAlerts()" class="w-full py-2.5 rounded-xl bg-orange-500/20 text-orange-400 hover:bg-orange-500/30 text-sm font-medium transition">Verificar Alertas</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Job Log -->
        <div class="glass-card rounded-2xl p-5 mt-6">
            <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="scroll-text" class="w-5 h-5 text-white/50"></i> Log de Execucoes
                </h3>
                <button @click="loadLog()" class="text-xs text-brand-300 hover:text-brand-200">Atualizar</button>
            </div>
            <template x-if="log.length === 0"><p class="text-center text-white/30 py-4">Nenhuma execucao registrada.</p></template>
            <div class="space-y-2 max-h-60 overflow-y-auto">
                <template x-for="entry in log" :key="entry.timestamp">
                    <div class="flex items-center gap-3 p-2 rounded-lg bg-dark-700/50 text-sm">
                        <span class="w-2 h-2 rounded-full flex-shrink-0" :class="entry.status === 'success' ? 'bg-green-500' : entry.status === 'error' ? 'bg-red-500' : 'bg-yellow-500'"></span>
                        <span class="font-medium uppercase text-xs w-14 text-white/60" x-text="entry.platform"></span>
                        <span class="flex-1 text-white/50 truncate" x-text="entry.message"></span>
                        <span class="text-xs text-white/30" x-text="new Date(entry.timestamp).toLocaleString('pt-BR')"></span>
                    </div>
                </template>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
function postPilot() {
    return {
        activeTab: 'queue',
        // Queue
        queueItems: [], queueStats: {},
        newItem: { title: '', platform: 'tiktok', content_type: 'video', priority: 5, description: '', scheduled_time: '' },
        addingItem: false, autoScheduleLoading: false,
        // Schedule
        bestTimes: null, weeklyPlan: [], timePlatform: '', postsPerDay: 2,
        // Captions
        captionTitle: '', captionPlatform: 'tiktok', captionTone: 'engajante', captionNiche: '',
        captionLoading: false, captionResult: null,
        // Recycle
        recycleSuggestions: [], recycleLoading: false,
        // AB Test
        abTitle: '', abPlatform: 'tiktok', abVariations: 2,
        abLoading: false, abResult: null,
        // Automation
        config: { enabled: false, interval_hours: 6, yt_enabled: true, yt_query: '', tt_enabled: false, tt_query: '', tt_hashtag: '', ig_enabled: false, ig_hashtag: '', ig_username: '' },
        log: [],

        async init() {
            await Promise.all([this.loadQueue(), this.loadQueueStats(), this.loadBestTimes(), this.loadWeeklyPlan(), this.loadConfig(), this.loadLog()]);
        },

        async loadQueue() {
            try { const d = await apiCall('/api/calendar/queue'); this.queueItems = d.items || []; } catch(e) {}
        },
        async loadQueueStats() {
            try { this.queueStats = await apiCall('/api/calendar/queue/stats'); } catch(e) {}
        },
        async addItem() {
            if (!this.newItem.title.trim()) return;
            this.addingItem = true;
            try {
                await apiCall('/api/calendar/queue', 'POST', this.newItem);
                this.newItem = { title: '', platform: 'tiktok', content_type: 'video', priority: 5, description: '', scheduled_time: '' };
                await this.loadQueue(); await this.loadQueueStats();
                showToast('Adicionado a fila!', 'success');
            } catch(e) { showToast('Erro ao adicionar', 'error'); }
            this.addingItem = false;
        },
        async removeItem(id) {
            try { await apiCall(`/api/calendar/queue/${id}`, 'DELETE'); await this.loadQueue(); await this.loadQueueStats(); showToast('Removido!', 'success'); } catch(e) {}
        },
        async publishItem(id) {
            try { await apiCall(`/api/calendar/queue/${id}/publish`, 'POST'); await this.loadQueue(); await this.loadQueueStats(); showToast('Publicado!', 'success'); } catch(e) {}
        },
        async autoSchedule() {
            this.autoScheduleLoading = true;
            try {
                const d = await apiCall('/api/calendar/auto-schedule', 'POST');
                showToast(`${d.scheduled} itens agendados com IA!`, 'success');
                await this.loadQueue(); await this.loadQueueStats();
            } catch(e) { showToast('Erro no auto-agendamento', 'error'); }
            this.autoScheduleLoading = false;
        },
        async loadBestTimes() {
            try { this.bestTimes = await apiCall(`/api/calendar/best-times?platform=${this.timePlatform}`); } catch(e) {}
        },
        async loadWeeklyPlan() {
            try { const d = await apiCall(`/api/calendar/weekly-plan?posts_per_day=${this.postsPerDay}`); this.weeklyPlan = d.plan || []; } catch(e) {}
        },
        async generateCaption() {
            this.captionLoading = true;
            try {
                this.captionResult = await apiCall('/api/calendar/smart-caption', 'POST', {
                    title: this.captionTitle, platform: this.captionPlatform, tone: this.captionTone, niche: this.captionNiche
                });
            } catch(e) { showToast('Erro ao gerar legenda', 'error'); }
            this.captionLoading = false;
        },
        async loadRecycling() {
            this.recycleLoading = true;
            try { const d = await apiCall('/api/calendar/recycle'); this.recycleSuggestions = d.suggestions || []; } catch(e) { showToast('Erro', 'error'); }
            this.recycleLoading = false;
        },
        addRecycleToQueue(s) {
            this.newItem.title = `[Reciclado] ${s.title || 'Video #' + s.video_id} - ${s.recycle_angle}`;
            this.newItem.platform = s.platform;
            this.activeTab = 'queue';
        },
        async runAbTest() {
            this.abLoading = true;
            try {
                this.abResult = await apiCall('/api/calendar/ab-test', 'POST', {
                    title: this.abTitle, platform: this.abPlatform, variations: this.abVariations
                });
            } catch(e) { showToast('Erro no teste A/B', 'error'); }
            this.abLoading = false;
        },
        async loadConfig() {
            try {
                const data = await apiCall('/api/scheduler/config');
                this.config.enabled = data.enabled;
                this.config.interval_hours = data.interval_hours;
                if (data.youtube) { this.config.yt_enabled = data.youtube.enabled; this.config.yt_query = data.youtube.query || ''; }
                if (data.tiktok) { this.config.tt_enabled = data.tiktok.enabled; this.config.tt_query = data.tiktok.query || ''; this.config.tt_hashtag = data.tiktok.hashtag || ''; }
                if (data.instagram) { this.config.ig_enabled = data.instagram.enabled; this.config.ig_hashtag = data.instagram.hashtag || ''; this.config.ig_username = data.instagram.username || ''; }
            } catch(e) {}
        },
        async saveConfig() {
            const p = new URLSearchParams({
                enabled: this.config.enabled, interval_hours: this.config.interval_hours,
                yt_enabled: this.config.yt_enabled, yt_query: this.config.yt_query, yt_region: 'BR',
                tt_enabled: this.config.tt_enabled, tt_query: this.config.tt_query, tt_hashtag: this.config.tt_hashtag,
                ig_enabled: this.config.ig_enabled, ig_hashtag: this.config.ig_hashtag, ig_username: this.config.ig_username,
            });
            await apiCall(`/api/scheduler/config?${p}`, 'POST');
            showToast('Configuracao salva!', 'success'); this.loadLog();
        },
        async loadLog() { try { const d = await apiCall('/api/scheduler/log'); this.log = d.log || []; } catch(e){} },
        async runNow(platform) { showToast('Executando...', 'info'); await apiCall(`/api/scheduler/run-now?platform=${platform}`, 'POST'); showToast('Coleta finalizada!', 'success'); this.loadLog(); },
        async checkAlerts() { const d = await apiCall('/api/alerts/check', 'POST'); showToast(`${d.total_unread} alertas nao lidos`, 'info'); },
        copyText(text) { navigator.clipboard.writeText(text); showToast('Copiado!', 'success'); },
        formatNumber(n) { if (!n) return '0'; if (n >= 1e6) return (n/1e6).toFixed(1)+'M'; if (n >= 1e3) return (n/1e3).toFixed(1)+'K'; return n.toString(); },
    };
}
</script>
{% endblock %}
