{% extends "base.html" %}
{% block title %}AutoFlow - Viral Social Pro{% endblock %}
{% block nav_automate %}active{% endblock %}
{% block page_title %}AutoFlow{% endblock %}
{% block page_subtitle %}Motor de Automacao de Workflows{% endblock %}

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

    <!-- TABS -->
    <div class="flex gap-2 mb-6 overflow-x-auto pb-1">
        <button class="tab-btn" :class="activeTab === 'workflows' && 'active'" @click="activeTab = 'workflows'; loadWorkflows()">
            <i data-lucide="git-branch" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Workflows
        </button>
        <button class="tab-btn" :class="activeTab === 'create' && 'active'" @click="activeTab = 'create'; loadStepTypes()">
            <i data-lucide="plus-circle" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Criar Workflow
        </button>
        <button class="tab-btn" :class="activeTab === 'templates' && 'active'" @click="activeTab = 'templates'; loadTemplates()">
            <i data-lucide="layout-template" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Templates
        </button>
        <button class="tab-btn" :class="activeTab === 'runs' && 'active'" @click="activeTab = 'runs'; loadRuns()">
            <i data-lucide="play-circle" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Execucoes
        </button>
        <button class="tab-btn" :class="activeTab === 'factory' && 'active'" @click="activeTab = 'factory'">
            <i data-lucide="factory" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Content Factory
        </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: WORKFLOWS                                                 -->
    <!-- ═══════════════════════════════════════════════════════════════ -->
    <div x-show="activeTab === 'workflows'" x-transition>

        <!-- Header -->
        <div class="flex items-center justify-between mb-4">
            <div>
                <h3 class="text-base font-bold text-white/80">Meus Workflows</h3>
                <p class="text-xs text-white/40 mt-0.5">Gerencie e execute seus workflows de automacao</p>
            </div>
            <div class="flex items-center gap-2">
                <button @click="loadWorkflows()" class="px-3 py-2 rounded-xl glass-light text-xs text-white/60 hover:text-white transition flex items-center gap-1">
                    <i data-lucide="refresh-cw" class="w-3.5 h-3.5"></i> Atualizar
                </button>
                <button @click="activeTab = 'create'" class="px-4 py-2 rounded-xl gradient-brand text-white text-xs font-semibold hover:opacity-90 transition flex items-center gap-1.5">
                    <i data-lucide="plus" class="w-3.5 h-3.5"></i> Novo Workflow
                </button>
            </div>
        </div>

        <!-- Loading State -->
        <template x-if="workflowsLoading">
            <div class="grid-cards">
                <template x-for="i in 3" :key="i">
                    <div class="glass-card rounded-2xl p-5">
                        <div class="skeleton h-5 w-3/4 mb-3"></div>
                        <div class="skeleton h-3 w-full mb-2"></div>
                        <div class="skeleton h-3 w-1/2 mb-4"></div>
                        <div class="flex gap-2">
                            <div class="skeleton h-8 w-20"></div>
                            <div class="skeleton h-8 w-16"></div>
                        </div>
                    </div>
                </template>
            </div>
        </template>

        <!-- Empty State -->
        <div x-show="!workflowsLoading && workflows.length === 0" class="glass-card rounded-2xl p-10 text-center">
            <div class="w-16 h-16 rounded-2xl gradient-brand flex items-center justify-center mx-auto mb-4 opacity-50">
                <i data-lucide="git-branch" class="w-8 h-8"></i>
            </div>
            <p class="text-white/50 text-sm mb-2">Nenhum workflow criado ainda</p>
            <p class="text-white/30 text-xs mb-4">Crie um novo workflow ou use um template para comecar.</p>
            <div class="flex items-center justify-center gap-3">
                <button @click="activeTab = 'create'" class="px-4 py-2.5 rounded-xl gradient-brand text-white text-sm font-semibold hover:opacity-90 transition">
                    <i data-lucide="plus" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Criar Workflow
                </button>
                <button @click="activeTab = 'templates'; loadTemplates()" class="px-4 py-2.5 rounded-xl glass-card text-white/70 text-sm font-medium hover:text-white transition">
                    <i data-lucide="layout-template" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Ver Templates
                </button>
            </div>
        </div>

        <!-- Workflows List -->
        <div x-show="!workflowsLoading && workflows.length > 0" class="space-y-3">
            <template x-for="wf in workflows" :key="wf.workflow_id">
                <div class="glass-card rounded-2xl p-4">
                    <div class="flex items-start justify-between gap-4">
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center gap-2 mb-1 flex-wrap">
                                <h4 class="font-bold text-white/90 truncate" x-text="wf.name"></h4>
                                <span class="px-2 py-0.5 rounded-lg text-[10px] font-semibold"
                                      :class="wf.status === 'active' ? 'bg-green-500/20 text-green-400' : 'bg-white/10 text-white/40'"
                                      x-text="wf.status === 'active' ? 'Ativo' : 'Inativo'"></span>
                                <span class="px-2 py-0.5 rounded-lg text-[10px] font-medium bg-brand-500/20 text-brand-300" x-text="triggerLabel(wf.trigger_type)"></span>
                            </div>
                            <p class="text-xs text-white/40 mb-2" x-text="wf.description || 'Sem descricao'"></p>
                            <div class="flex items-center gap-4 text-xs text-white/30">
                                <span class="flex items-center gap-1">
                                    <i data-lucide="layers" class="w-3 h-3"></i>
                                    <span x-text="(wf.steps_count || 0) + ' passos'"></span>
                                </span>
                                <span class="flex items-center gap-1">
                                    <i data-lucide="play" class="w-3 h-3"></i>
                                    <span x-text="(wf.run_count || 0) + ' execucoes'"></span>
                                </span>
                                <span x-show="wf.last_run" class="flex items-center gap-1">
                                    <i data-lucide="clock" class="w-3 h-3"></i>
                                    <span x-text="timeAgo(wf.last_run)"></span>
                                </span>
                            </div>
                        </div>
                        <div class="flex items-center gap-2 flex-shrink-0">
                            <button @click="runWorkflow(wf.workflow_id)" :disabled="runningId === wf.workflow_id"
                                    class="px-3 py-2 rounded-xl gradient-brand text-white text-xs font-semibold hover:opacity-90 transition disabled:opacity-50">
                                <span x-show="runningId !== wf.workflow_id" class="flex items-center gap-1">
                                    <i data-lucide="play" class="w-3.5 h-3.5"></i> Executar
                                </span>
                                <span x-show="runningId === wf.workflow_id" class="flex items-center gap-1">
                                    <i data-lucide="loader" class="w-3.5 h-3.5 animate-spin"></i> Rodando...
                                </span>
                            </button>
                            <button @click="viewCostEstimate(wf.workflow_id)" class="p-2 rounded-xl glass-light text-white/50 hover:text-white transition" title="Estimativa de custo">
                                <i data-lucide="calculator" class="w-4 h-4"></i>
                            </button>
                            <button @click="deleteWorkflow(wf.workflow_id)" class="p-2 rounded-xl hover:bg-red-500/20 text-red-400/60 hover:text-red-400 transition" title="Deletar">
                                <i data-lucide="trash-2" class="w-4 h-4"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Run Result (inline after execution) -->
                    <div x-show="lastRunResult && lastRunResult.workflow_id === wf.workflow_id" class="mt-3 p-3 rounded-xl bg-dark-700/50 border border-white/5" x-transition>
                        <div class="flex items-center gap-2 mb-2">
                            <span class="w-2 h-2 rounded-full"
                                  :class="lastRunResult?.status === 'completed' ? 'bg-green-400' : lastRunResult?.status === 'running' ? 'bg-brand-400 animate-pulse' : lastRunResult?.status === 'pending' ? 'bg-yellow-400' : 'bg-red-400'"></span>
                            <span class="text-xs font-semibold"
                                  :class="lastRunResult?.status === 'completed' ? 'text-green-400' : lastRunResult?.status === 'running' ? 'text-brand-400' : lastRunResult?.status === 'pending' ? 'text-yellow-400' : 'text-red-400'"
                                  x-text="statusLabel(lastRunResult?.status)"></span>
                            <span class="text-xs text-white/30"
                                  x-text="(lastRunResult?.steps_completed || 0) + '/' + (lastRunResult?.steps_total || 0) + ' passos em ' + (lastRunResult?.duration || 0) + 's'"></span>
                        </div>
                        <template x-for="sr in (lastRunResult?.results || [])" :key="sr.step_id">
                            <div class="flex items-center gap-2 text-xs py-1 border-t border-white/5">
                                <i data-lucide="check-circle" class="w-3.5 h-3.5 flex-shrink-0" :class="sr.success ? 'text-green-400' : 'text-red-400'"></i>
                                <span class="text-white/60" x-text="sr.step_name"></span>
                                <span class="text-white/30 ml-auto" x-text="(sr.duration || 0) + 's'"></span>
                            </div>
                        </template>
                    </div>
                </div>
            </template>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════ -->
    <!-- TAB: CREATE WORKFLOW                                           -->
    <!-- ═══════════════════════════════════════════════════════════════ -->
    <div x-show="activeTab === 'create'" x-transition>

        <div class="max-w-3xl mx-auto">
            <div class="glass-card rounded-2xl p-6">
                <h3 class="text-lg font-bold text-white/90 mb-5 flex items-center gap-3">
                    <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>
                    Criar Novo Workflow
                </h3>

                <div class="space-y-5">
                    <!-- Name & Description -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="text-xs text-white/50 mb-1.5 block font-medium">Nome do Workflow *</label>
                            <input x-model="newName" type="text" placeholder="Ex: Scan diario de tendencias"
                                   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 transition">
                        </div>
                        <div>
                            <label class="text-xs text-white/50 mb-1.5 block font-medium">Tipo de Trigger</label>
                            <select x-model="newTrigger"
                                    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 transition">
                                <option value="manual">Manual</option>
                                <option value="schedule">Agendado (Schedule)</option>
                                <option value="webhook">Webhook</option>
                                <option value="event">Evento</option>
                            </select>
                        </div>
                    </div>

                    <div>
                        <label class="text-xs text-white/50 mb-1.5 block font-medium">Descricao</label>
                        <textarea x-model="newDescription" rows="2" placeholder="Descreva o que este workflow faz..."
                                  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 transition"></textarea>
                    </div>

                    <!-- Trigger Config (conditional) -->
                    <div x-show="newTrigger === 'schedule'" x-transition class="p-4 rounded-xl glass-light border border-brand-500/10">
                        <label class="text-xs text-white/50 mb-1.5 block font-medium">
                            <i data-lucide="clock" class="w-3.5 h-3.5 inline-block mr-1 -mt-0.5"></i> Configuracao de Agendamento
                        </label>
                        <input x-model="triggerConfig.cron" type="text" placeholder="Cron expression: 0 9 * * * (diario as 9h)"
                               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 transition">
                        <p class="text-[10px] text-white/25 mt-1.5">Formato cron: minuto hora dia mes dia_semana</p>
                    </div>

                    <div x-show="newTrigger === 'webhook'" x-transition class="p-4 rounded-xl glass-light border border-brand-500/10">
                        <label class="text-xs text-white/50 mb-1.5 block font-medium">
                            <i data-lucide="webhook" class="w-3.5 h-3.5 inline-block mr-1 -mt-0.5"></i> Configuracao de Webhook
                        </label>
                        <input x-model="triggerConfig.secret" type="text" placeholder="Secret key (opcional)"
                               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 transition">
                        <p class="text-[10px] text-white/25 mt-1.5">O URL do webhook sera gerado automaticamente</p>
                    </div>

                    <div x-show="newTrigger === 'event'" x-transition class="p-4 rounded-xl glass-light border border-brand-500/10">
                        <label class="text-xs text-white/50 mb-1.5 block font-medium">
                            <i data-lucide="zap" class="w-3.5 h-3.5 inline-block mr-1 -mt-0.5"></i> Tipo de Evento
                        </label>
                        <input x-model="triggerConfig.event_type" type="text" placeholder="Ex: new_trend, video_uploaded"
                               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 transition">
                    </div>

                    <!-- Steps Builder -->
                    <div>
                        <div class="flex items-center justify-between mb-3">
                            <label class="text-xs text-white/50 font-medium">Passos do Workflow</label>
                            <span class="text-[10px] text-white/25" x-text="newSteps.length + ' passo(s)'"></span>
                        </div>

                        <!-- Steps list -->
                        <div class="space-y-2 mb-3">
                            <template x-for="(step, idx) in newSteps" :key="idx">
                                <div class="flex items-center gap-2 p-2 rounded-xl glass-light border border-white/5">
                                    <span class="flex-shrink-0 w-7 h-7 rounded-lg bg-brand-500/20 text-brand-300 flex items-center justify-center text-xs font-bold" x-text="idx + 1"></span>

                                    <select x-model="step.type"
                                            class="flex-1 bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none transition">
                                        <option value="">Selecione o tipo...</option>
                                        <template x-for="st in stepTypes" :key="st.type">
                                            <option :value="st.type" x-text="st.name"></option>
                                        </template>
                                    </select>

                                    <input x-model="step.name" type="text" placeholder="Nome do passo"
                                           class="w-40 bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none transition">

                                    <button @click="moveStep(idx, -1)" :disabled="idx === 0"
                                            class="p-1.5 rounded-lg hover:bg-white/10 text-white/30 hover:text-white transition disabled:opacity-20 disabled:cursor-not-allowed">
                                        <i data-lucide="chevron-up" class="w-4 h-4"></i>
                                    </button>
                                    <button @click="moveStep(idx, 1)" :disabled="idx === newSteps.length - 1"
                                            class="p-1.5 rounded-lg hover:bg-white/10 text-white/30 hover:text-white transition disabled:opacity-20 disabled:cursor-not-allowed">
                                        <i data-lucide="chevron-down" class="w-4 h-4"></i>
                                    </button>

                                    <button @click="newSteps.splice(idx, 1)" class="p-1.5 rounded-lg hover:bg-red-500/20 text-red-400/60 hover:text-red-400 transition">
                                        <i data-lucide="trash-2" class="w-4 h-4"></i>
                                    </button>
                                </div>
                            </template>
                        </div>

                        <!-- Empty steps state -->
                        <div x-show="newSteps.length === 0" class="p-4 rounded-xl border border-dashed border-white/10 text-center mb-3">
                            <p class="text-xs text-white/30">Nenhum passo adicionado. Clique abaixo para adicionar.</p>
                        </div>

                        <button @click="newSteps.push({type: '', name: '', config: {}}); $nextTick(() => { if (window.lucide) lucide.createIcons(); })"
                                class="flex items-center gap-2 px-4 py-2 rounded-xl glass-light text-brand-300 text-sm hover:text-white transition border border-dashed border-brand-500/20 hover:border-brand-500/40">
                            <i data-lucide="plus" class="w-4 h-4"></i> Adicionar Passo
                        </button>
                    </div>

                    <!-- Step Types Reference -->
                    <div x-show="stepTypes.length > 0" class="p-4 rounded-xl glass-light border border-white/5">
                        <p class="text-xs text-white/40 font-medium mb-2 flex items-center gap-1">
                            <i data-lucide="info" class="w-3.5 h-3.5"></i> Tipos de passos disponiveis
                        </p>
                        <div class="flex flex-wrap gap-1.5">
                            <template x-for="st in stepTypes" :key="st.type">
                                <span class="px-2 py-1 rounded-lg text-[10px] font-medium glass-light text-white/50 border border-white/5" x-text="st.name"></span>
                            </template>
                        </div>
                    </div>

                    <!-- Actions -->
                    <div class="flex items-center gap-3 pt-2">
                        <button @click="createWorkflow()" :disabled="createLoading || !newName.trim()"
                                class="px-6 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-50 flex items-center gap-2">
                            <i data-lucide="check" class="w-4 h-4" x-show="!createLoading"></i>
                            <i data-lucide="loader" class="w-4 h-4 animate-spin" x-show="createLoading"></i>
                            <span x-text="createLoading ? 'Criando...' : 'Criar Workflow'"></span>
                        </button>
                        <button @click="resetCreateForm()" class="px-4 py-2.5 rounded-xl glass-card text-white/50 text-sm font-medium hover:text-white transition">
                            Limpar
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════ -->
    <!-- TAB: TEMPLATES                                                 -->
    <!-- ═══════════════════════════════════════════════════════════════ -->
    <div x-show="activeTab === 'templates'" x-transition>

        <div class="mb-4">
            <h3 class="text-base font-bold text-white/80 mb-1">Templates Prontos</h3>
            <p class="text-xs text-white/40">Workflows pre-configurados para os casos de uso mais comuns. Um clique para criar.</p>
        </div>

        <!-- Loading State -->
        <template x-if="templatesLoading">
            <div class="grid-cards">
                <template x-for="i in 4" :key="i">
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-start gap-3 mb-3">
                            <div class="skeleton w-11 h-11 rounded-xl"></div>
                            <div class="flex-1">
                                <div class="skeleton h-4 w-3/4 mb-2"></div>
                                <div class="skeleton h-3 w-1/2"></div>
                            </div>
                        </div>
                        <div class="skeleton h-10 w-full mb-3"></div>
                        <div class="skeleton h-9 w-full rounded-xl"></div>
                    </div>
                </template>
            </div>
        </template>

        <!-- Templates Grid -->
        <div x-show="!templatesLoading" class="grid-cards">
            <template x-for="tmpl in templates" :key="tmpl.template_id">
                <div class="glass-card rounded-2xl p-5 flex flex-col">
                    <div class="flex items-start gap-3 mb-3">
                        <div class="w-11 h-11 rounded-xl flex items-center justify-center flex-shrink-0"
                             :class="templateGradient(tmpl.color)">
                            <i :data-lucide="tmpl.icon || 'workflow'" class="w-5 h-5 text-white"></i>
                        </div>
                        <div class="min-w-0">
                            <h4 class="font-bold text-white/90 text-sm" x-text="tmpl.name"></h4>
                            <span class="px-2 py-0.5 rounded-lg text-[10px] font-medium bg-white/5 text-white/40" x-text="tmpl.category || 'Geral'"></span>
                        </div>
                    </div>

                    <p class="text-xs text-white/50 leading-relaxed mb-3 flex-1" x-text="tmpl.description"></p>

                    <!-- Steps Preview -->
                    <div class="flex flex-wrap gap-1.5 mb-4">
                        <template x-for="(step, si) in (tmpl.steps || [])" :key="si">
                            <span class="px-2 py-0.5 rounded-lg text-[10px] font-medium glass-light text-brand-300 flex items-center gap-1">
                                <span class="w-4 h-4 rounded bg-brand-500/20 flex items-center justify-center text-[9px] font-bold" x-text="si + 1"></span>
                                <span x-text="step.name || step.type"></span>
                            </span>
                        </template>
                    </div>

                    <button @click="createFromTemplate(tmpl.template_id)" :disabled="creatingTemplateId === tmpl.template_id"
                            class="w-full px-4 py-2.5 rounded-xl gradient-brand text-white text-sm font-semibold hover:opacity-90 transition disabled:opacity-50 flex items-center justify-center gap-2">
                        <i data-lucide="zap" class="w-4 h-4" x-show="creatingTemplateId !== tmpl.template_id"></i>
                        <i data-lucide="loader" class="w-4 h-4 animate-spin" x-show="creatingTemplateId === tmpl.template_id"></i>
                        <span x-text="creatingTemplateId === tmpl.template_id ? 'Criando...' : 'Criar Workflow'"></span>
                    </button>
                </div>
            </template>
        </div>

        <!-- Empty State -->
        <div x-show="!templatesLoading && templates.length === 0" class="glass-card rounded-2xl p-10 text-center">
            <div class="w-14 h-14 rounded-2xl gradient-ocean flex items-center justify-center mx-auto mb-4 opacity-50">
                <i data-lucide="layout-template" class="w-7 h-7"></i>
            </div>
            <p class="text-white/40 text-sm">Nenhum template disponivel no momento.</p>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════ -->
    <!-- TAB: RUNS (EXECUCOES)                                          -->
    <!-- ═══════════════════════════════════════════════════════════════ -->
    <div x-show="activeTab === 'runs'" x-transition>

        <div class="flex items-center justify-between mb-4">
            <h3 class="text-base font-bold text-white/80">Execucoes de Workflows</h3>
            <button @click="loadRuns()" class="px-3 py-2 rounded-xl glass-light text-xs text-white/60 hover:text-white transition flex items-center gap-1">
                <i data-lucide="refresh-cw" class="w-3.5 h-3.5"></i> Atualizar
            </button>
        </div>

        <!-- Loading State -->
        <template x-if="runsLoading">
            <div class="space-y-3">
                <template x-for="i in 4" :key="i">
                    <div class="glass-card rounded-2xl p-4">
                        <div class="flex items-center gap-3">
                            <div class="skeleton w-9 h-9 rounded-xl"></div>
                            <div class="flex-1">
                                <div class="skeleton h-4 w-1/3 mb-2"></div>
                                <div class="skeleton h-3 w-1/2"></div>
                            </div>
                            <div class="skeleton h-6 w-16 rounded-lg"></div>
                        </div>
                    </div>
                </template>
            </div>
        </template>

        <!-- Empty State -->
        <div x-show="!runsLoading && runs.length === 0" class="glass-card rounded-2xl p-10 text-center">
            <div class="w-14 h-14 rounded-2xl gradient-ocean flex items-center justify-center mx-auto mb-4 opacity-50">
                <i data-lucide="play-circle" class="w-7 h-7"></i>
            </div>
            <p class="text-white/40 text-sm mb-1">Nenhuma execucao registrada</p>
            <p class="text-white/25 text-xs">Execute um workflow para ver os resultados aqui.</p>
        </div>

        <!-- Runs List -->
        <div x-show="!runsLoading && runs.length > 0" class="space-y-3">
            <template x-for="run in runs" :key="run.run_id">
                <div class="glass-card rounded-2xl p-4">
                    <div class="flex items-center justify-between gap-4 cursor-pointer" @click="toggleRunDetails(run)">
                        <div class="flex items-center gap-3 min-w-0">
                            <!-- Status icon -->
                            <div class="w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0"
                                 :class="runStatusBg(run.status)">
                                <i :data-lucide="runStatusIcon(run.status)"
                                   class="w-5 h-5"
                                   :class="runStatusColor(run.status)"></i>
                            </div>
                            <div class="min-w-0">
                                <h4 class="font-semibold text-white/90 text-sm truncate" x-text="run.workflow_name || 'Workflow'"></h4>
                                <div class="flex items-center gap-3 text-xs text-white/30">
                                    <span x-text="(run.steps_completed || 0) + '/' + (run.steps_total || 0) + ' passos'"></span>
                                    <span x-show="run.duration" x-text="run.duration + 's'"></span>
                                    <span x-text="timeAgo(run.started_at)"></span>
                                </div>
                            </div>
                        </div>
                        <div class="flex items-center gap-2 flex-shrink-0">
                            <span class="px-2.5 py-1 rounded-lg text-[11px] font-semibold"
                                  :class="runStatusBadge(run.status)"
                                  x-text="statusLabel(run.status)"></span>
                            <i data-lucide="chevron-down" class="w-4 h-4 text-white/30 transition-transform duration-200" :class="run._expanded && 'rotate-180'"></i>
                        </div>
                    </div>

                    <!-- Expanded: Step-by-step progress -->
                    <div x-show="run._expanded" x-transition class="mt-3 pt-3 border-t border-white/5">
                        <!-- Step progress bar -->
                        <div class="mb-3" x-show="run.steps_total > 0">
                            <div class="w-full h-1.5 rounded-full bg-dark-700 overflow-hidden">
                                <div class="h-full rounded-full transition-all duration-500"
                                     :class="run.status === 'completed' ? 'gradient-success' : run.status === 'failed' ? 'gradient-fire' : 'gradient-brand'"
                                     :style="'width:' + ((run.steps_completed || 0) / (run.steps_total || 1) * 100) + '%'"></div>
                            </div>
                        </div>

                        <!-- Loading run details -->
                        <div x-show="run._loadingDetails" class="py-4 text-center">
                            <i data-lucide="loader" class="w-5 h-5 text-brand-400 animate-spin mx-auto mb-2"></i>
                            <p class="text-xs text-white/30">Carregando detalhes...</p>
                        </div>

                        <!-- Step results -->
                        <template x-for="(sr, sri) in (run.results || [])" :key="sri">
                            <div class="py-2 border-b border-white/5 last:border-0">
                                <div class="flex items-center gap-2 mb-1">
                                    <span class="w-5 h-5 rounded bg-brand-500/20 flex items-center justify-center text-[10px] font-bold text-brand-300" x-text="sri + 1"></span>
                                    <i :data-lucide="sr.success ? 'check-circle' : sr.success === false ? 'x-circle' : 'clock'"
                                       class="w-4 h-4"
                                       :class="sr.success ? 'text-green-400' : sr.success === false ? 'text-red-400' : 'text-yellow-400'"></i>
                                    <span class="text-sm text-white/70 font-medium" x-text="sr.step_name || sr.step_type"></span>
                                    <span class="text-xs text-white/30 ml-auto" x-text="sr.step_type"></span>
                                    <span class="text-xs text-white/20" x-show="sr.duration" x-text="sr.duration + 's'"></span>
                                </div>
                                <div x-show="sr.error" class="ml-7 text-xs text-red-400/70 mt-1" x-text="sr.error"></div>
                                <div x-show="sr.result && !sr.error" class="ml-7 mt-1">
                                    <template x-if="sr.result?.script">
                                        <pre class="text-xs text-white/40 bg-dark-800 rounded-lg p-2 max-h-32 overflow-y-auto whitespace-pre-wrap" x-text="sr.result.script?.substring(0, 300) + (sr.result.script?.length > 300 ? '...' : '')"></pre>
                                    </template>
                                    <template x-if="sr.result?.trends_found !== undefined">
                                        <span class="text-xs text-white/40" x-text="sr.result.trends_found + ' tendencias detectadas'"></span>
                                    </template>
                                    <template x-if="sr.result?.videos_found !== undefined">
                                        <span class="text-xs text-white/40" x-text="sr.result.videos_found + ' videos encontrados'"></span>
                                    </template>
                                    <template x-if="sr.result?.replies_generated !== undefined">
                                        <span class="text-xs text-white/40" x-text="sr.result.replies_generated + ' respostas geradas'"></span>
                                    </template>
                                    <template x-if="sr.result?.summary">
                                        <p class="text-xs text-white/40" x-text="sr.result.summary?.substring(0, 200)"></p>
                                    </template>
                                </div>
                            </div>
                        </template>

                        <!-- No results yet -->
                        <div x-show="!run._loadingDetails && (!run.results || run.results.length === 0)" class="py-3 text-center">
                            <p class="text-xs text-white/25">Nenhum detalhe disponivel para esta execucao.</p>
                        </div>
                    </div>
                </div>
            </template>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════ -->
    <!-- TAB: CONTENT FACTORY                                           -->
    <!-- ═══════════════════════════════════════════════════════════════ -->
    <div x-show="activeTab === 'factory'" x-transition>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

            <!-- Factory 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="factory" class="w-5 h-5"></i>
                    </div>
                    Content Factory
                </h3>
                <p class="text-xs text-white/40 mb-4">Pipeline rapido de producao de conteudo. Gere multiplos roteiros de uma vez.</p>

                <div class="space-y-4">
                    <!-- Topics -->
                    <div>
                        <label class="text-xs text-white/50 mb-1.5 block font-medium">Topicos (um por linha)</label>
                        <textarea x-model="cfTopics" rows="5" placeholder="Ex:&#10;Como viralizar no TikTok&#10;Truques de edicao com CapCut&#10;Tendencias de 2026&#10;(ou deixe vazio para auto-detectar)"
                                  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 transition"></textarea>
                    </div>

                    <!-- Count Slider -->
                    <div>
                        <div class="flex items-center justify-between mb-1.5">
                            <label class="text-xs text-white/50 font-medium">Quantidade</label>
                            <span class="text-xs font-bold text-brand-300" x-text="cfCount + ' roteiro(s)'"></span>
                        </div>
                        <input x-model="cfCount" type="range" min="1" max="20" step="1"
                               class="w-full h-2 rounded-full appearance-none cursor-pointer"
                               style="background: linear-gradient(to right, #7c3aed, #ec4899); accent-color: #7c3aed;">
                        <div class="flex items-center justify-between text-[10px] text-white/20 mt-1">
                            <span>1</span>
                            <span>10</span>
                            <span>20</span>
                        </div>
                    </div>

                    <!-- Niche -->
                    <div>
                        <label class="text-xs text-white/50 mb-1.5 block font-medium">Nicho</label>
                        <input x-model="cfNiche" type="text" placeholder="Ex: fitness, tech, humor..."
                               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 transition">
                    </div>

                    <!-- Start Button -->
                    <button @click="runContentFactory()" :disabled="cfLoading"
                            class="w-full px-6 py-3 rounded-xl gradient-fire text-white font-bold text-sm hover:opacity-90 transition disabled:opacity-50">
                        <span x-show="!cfLoading" class="flex items-center justify-center gap-2">
                            <i data-lucide="zap" class="w-4 h-4"></i> Iniciar Producao
                        </span>
                        <span x-show="cfLoading" class="flex items-center justify-center gap-2">
                            <i data-lucide="loader" class="w-4 h-4 animate-spin"></i> Gerando... (pode demorar)
                        </span>
                    </button>
                    <p class="text-[10px] text-white/20 text-center">100% IA local via Ollama - Custo R$0</p>
                </div>
            </div>

            <!-- Factory Results -->
            <div class="lg:col-span-2">
                <!-- Empty state -->
                <div x-show="!cfResult && !cfLoading" class="glass-card rounded-2xl p-10 text-center h-full flex flex-col items-center justify-center min-h-[300px]">
                    <i data-lucide="factory" class="w-16 h-16 text-white/10 mb-4"></i>
                    <p class="text-white/30 text-sm">Os roteiros gerados aparecerao aqui.</p>
                    <p class="text-white/20 text-xs mt-1">Configure e clique em Iniciar Producao.</p>
                </div>

                <!-- Loading state -->
                <div x-show="cfLoading && !cfResult" class="glass-card rounded-2xl p-10 text-center h-full flex flex-col items-center justify-center min-h-[300px]">
                    <div class="w-16 h-16 rounded-full border-4 border-brand-500/20 border-t-brand-500 animate-spin mb-4"></div>
                    <p class="text-white/50 text-sm">Gerando roteiros com IA local...</p>
                    <p class="text-white/30 text-xs mt-1">Isso pode levar alguns minutos.</p>
                </div>

                <!-- Results -->
                <div x-show="cfResult" class="space-y-3">
                    <div class="flex items-center justify-between">
                        <h3 class="text-base font-bold text-white/80">
                            <span x-text="cfResult?.total_generated || 0"></span> Roteiros Gerados
                        </h3>
                        <div class="flex items-center gap-3">
                            <span class="text-xs text-green-400 font-medium" x-text="cfResult?.cost || 'R$0.00'"></span>
                            <button @click="cfResult = null" class="text-xs text-white/30 hover:text-white transition">Limpar</button>
                        </div>
                    </div>

                    <template x-for="(item, idx) in (cfResult?.content || [])" :key="idx">
                        <div class="glass-card rounded-2xl p-4">
                            <div class="flex items-start justify-between gap-3 cursor-pointer" @click="item._expanded = !item._expanded">
                                <div class="flex items-center gap-2 min-w-0">
                                    <span class="flex-shrink-0 w-8 h-8 rounded-xl gradient-brand flex items-center justify-center text-xs font-bold text-white" x-text="item.index || idx + 1"></span>
                                    <div class="min-w-0">
                                        <h4 class="font-semibold text-white/90 text-sm truncate" x-text="item.topic"></h4>
                                        <div class="flex items-center gap-2 text-xs text-white/30">
                                            <span x-text="(item.word_count || 0) + ' palavras'"></span>
                                            <span x-show="item.estimated_duration" x-text="'~' + item.estimated_duration"></span>
                                            <span x-show="item.niche" class="text-brand-300" x-text="item.niche"></span>
                                        </div>
                                    </div>
                                </div>
                                <div class="flex items-center gap-2 flex-shrink-0">
                                    <span class="px-2 py-0.5 rounded-lg text-[10px] font-semibold bg-green-500/20 text-green-400">Pronto</span>
                                    <i data-lucide="chevron-down" class="w-4 h-4 text-white/30 transition-transform" :class="item._expanded && 'rotate-180'"></i>
                                </div>
                            </div>

                            <div x-show="item._expanded" x-transition class="mt-3 pt-3 border-t border-white/5">
                                <pre class="text-xs text-white/60 bg-dark-800 rounded-xl p-4 whitespace-pre-wrap max-h-64 overflow-y-auto leading-relaxed" x-text="item.script"></pre>
                                <div class="flex gap-2 mt-3">
                                    <button @click="copyToClipboard(item.script)" class="flex items-center gap-1 px-3 py-1.5 rounded-lg glass-light text-white/60 text-xs hover:text-white transition">
                                        <i data-lucide="copy" class="w-3 h-3"></i> Copiar
                                    </button>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════ -->
    <!-- TAB: STATISTICS                                                -->
    <!-- ═══════════════════════════════════════════════════════════════ -->
    <div x-show="activeTab === 'stats'" x-transition>

        <!-- KPI Cards -->
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
            <div class="glass-card rounded-2xl p-4 text-center">
                <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center mx-auto mb-2">
                    <i data-lucide="git-branch" class="w-5 h-5"></i>
                </div>
                <p class="stat-number text-gradient" x-text="stats?.total_workflows || 0"></p>
                <p class="text-xs text-white/40 mt-1">Total Workflows</p>
            </div>
            <div class="glass-card rounded-2xl p-4 text-center">
                <div class="w-10 h-10 rounded-xl gradient-ocean flex items-center justify-center mx-auto mb-2">
                    <i data-lucide="play-circle" class="w-5 h-5"></i>
                </div>
                <p class="stat-number text-accent-cyan" x-text="stats?.total_runs || 0"></p>
                <p class="text-xs text-white/40 mt-1">Total Execucoes</p>
            </div>
            <div class="glass-card rounded-2xl p-4 text-center">
                <div class="w-10 h-10 rounded-xl gradient-success flex items-center justify-center mx-auto mb-2">
                    <i data-lucide="check-circle" class="w-5 h-5"></i>
                </div>
                <p class="stat-number text-accent-green" x-text="(stats?.success_rate || 0) + '%'"></p>
                <p class="text-xs text-white/40 mt-1">Taxa de Sucesso</p>
            </div>
            <div class="glass-card rounded-2xl p-4 text-center">
                <div class="w-10 h-10 rounded-xl gradient-fire flex items-center justify-center mx-auto mb-2">
                    <i data-lucide="timer" class="w-5 h-5"></i>
                </div>
                <p class="stat-number text-accent-orange" x-text="(stats?.avg_duration || 0) + 's'"></p>
                <p class="text-xs text-white/40 mt-1">Duracao Media</p>
            </div>
        </div>

        <!-- Detailed Stats Grid -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- General Summary -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-base font-bold text-white/80 mb-4 flex items-center gap-2">
                    <i data-lucide="bar-chart-3" class="w-5 h-5 text-brand-400"></i> Resumo Geral
                </h3>
                <div class="space-y-3">
                    <div class="flex items-center justify-between py-2 border-b border-white/5">
                        <span class="text-sm text-white/50">Total de Workflows</span>
                        <span class="text-sm font-bold text-white/90" x-text="stats?.total_workflows || 0"></span>
                    </div>
                    <div class="flex items-center justify-between py-2 border-b border-white/5">
                        <span class="text-sm text-white/50">Workflows Ativos</span>
                        <span class="text-sm font-bold text-green-400" x-text="stats?.active_workflows || 0"></span>
                    </div>
                    <div class="flex items-center justify-between py-2 border-b border-white/5">
                        <span class="text-sm text-white/50">Total de Execucoes</span>
                        <span class="text-sm font-bold text-white/90" x-text="stats?.total_runs || 0"></span>
                    </div>
                    <div class="flex items-center justify-between py-2 border-b border-white/5">
                        <span class="text-sm text-white/50">Execucoes com Sucesso</span>
                        <span class="text-sm font-bold text-green-400" x-text="stats?.successful_runs || 0"></span>
                    </div>
                    <div class="flex items-center justify-between py-2 border-b border-white/5">
                        <span class="text-sm text-white/50">Execucoes Falhadas</span>
                        <span class="text-sm font-bold text-red-400" x-text="stats?.failed_runs || 0"></span>
                    </div>
                    <div class="flex items-center justify-between py-2 border-b border-white/5">
                        <span class="text-sm text-white/50">Steps Executados</span>
                        <span class="text-sm font-bold text-brand-300" x-text="stats?.total_steps_executed || 0"></span>
                    </div>
                    <div class="flex items-center justify-between py-2 border-b border-white/5">
                        <span class="text-sm text-white/50">Execucoes Hoje</span>
                        <span class="text-sm font-bold text-accent-cyan" x-text="stats?.runs_today || 0"></span>
                    </div>
                    <div class="flex items-center justify-between py-2">
                        <span class="text-sm text-white/50">Custo Total</span>
                        <span class="text-sm font-bold text-green-400" x-text="stats?.cost_total || 'R$0.00'"></span>
                    </div>
                </div>
            </div>

            <!-- Most Used Templates -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-base font-bold text-white/80 mb-4 flex items-center gap-2">
                    <i data-lucide="trophy" class="w-5 h-5 text-yellow-400"></i> Templates Mais Usados
                </h3>
                <div x-show="stats?.most_used_templates && stats.most_used_templates.length > 0" class="space-y-3">
                    <template x-for="(t, ti) in (stats?.most_used_templates || [])" :key="ti">
                        <div class="flex items-center gap-3 py-2 border-b border-white/5 last:border-0">
                            <span class="w-7 h-7 rounded-lg gradient-brand flex items-center justify-center text-xs font-bold" x-text="ti + 1"></span>
                            <div class="flex-1 min-w-0">
                                <p class="text-sm text-white/80 font-medium truncate" x-text="t.template"></p>
                            </div>
                            <span class="text-sm font-bold text-brand-300" x-text="t.count + 'x'"></span>
                        </div>
                    </template>
                </div>
                <div x-show="!stats?.most_used_templates || stats.most_used_templates.length === 0" class="text-center py-6">
                    <i data-lucide="trophy" class="w-10 h-10 text-white/10 mx-auto mb-2"></i>
                    <p class="text-xs text-white/30">Nenhum dado ainda. Execute workflows para gerar estatisticas.</p>
                </div>

                <!-- Cost note -->
                <div class="mt-4 p-3 rounded-xl bg-green-500/10 border border-green-500/20">
                    <div class="flex items-center gap-2">
                        <i data-lucide="leaf" class="w-4 h-4 text-green-400"></i>
                        <span class="text-xs font-semibold text-green-400">100% IA Local</span>
                    </div>
                    <p class="text-[11px] text-green-400/60 mt-1" x-text="stats?.cost_note || 'Ollama local - custo zero'"></p>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════ -->
    <!-- MODAL: COST ESTIMATE                                           -->
    <!-- ═══════════════════════════════════════════════════════════════ -->
    <div x-show="showCostModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm"
         @click.self="showCostModal = false" @keydown.escape.window="showCostModal = false"
         x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100"
         x-transition:leave="transition ease-in duration-150" x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0">
        <div class="glass rounded-2xl w-full max-w-lg p-6" @click.stop>
            <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="calculator" class="w-5 h-5 text-brand-400"></i> Estimativa de Custo
                </h3>
                <button @click="showCostModal = false" class="p-1.5 rounded-lg hover:bg-white/10 transition">
                    <i data-lucide="x" class="w-5 h-5"></i>
                </button>
            </div>
            <div x-show="costEstimate">
                <div class="mb-4 p-4 rounded-xl bg-green-500/10 border border-green-500/20 text-center">
                    <p class="text-2xl font-bold text-green-400" x-text="costEstimate?.total_cost || 'R$0.00'"></p>
                    <p class="text-xs text-green-400/60 mt-1">por execucao</p>
                </div>
                <div class="space-y-2 mb-4">
                    <template x-for="(sc, sci) in (costEstimate?.step_costs || [])" :key="sci">
                        <div class="flex items-center justify-between py-2 border-b border-white/5 text-sm">
                            <div class="flex items-center gap-2">
                                <span class="w-5 h-5 rounded bg-brand-500/20 flex items-center justify-center text-[10px] font-bold text-brand-300" x-text="sci + 1"></span>
                                <span class="text-white/70" x-text="sc.step_name"></span>
                            </div>
                            <div class="flex items-center gap-3">
                                <span class="text-xs text-white/30" x-text="sc.estimated_time"></span>
                                <span class="text-xs font-semibold" :class="sc.engine === 'local' ? 'text-green-400' : 'text-yellow-400'" x-text="sc.cost"></span>
                            </div>
                        </div>
                    </template>
                </div>
                <div class="flex items-center justify-between text-xs text-white/30">
                    <span>Tempo estimado total</span>
                    <span x-text="costEstimate?.estimated_time || '--'"></span>
                </div>
                <p class="text-[11px] text-white/20 mt-2" x-text="costEstimate?.note || ''"></p>
            </div>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════════ -->
    <!-- MODAL: RUN DETAILS                                             -->
    <!-- ═══════════════════════════════════════════════════════════════ -->
    <div x-show="selectedRun" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-sm"
         @click.self="selectedRun = null" @keydown.escape.window="selectedRun = null"
         x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100"
         x-transition:leave="transition ease-in duration-150" x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0">
        <div class="glass rounded-2xl w-full max-w-2xl p-6 max-h-[80vh] overflow-y-auto" @click.stop>
            <div class="flex items-center justify-between mb-4">
                <div>
                    <h3 class="text-lg font-bold text-white/90" x-text="selectedRun?.workflow_name || 'Detalhes da Execucao'"></h3>
                    <p class="text-xs text-white/40 mt-0.5" x-text="'Run ID: ' + (selectedRun?.run_id || '')"></p>
                </div>
                <button @click="selectedRun = null" class="p-1.5 rounded-lg hover:bg-white/10 transition">
                    <i data-lucide="x" class="w-5 h-5"></i>
                </button>
            </div>

            <!-- Run status header -->
            <div class="flex items-center gap-3 mb-4 p-3 rounded-xl glass-light">
                <div class="w-10 h-10 rounded-xl flex items-center justify-center"
                     :class="runStatusBg(selectedRun?.status)">
                    <i :data-lucide="runStatusIcon(selectedRun?.status)"
                       class="w-5 h-5" :class="runStatusColor(selectedRun?.status)"></i>
                </div>
                <div>
                    <span class="text-sm font-bold" :class="runStatusColor(selectedRun?.status)" x-text="statusLabel(selectedRun?.status)"></span>
                    <div class="flex items-center gap-3 text-xs text-white/30">
                        <span x-text="(selectedRun?.steps_completed || 0) + '/' + (selectedRun?.steps_total || 0) + ' passos'"></span>
                        <span x-show="selectedRun?.duration" x-text="selectedRun?.duration + 's'"></span>
                        <span x-text="timeAgo(selectedRun?.started_at)"></span>
                    </div>
                </div>
            </div>

            <!-- Steps -->
            <div class="space-y-2">
                <template x-for="(sr, sri) in (selectedRun?.results || [])" :key="sri">
                    <div class="p-3 rounded-xl glass-light border border-white/5">
                        <div class="flex items-center gap-2">
                            <span class="w-6 h-6 rounded-lg bg-brand-500/20 flex items-center justify-center text-[10px] font-bold text-brand-300" x-text="sri + 1"></span>
                            <i :data-lucide="sr.success ? 'check-circle' : sr.success === false ? 'x-circle' : 'clock'"
                               class="w-4 h-4" :class="sr.success ? 'text-green-400' : sr.success === false ? 'text-red-400' : 'text-yellow-400'"></i>
                            <span class="text-sm text-white/80 font-medium" x-text="sr.step_name || sr.step_type"></span>
                            <span class="text-xs text-white/20 ml-auto" x-show="sr.duration" x-text="sr.duration + 's'"></span>
                        </div>
                        <div x-show="sr.error" class="ml-8 mt-2 text-xs text-red-400/70 bg-red-500/5 rounded-lg p-2" x-text="sr.error"></div>
                    </div>
                </template>
            </div>
        </div>
    </div>

</div>
{% endblock %}

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

        // Workflows
        workflows: [],
        workflowsLoading: false,
        runningId: null,
        lastRunResult: null,

        // Create
        newName: '',
        newDescription: '',
        newTrigger: 'manual',
        newSteps: [{type: '', name: '', config: {}}],
        triggerConfig: { cron: '', secret: '', event_type: '' },
        createLoading: false,

        // Templates
        templates: [],
        templatesLoading: false,
        creatingTemplateId: null,

        // Runs
        runs: [],
        runsLoading: false,
        selectedRun: null,

        // Content Factory
        cfTopics: '',
        cfCount: 5,
        cfNiche: '',
        cfLoading: false,
        cfResult: null,

        // Stats
        stats: null,

        // Step types
        stepTypes: [],

        // Cost modal
        showCostModal: false,
        costEstimate: null,

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

        // ── Data Loading ──────────────────────────────────────────

        async loadStepTypes() {
            try {
                this.stepTypes = await apiCall('/api/autoflow/step-types');
            } catch(e) { console.error('Erro step-types:', e); }
        },

        async loadWorkflows() {
            this.workflowsLoading = true;
            try {
                this.workflows = await apiCall('/api/autoflow/workflows');
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            } catch(e) { console.error('Erro workflows:', e); }
            this.workflowsLoading = false;
        },

        async loadTemplates() {
            this.templatesLoading = true;
            try {
                this.templates = await apiCall('/api/autoflow/templates');
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            } catch(e) { console.error('Erro templates:', e); }
            this.templatesLoading = false;
        },

        async loadRuns() {
            this.runsLoading = true;
            try {
                const data = await apiCall('/api/autoflow/runs');
                this.runs = (Array.isArray(data) ? data : []).map(r => ({ ...r, _expanded: false, _loadingDetails: false }));
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            } catch(e) { console.error('Erro runs:', e); }
            this.runsLoading = false;
        },

        async loadStats() {
            try {
                this.stats = await apiCall('/api/autoflow/stats');
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            } catch(e) { console.error('Erro stats:', e); }
        },

        // ── Workflow Actions ──────────────────────────────────────

        async createWorkflow() {
            if (!this.newName.trim()) { showToast('Nome do workflow obrigatorio', 'warning'); return; }
            this.createLoading = true;
            try {
                const validSteps = this.newSteps.filter(s => s.type);
                const payload = {
                    name: this.newName.trim(),
                    description: this.newDescription.trim(),
                    trigger_type: this.newTrigger,
                    trigger_config: this.newTrigger !== 'manual' ? { ...this.triggerConfig } : {},
                    steps: validSteps,
                };
                await apiCall('/api/autoflow/workflows', 'POST', payload);
                showToast('Workflow criado com sucesso!', 'success');
                this.resetCreateForm();
                this.activeTab = 'workflows';
                await this.loadWorkflows();
            } catch(e) { showToast('Erro ao criar workflow', 'error'); }
            this.createLoading = false;
        },

        resetCreateForm() {
            this.newName = '';
            this.newDescription = '';
            this.newTrigger = 'manual';
            this.newSteps = [{type: '', name: '', config: {}}];
            this.triggerConfig = { cron: '', secret: '', event_type: '' };
        },

        async deleteWorkflow(id) {
            if (!confirm('Tem certeza que deseja deletar este workflow?')) return;
            try {
                await apiCall('/api/autoflow/workflows/' + id, 'DELETE');
                showToast('Workflow deletado', 'success');
                this.workflows = this.workflows.filter(w => w.workflow_id !== id);
            } catch(e) { showToast('Erro ao deletar', 'error'); }
        },

        async runWorkflow(id) {
            this.runningId = id;
            this.lastRunResult = null;
            showToast('Executando workflow...', 'info');
            try {
                const result = await apiCall('/api/autoflow/workflows/' + id + '/run', 'POST', { input_data: {} });
                result.workflow_id = id;
                this.lastRunResult = result;
                const status = result.status || 'unknown';
                if (status === 'completed' || status === 'success') {
                    showToast('Workflow concluido com sucesso!', 'success');
                } else if (status === 'partial') {
                    showToast('Workflow concluido parcialmente', 'warning');
                } else {
                    showToast('Workflow falhou', 'error');
                }
                await this.loadWorkflows();
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            } catch(e) { showToast('Erro ao executar workflow', 'error'); }
            this.runningId = null;
        },

        async createFromTemplate(templateId) {
            this.creatingTemplateId = templateId;
            try {
                await apiCall('/api/autoflow/templates/' + templateId + '/create', 'POST');
                showToast('Workflow criado a partir do template!', 'success');
                this.activeTab = 'workflows';
                await this.loadWorkflows();
            } catch(e) { showToast('Erro ao criar do template', 'error'); }
            this.creatingTemplateId = null;
        },

        async viewCostEstimate(id) {
            try {
                this.costEstimate = await apiCall('/api/autoflow/cost-estimate/' + id);
                this.showCostModal = true;
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            } catch(e) { showToast('Erro ao carregar estimativa', 'error'); }
        },

        // ── Run Details ──────────────────────────────────────────

        async toggleRunDetails(run) {
            run._expanded = !run._expanded;
            if (run._expanded && (!run.results || run.results.length === 0)) {
                run._loadingDetails = true;
                try {
                    const details = await apiCall('/api/autoflow/runs/' + run.run_id);
                    run.results = details.results || [];
                    run.steps_completed = details.steps_completed || run.steps_completed;
                    run.steps_total = details.steps_total || run.steps_total;
                    run.duration = details.duration || run.duration;
                    this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
                } catch(e) { console.error('Erro run details:', e); }
                run._loadingDetails = false;
            }
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        // ── Content Factory ──────────────────────────────────────

        async runContentFactory() {
            this.cfLoading = true;
            this.cfResult = null;
            try {
                const topicsList = this.cfTopics.split('\n').map(t => t.trim()).filter(t => t.length > 0);
                const payload = {
                    topics: topicsList.length > 0 ? topicsList : null,
                    count: parseInt(this.cfCount),
                    niche: this.cfNiche.trim() || null,
                };
                this.cfResult = await apiCall('/api/autoflow/content-factory', 'POST', payload);
                if (this.cfResult?.content) {
                    this.cfResult.content = this.cfResult.content.map(c => ({...c, _expanded: false}));
                }
                showToast((this.cfResult?.total_generated || 0) + ' roteiros gerados!', 'success');
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            } catch(e) { showToast('Erro na Content Factory', 'error'); console.error(e); }
            this.cfLoading = false;
        },

        // ── Steps Builder ────────────────────────────────────────

        moveStep(idx, direction) {
            const newIdx = idx + direction;
            if (newIdx < 0 || newIdx >= this.newSteps.length) return;
            const temp = this.newSteps[idx];
            this.newSteps[idx] = this.newSteps[newIdx];
            this.newSteps[newIdx] = temp;
            // Force reactivity
            this.newSteps = [...this.newSteps];
        },

        // ── Helpers ──────────────────────────────────────────────

        triggerLabel(type) {
            const labels = { manual: 'Manual', schedule: 'Agendado', webhook: 'Webhook', event: 'Evento' };
            return labels[type] || type;
        },

        statusLabel(status) {
            const labels = { pending: 'Pendente', running: 'Rodando', completed: 'Concluido', success: 'Concluido', failed: 'Falhou', partial: 'Parcial' };
            return labels[status] || status || 'Desconhecido';
        },

        runStatusIcon(status) {
            const icons = { pending: 'clock', running: 'loader', completed: 'check-circle', success: 'check-circle', failed: 'x-circle', partial: 'alert-circle' };
            return icons[status] || 'help-circle';
        },

        runStatusColor(status) {
            const colors = { pending: 'text-yellow-400', running: 'text-brand-400 animate-spin', completed: 'text-green-400', success: 'text-green-400', failed: 'text-red-400', partial: 'text-yellow-400' };
            return colors[status] || 'text-white/40';
        },

        runStatusBg(status) {
            const bgs = { pending: 'bg-yellow-500/20', running: 'bg-brand-500/20', completed: 'bg-green-500/20', success: 'bg-green-500/20', failed: 'bg-red-500/20', partial: 'bg-yellow-500/20' };
            return bgs[status] || 'bg-white/10';
        },

        runStatusBadge(status) {
            const badges = { pending: 'bg-yellow-500/20 text-yellow-400', running: 'bg-brand-500/20 text-brand-400', completed: 'bg-green-500/20 text-green-400', success: 'bg-green-500/20 text-green-400', failed: 'bg-red-500/20 text-red-400', partial: 'bg-yellow-500/20 text-yellow-400' };
            return badges[status] || 'bg-white/10 text-white/40';
        },

        templateGradient(color) {
            const map = { brand: 'gradient-brand', cyan: 'gradient-ocean', ocean: 'gradient-ocean', pink: 'gradient-brand', orange: 'gradient-fire', fire: 'gradient-fire', green: 'gradient-success', success: 'gradient-success' };
            return map[color] || 'gradient-brand';
        },

        copyToClipboard(text) {
            if (!text) return;
            navigator.clipboard.writeText(text).then(() => {
                showToast('Copiado para a area de transferencia!', 'success');
            }).catch(() => {
                showToast('Erro ao copiar', 'error');
            });
        },
    };
}
</script>
{% endblock %}
