{% extends "base.html" %}
{% block title %}ScriptGenius - Viral Social Pro{% endblock %}
{% block nav_scriptgenius %}active{% endblock %}
{% block page_title %}ScriptGenius{% endblock %}
{% block page_subtitle %}Roteiros virais com IA, banco de hooks e TTS{% endblock %}

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

    <!-- TABS -->
    <div class="flex gap-2 mb-6 overflow-x-auto pb-1">
        <button class="tab-btn" :class="tab === 'generate' && 'active'" @click="tab = 'generate'">
            <i data-lucide="sparkles" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Gerar Script
        </button>
        <button class="tab-btn" :class="tab === 'hooks' && 'active'" @click="tab = 'hooks'; loadHooks()">
            <i data-lucide="anchor" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Banco de Hooks
        </button>
        <button class="tab-btn" :class="tab === 'cta' && 'active'" @click="tab = 'cta'">
            <i data-lucide="megaphone" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> CTA & Otimizacao
        </button>
        <button class="tab-btn" :class="tab === 'scripts' && 'active'" @click="tab = 'scripts'; loadScripts()">
            <i data-lucide="file-text" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Meus Scripts
        </button>
        <button class="tab-btn" :class="tab === 'tts' && 'active'" @click="tab = 'tts'; loadVoices()">
            <i data-lucide="volume-2" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Narrador (TTS)
        </button>
    </div>

    <!-- TAB: GERAR SCRIPT -->
    <div x-show="tab === 'generate'" x-transition>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- Form -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                    <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center"><i data-lucide="sparkles" class="w-5 h-5"></i></div>
                    Gerar Roteiro com IA
                </h3>
                <div class="space-y-4">
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Topico do Video *</label>
                        <input x-model="genTopic" type="text" placeholder="Ex: Como ganhar seguidores rapido no TikTok"
                               class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="text-xs text-white/50 mb-1 block">Plataforma</label>
                            <select x-model="genPlatform" class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                                <option value="tiktok">TikTok</option>
                                <option value="instagram">Instagram</option>
                                <option value="youtube">YouTube</option>
                            </select>
                        </div>
                        <div>
                            <label class="text-xs text-white/50 mb-1 block">Estilo</label>
                            <select x-model="genStyle" class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                                <option value="tutorial">Tutorial</option>
                                <option value="storytelling">Storytelling</option>
                                <option value="humor">Humor</option>
                                <option value="review">Review</option>
                                <option value="trending">Trending</option>
                                <option value="motivacional">Motivacional</option>
                                <option value="lista">Lista/Top X</option>
                                <option value="antes_depois">Antes e Depois</option>
                                <option value="pov">POV</option>
                                <option value="react">React</option>
                            </select>
                        </div>
                    </div>
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Duracao (segundos)</label>
                        <input x-model.number="genDuration" type="range" min="15" max="180" step="5" class="w-full accent-brand-500">
                        <span class="text-xs text-white/40" x-text="genDuration + 's'"></span>
                    </div>
                    <button @click="generateScript()" :disabled="generating || !genTopic" class="w-full py-3 rounded-xl gradient-brand text-white font-bold text-sm disabled:opacity-50 transition flex items-center justify-center gap-2">
                        <i data-lucide="sparkles" class="w-4 h-4" :class="generating && 'animate-spin'"></i>
                        <span x-text="generating ? 'Gerando roteiro...' : 'Gerar Roteiro com IA'"></span>
                    </button>
                </div>

                <!-- Templates -->
                <div class="mt-6">
                    <h4 class="text-sm font-bold text-white/60 mb-3">Templates Rapidos</h4>
                    <div class="grid grid-cols-2 gap-2">
                        <template x-for="tmpl in templates" :key="tmpl.name">
                            <button @click="genStyle = tmpl.style; genTopic = genTopic || tmpl.name" class="glass-light rounded-xl p-3 text-left hover:border-brand-400/30 transition">
                                <p class="text-xs font-bold text-white/70" x-text="tmpl.name"></p>
                                <p class="text-[10px] text-white/30 mt-0.5" x-text="tmpl.description"></p>
                            </button>
                        </template>
                    </div>
                </div>
            </div>

            <!-- Preview -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                    <i data-lucide="eye" class="w-5 h-5 text-brand-400"></i> Preview do Roteiro
                </h3>
                <div x-show="!generatedScript" class="text-center py-16">
                    <i data-lucide="file-text" class="w-16 h-16 text-white/10 mx-auto mb-3"></i>
                    <p class="text-sm text-white/30">Preencha o formulario e clique em "Gerar" para criar seu roteiro</p>
                </div>
                <div x-show="generatedScript" x-transition>
                    <!-- Hook -->
                    <div class="mb-4" x-show="generatedScript?.hook">
                        <div class="flex items-center gap-2 mb-1">
                            <span class="px-2 py-0.5 rounded text-[10px] font-bold gradient-fire text-white">HOOK</span>
                            <span class="text-[10px] text-white/30">Primeiros 3 segundos</span>
                        </div>
                        <div class="glass-light rounded-xl p-3 text-sm text-white/80 border-l-2 border-accent-orange" x-text="generatedScript.hook"></div>
                    </div>
                    <!-- Body -->
                    <div class="mb-4" x-show="generatedScript?.body">
                        <div class="flex items-center gap-2 mb-1">
                            <span class="px-2 py-0.5 rounded text-[10px] font-bold gradient-brand text-white">CORPO</span>
                        </div>
                        <div class="glass-light rounded-xl p-3 text-sm text-white/70 whitespace-pre-wrap leading-relaxed" x-text="generatedScript.body"></div>
                    </div>
                    <!-- CTA -->
                    <div class="mb-4" x-show="generatedScript?.cta">
                        <div class="flex items-center gap-2 mb-1">
                            <span class="px-2 py-0.5 rounded text-[10px] font-bold gradient-success text-white">CTA</span>
                        </div>
                        <div class="glass-light rounded-xl p-3 text-sm text-white/80 border-l-2 border-accent-green" x-text="generatedScript.cta"></div>
                    </div>
                    <!-- Hashtags -->
                    <div class="flex flex-wrap gap-1 mb-4" x-show="generatedScript?.hashtags?.length">
                        <template x-for="tag in generatedScript.hashtags">
                            <span class="px-2 py-0.5 rounded text-[10px] glass-light text-brand-300" x-text="'#' + tag"></span>
                        </template>
                    </div>
                    <!-- Full Script (collapsible) -->
                    <details class="glass-light rounded-xl p-3 mb-4">
                        <summary class="text-xs font-bold text-white/50 cursor-pointer">Ver roteiro completo</summary>
                        <pre class="text-xs text-white/60 whitespace-pre-wrap mt-2 leading-relaxed" x-text="generatedScript?.full_script"></pre>
                    </details>
                    <!-- Actions -->
                    <div class="flex gap-2 flex-wrap">
                        <button @click="saveGeneratedScript()" class="px-4 py-2 rounded-xl gradient-brand text-white text-xs font-bold">Salvar Script</button>
                        <button @click="rewriteViral()" :disabled="rewriting" class="px-4 py-2 rounded-xl glass-card text-white/70 text-xs font-bold hover:text-white">
                            <span x-text="rewriting ? 'Reescrevendo...' : 'Reescrever p/ Viral'"></span>
                        </button>
                        <button @click="analyzeReadability(generatedScript?.full_script)" class="px-4 py-2 rounded-xl glass-card text-white/70 text-xs font-bold hover:text-white">Legibilidade</button>
                    </div>
                    <!-- Readability result -->
                    <div x-show="readabilityResult" x-transition class="glass-light rounded-xl p-3 mt-3">
                        <div class="flex items-center gap-3 mb-2">
                            <span class="text-lg font-bold" :style="'color:' + scoreColor(readabilityResult?.score || 0)" x-text="readabilityResult?.score + '/100'"></span>
                            <span class="text-xs text-white/40" x-text="'~' + readabilityResult?.duration_estimate_seconds + 's de narracao'"></span>
                        </div>
                        <template x-for="issue in (readabilityResult?.issues || [])">
                            <p class="text-[11px] text-white/50 flex items-center gap-1"><i data-lucide="alert-circle" class="w-3 h-3"></i> <span x-text="issue"></span></p>
                        </template>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- TAB: BANCO DE HOOKS -->
    <div x-show="tab === 'hooks'" x-transition>
        <div class="glass-card rounded-2xl p-5 mb-4">
            <div class="flex flex-col md:flex-row gap-3 items-end">
                <div class="flex-1">
                    <h3 class="text-lg font-bold text-white/90 mb-1 flex items-center gap-2">
                        <div class="w-10 h-10 rounded-xl gradient-fire flex items-center justify-center"><i data-lucide="anchor" class="w-5 h-5"></i></div>
                        Banco de Hooks
                    </h3>
                    <p class="text-xs text-white/40 ml-12">500+ hooks testados em PT-BR + geracao com IA</p>
                </div>
                <div class="flex gap-2">
                    <input x-model="hookSearch" @input.debounce.300ms="searchHooks()" type="text" placeholder="Buscar hooks..."
                           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 w-48">
                    <select x-model="hookCategory" @change="searchHooks()" class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                        <option value="">Todas categorias</option>
                        <option value="curiosidade">Curiosidade</option>
                        <option value="choque">Choque</option>
                        <option value="pergunta">Pergunta</option>
                        <option value="desafio">Desafio</option>
                        <option value="urgencia">Urgencia</option>
                        <option value="autoridade">Autoridade</option>
                        <option value="emocional">Emocional</option>
                        <option value="hack">Hack/Dica</option>
                        <option value="polemica">Polemica</option>
                        <option value="transformacao">Transformacao</option>
                    </select>
                    <button @click="seedHooks()" class="px-4 py-2 rounded-xl glass-card text-white/70 text-xs font-bold hover:text-white whitespace-nowrap">Seed Hooks</button>
                </div>
            </div>
        </div>

        <!-- AI Hook Generator -->
        <div class="glass-card rounded-2xl p-5 mb-4">
            <h4 class="text-sm font-bold text-white/70 mb-3">Gerar Hooks com IA</h4>
            <div class="flex gap-3">
                <input x-model="hookGenTopic" type="text" placeholder="Topico para gerar hooks..."
                       class="flex-1 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">
                <button @click="generateAiHooks()" :disabled="generatingHooks || !hookGenTopic" class="px-4 py-2 rounded-xl gradient-brand text-white text-xs font-bold disabled:opacity-50">
                    <span x-text="generatingHooks ? 'Gerando...' : 'Gerar com IA'"></span>
                </button>
            </div>
            <div x-show="aiHooks.length" x-transition class="mt-3 space-y-2">
                <template x-for="(hook, idx) in aiHooks" :key="idx">
                    <div class="glass-light rounded-xl p-3 flex items-center justify-between">
                        <p class="text-sm text-white/70" x-text="hook.text"></p>
                        <button @click="copyText(hook.text)" class="text-xs text-brand-300 hover:text-brand-200 px-2">Copiar</button>
                    </div>
                </template>
            </div>
        </div>

        <!-- Hook List -->
        <div class="grid-cards">
            <template x-for="hook in hooks" :key="hook.id">
                <div class="glass-card rounded-xl p-4 group">
                    <div class="flex items-start justify-between mb-2">
                        <span class="px-2 py-0.5 rounded text-[10px] font-bold" :class="{
                            'bg-brand-500/20 text-brand-300': hook.category === 'curiosidade',
                            'bg-red-500/20 text-red-400': hook.category === 'choque',
                            'bg-cyan-500/20 text-cyan-400': hook.category === 'pergunta',
                            'bg-orange-500/20 text-orange-400': hook.category === 'desafio',
                            'bg-yellow-500/20 text-yellow-400': hook.category === 'urgencia',
                            'bg-blue-500/20 text-blue-400': hook.category === 'autoridade',
                            'bg-pink-500/20 text-pink-400': hook.category === 'emocional',
                            'bg-green-500/20 text-green-400': hook.category === 'hack',
                            'bg-purple-500/20 text-purple-400': hook.category === 'polemica',
                            'bg-teal-500/20 text-teal-400': hook.category === 'transformacao',
                        }" x-text="hook.category"></span>
                        <div class="flex items-center gap-1 text-[10px] text-white/30">
                            <template x-for="i in 5"><i data-lucide="star" class="w-3 h-3" :class="i <= hook.rating ? 'text-yellow-400 fill-yellow-400' : 'text-white/10'"></i></template>
                        </div>
                    </div>
                    <p class="text-sm text-white/80 leading-relaxed mb-3" x-text="hook.text"></p>
                    <div class="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition">
                        <button @click="copyText(hook.text)" class="text-[10px] text-brand-300 hover:text-brand-200 px-2 py-1 rounded glass-light">Copiar</button>
                        <button @click="rateHook(hook.id, 5)" class="text-[10px] text-yellow-400 hover:text-yellow-300 px-2 py-1 rounded glass-light">+1</button>
                    </div>
                </div>
            </template>
        </div>
        <div x-show="hooks.length === 0 && !loadingHooks" class="text-center py-12">
            <i data-lucide="anchor" class="w-12 h-12 text-white/10 mx-auto mb-3"></i>
            <p class="text-sm text-white/30">Nenhum hook encontrado. Clique em "Seed Hooks" para popular o banco.</p>
        </div>
    </div>

    <!-- TAB: CTA & OTIMIZACAO -->
    <div x-show="tab === 'cta'" x-transition>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- CTA Generator -->
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                    <div class="w-10 h-10 rounded-xl gradient-success flex items-center justify-center"><i data-lucide="megaphone" class="w-5 h-5"></i></div>
                    Gerador de CTA
                </h3>
                <div class="space-y-3">
                    <input x-model="ctaTopic" type="text" placeholder="Topico do video..."
                           class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                    <div class="grid grid-cols-2 gap-3">
                        <select x-model="ctaGoal" class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                            <option value="seguir">Seguir perfil</option>
                            <option value="comentar">Gerar comentarios</option>
                            <option value="compartilhar">Compartilhar</option>
                            <option value="salvar">Salvar video</option>
                            <option value="link">Click no link</option>
                            <option value="comprar">Comprar</option>
                        </select>
                        <select x-model="ctaPlatform" class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-sm text-white/80 focus:border-brand-400 focus:outline-none">
                            <option value="tiktok">TikTok</option>
                            <option value="instagram">Instagram</option>
                            <option value="youtube">YouTube</option>
                        </select>
                    </div>
                    <button @click="generateCTA()" :disabled="generatingCta || !ctaTopic" class="w-full py-2.5 rounded-xl gradient-success text-white text-sm font-bold disabled:opacity-50">
                        <span x-text="generatingCta ? 'Gerando...' : 'Gerar CTAs'"></span>
                    </button>
                </div>
                <div x-show="ctaResults.length" x-transition class="mt-4 space-y-2">
                    <template x-for="(cta, idx) in ctaResults" :key="idx">
                        <div class="glass-light rounded-xl p-3 flex items-center justify-between group">
                            <p class="text-sm text-white/80" x-text="cta"></p>
                            <button @click="copyText(cta)" class="text-xs text-brand-300 opacity-0 group-hover:opacity-100 transition">Copiar</button>
                        </div>
                    </template>
                </div>
            </div>

            <!-- Readability & Retention -->
            <div class="space-y-4">
                <div class="glass-card rounded-2xl p-5">
                    <h3 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2"><i data-lucide="book-open" class="w-4 h-4 text-brand-400"></i> Analise de Legibilidade</h3>
                    <textarea x-model="analyzeText" rows="4" placeholder="Cole seu roteiro aqui para analise..."
                              class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none resize-none"></textarea>
                    <button @click="analyzeReadability(analyzeText)" :disabled="!analyzeText" class="mt-2 px-4 py-2 rounded-xl gradient-brand text-white text-xs font-bold disabled:opacity-50">Analisar</button>
                    <div x-show="readabilityResult" x-transition class="mt-3">
                        <div class="flex items-center gap-3 mb-2">
                            <span class="text-2xl font-bold" :style="'color:' + scoreColor(readabilityResult?.score || 0)" x-text="readabilityResult?.score + '/100'"></span>
                            <div class="text-xs text-white/40">
                                <p x-text="readabilityResult?.word_count + ' palavras | ' + readabilityResult?.sentence_count + ' frases'"></p>
                                <p x-text="'~' + readabilityResult?.duration_estimate_seconds + 's de narracao'"></p>
                            </div>
                        </div>
                        <template x-for="issue in (readabilityResult?.issues || [])">
                            <p class="text-[11px] text-white/50 flex items-center gap-1 mb-1"><i data-lucide="info" class="w-3 h-3 flex-shrink-0"></i> <span x-text="issue"></span></p>
                        </template>
                    </div>
                </div>
                <div class="glass-card rounded-2xl p-5">
                    <h3 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2"><i data-lucide="alert-triangle" class="w-4 h-4 text-accent-orange"></i> Riscos de Retencao</h3>
                    <button @click="checkRetention(analyzeText)" :disabled="!analyzeText" class="px-4 py-2 rounded-xl gradient-fire text-white text-xs font-bold disabled:opacity-50">Verificar Riscos</button>
                    <div x-show="retentionResult" x-transition class="mt-3">
                        <div class="flex items-center gap-2 mb-2">
                            <span class="text-lg font-bold" :style="'color:' + scoreColor(retentionResult?.retention_score || 0)" x-text="'Retencao: ' + retentionResult?.retention_score + '/100'"></span>
                        </div>
                        <template x-for="risk in (retentionResult?.risks || [])">
                            <div class="glass-light rounded-lg p-2 mb-1 flex items-start gap-2">
                                <span class="px-1.5 py-0.5 rounded text-[9px] font-bold" :class="risk.severity === 'high' ? 'bg-red-500/20 text-red-400' : 'bg-yellow-500/20 text-yellow-400'" x-text="risk.severity"></span>
                                <p class="text-[11px] text-white/60" x-text="'L' + risk.line + ': ' + risk.message"></p>
                            </div>
                        </template>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- TAB: MEUS SCRIPTS -->
    <div x-show="tab === 'scripts'" x-transition>
        <div x-show="scripts.length === 0 && !loadingScripts" class="text-center py-16">
            <i data-lucide="file-text" class="w-16 h-16 text-white/10 mx-auto mb-3"></i>
            <p class="text-sm text-white/30">Nenhum script salvo ainda</p>
            <p class="text-xs text-white/20 mt-1">Gere um script na aba "Gerar Script" e salve</p>
        </div>
        <div class="grid-cards">
            <template x-for="script in scripts" :key="script.id">
                <div class="glass-card rounded-xl p-4">
                    <div class="flex items-center justify-between mb-2">
                        <h4 class="text-sm font-bold text-white/80 truncate flex-1" x-text="script.title"></h4>
                        <div class="flex items-center gap-1 flex-shrink-0">
                            <span class="px-2 py-0.5 rounded text-[10px]" :class="'badge-' + script.platform" x-text="platformLabel(script.platform)"></span>
                            <span class="px-2 py-0.5 rounded text-[10px] glass-light text-white/40" x-text="script.style"></span>
                        </div>
                    </div>
                    <p class="text-xs text-white/50 line-clamp-3 mb-3" x-text="script.hook || script.full_script?.substring(0, 150)" style="display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;"></p>
                    <div class="flex items-center justify-between">
                        <span class="text-[10px] text-white/30" x-text="timeAgo(script.created_at)"></span>
                        <div class="flex gap-2">
                            <button @click="viewScript(script)" class="text-[10px] text-brand-300 hover:text-brand-200">Ver</button>
                            <button @click="deleteScript(script.id)" class="text-[10px] text-red-400 hover:text-red-300">Excluir</button>
                        </div>
                    </div>
                </div>
            </template>
        </div>

        <!-- Script Detail Modal -->
        <div x-show="viewingScript" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
             @click.self="viewingScript = null" @keydown.escape.window="viewingScript = null">
            <div class="glass rounded-2xl w-full max-w-2xl max-h-[85vh] overflow-y-auto p-5" @click.stop>
                <div class="flex items-center justify-between mb-4">
                    <h3 class="font-bold text-white/90" x-text="viewingScript?.title"></h3>
                    <button @click="viewingScript = null" class="p-1.5 rounded-lg hover:bg-white/10"><i data-lucide="x" class="w-5 h-5"></i></button>
                </div>
                <pre class="text-sm text-white/70 whitespace-pre-wrap leading-relaxed glass-light rounded-xl p-4" x-text="viewingScript?.full_script"></pre>
                <div class="flex flex-wrap gap-1 mt-3">
                    <template x-for="tag in (viewingScript?.hashtags || [])">
                        <span class="px-2 py-0.5 rounded text-[10px] glass-light text-brand-300" x-text="'#' + tag"></span>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- TAB: TTS NARRADOR -->
    <div x-show="tab === 'tts'" x-transition>
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-lg font-bold text-white/90 mb-4 flex items-center gap-2">
                    <div class="w-10 h-10 rounded-xl gradient-ocean flex items-center justify-center"><i data-lucide="volume-2" class="w-5 h-5"></i></div>
                    Narrador com IA (TTS)
                </h3>
                <div class="space-y-4">
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Voz</label>
                        <select x-model="ttsVoice" 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">
                            <template x-for="v in voices" :key="v.name">
                                <option :value="v.name" x-text="v.name + ' (' + v.gender + ')'"></option>
                            </template>
                        </select>
                    </div>
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Texto para narrar</label>
                        <textarea x-model="ttsText" rows="6" placeholder="Cole o texto do roteiro aqui..."
                                  class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none resize-none"></textarea>
                    </div>
                    <button @click="generateTTS()" :disabled="generatingTts || !ttsText" class="w-full py-3 rounded-xl gradient-ocean text-white font-bold text-sm disabled:opacity-50 flex items-center justify-center gap-2">
                        <i data-lucide="volume-2" class="w-4 h-4" :class="generatingTts && 'animate-pulse'"></i>
                        <span x-text="generatingTts ? 'Gerando audio...' : 'Gerar Audio'"></span>
                    </button>
                </div>
            </div>
            <div class="glass-card rounded-2xl p-5">
                <h3 class="text-sm font-bold text-white/80 mb-4">Player de Audio</h3>
                <div x-show="!ttsResult" class="text-center py-16">
                    <i data-lucide="headphones" class="w-16 h-16 text-white/10 mx-auto mb-3"></i>
                    <p class="text-sm text-white/30">Gere um audio para ouvir aqui</p>
                </div>
                <div x-show="ttsResult" x-transition>
                    <div class="glass-light rounded-xl p-4 mb-4">
                        <audio controls class="w-full" :src="ttsResult?.download_url" x-show="ttsResult?.download_url"></audio>
                    </div>
                    <div class="flex items-center justify-between">
                        <span class="text-xs text-white/40" x-text="'Voz: ' + (ttsResult?.voice || '')"></span>
                        <a :href="ttsResult?.download_url" download class="px-4 py-2 rounded-xl gradient-brand text-white text-xs font-bold" x-show="ttsResult?.download_url">Download MP3</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>
{% endblock %}

{% block scripts %}
<script>
function scriptGenius() {
    return {
        tab: 'generate',

        // Generate
        genTopic: '',
        genPlatform: 'tiktok',
        genStyle: 'tutorial',
        genDuration: 30,
        generating: false,
        generatedScript: null,
        templates: [],
        rewriting: false,
        readabilityResult: null,

        // Hooks
        hooks: [],
        loadingHooks: false,
        hookSearch: '',
        hookCategory: '',
        hookGenTopic: '',
        generatingHooks: false,
        aiHooks: [],

        // CTA
        ctaTopic: '',
        ctaGoal: 'seguir',
        ctaPlatform: 'tiktok',
        generatingCta: false,
        ctaResults: [],

        // Analyze
        analyzeText: '',
        retentionResult: null,

        // Scripts
        scripts: [],
        loadingScripts: false,
        viewingScript: null,

        // TTS
        ttsText: '',
        ttsVoice: 'pt-BR-AntonioNeural',
        voices: [],
        generatingTts: false,
        ttsResult: null,

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

        async loadTemplates() {
            try {
                const r = await fetch('/api/scripts/templates');
                const d = await r.json();
                this.templates = d.templates || [];
            } catch(e) {}
        },

        async generateScript() {
            if (!this.genTopic || this.generating) return;
            this.generating = true;
            this.readabilityResult = null;
            showToast('Gerando roteiro com IA... aguarde ~30s', 'info');
            try {
                const r = await fetch('/api/scripts/generate', {
                    method: 'POST', headers: {'Content-Type':'application/json'},
                    body: JSON.stringify({
                        topic: this.genTopic, platform: this.genPlatform,
                        style: this.genStyle, duration: this.genDuration,
                    })
                });
                this.generatedScript = await r.json();
                showToast('Roteiro gerado!', 'success');
            } catch(e) { showToast('Erro ao gerar roteiro', 'error'); }
            this.generating = false;
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        async saveGeneratedScript() {
            if (!this.generatedScript) return;
            try {
                await fetch('/api/scripts', {
                    method: 'POST', headers: {'Content-Type':'application/json'},
                    body: JSON.stringify({
                        title: this.genTopic, platform: this.genPlatform, style: this.genStyle,
                        hook: this.generatedScript.hook, body: this.generatedScript.body,
                        cta: this.generatedScript.cta, full_script: this.generatedScript.full_script,
                        hashtags: this.generatedScript.hashtags, duration_estimate: this.genDuration,
                    })
                });
                showToast('Script salvo!', 'success');
            } catch(e) { showToast('Erro ao salvar', 'error'); }
        },

        async rewriteViral() {
            if (!this.generatedScript?.full_script || this.rewriting) return;
            this.rewriting = true;
            try {
                const r = await fetch('/api/scripts/rewrite-viral', {
                    method: 'POST', headers: {'Content-Type':'application/json'},
                    body: JSON.stringify({ text: this.generatedScript.full_script })
                });
                const d = await r.json();
                if (d.viral_version) {
                    this.generatedScript.full_script = d.viral_version;
                    showToast('Reescrito para viral!', 'success');
                }
            } catch(e) { showToast('Erro', 'error'); }
            this.rewriting = false;
        },

        async analyzeReadability(text) {
            if (!text) return;
            try {
                const r = await fetch('/api/scripts/readability', {
                    method: 'POST', headers: {'Content-Type':'application/json'},
                    body: JSON.stringify({ text })
                });
                this.readabilityResult = await r.json();
            } catch(e) {}
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        async checkRetention(text) {
            if (!text) return;
            try {
                const r = await fetch('/api/scripts/retention-risks', {
                    method: 'POST', headers: {'Content-Type':'application/json'},
                    body: JSON.stringify({ text })
                });
                this.retentionResult = await r.json();
            } catch(e) {}
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        // Hooks
        async loadHooks() {
            if (this.hooks.length > 0) return;
            this.loadingHooks = true;
            try {
                const r = await fetch('/api/hooks?limit=50');
                const d = await r.json();
                this.hooks = d.hooks || [];
            } catch(e) {}
            this.loadingHooks = false;
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        async searchHooks() {
            try {
                const params = new URLSearchParams({limit: '50'});
                if (this.hookSearch) params.set('query', this.hookSearch);
                if (this.hookCategory) params.set('category', this.hookCategory);
                const r = await fetch('/api/hooks?' + params);
                const d = await r.json();
                this.hooks = d.hooks || [];
            } catch(e) {}
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        async seedHooks() {
            showToast('Populando banco de hooks...', 'info');
            try {
                const r = await fetch('/api/hooks/seed', { method: 'POST' });
                const d = await r.json();
                showToast(`Hooks carregados: ${d.total || 0} total`, 'success');
                await this.searchHooks();
            } catch(e) { showToast('Erro', 'error'); }
        },

        async generateAiHooks() {
            if (!this.hookGenTopic || this.generatingHooks) return;
            this.generatingHooks = true;
            try {
                const r = await fetch('/api/hooks/generate', {
                    method: 'POST', headers: {'Content-Type':'application/json'},
                    body: JSON.stringify({ topic: this.hookGenTopic, category: this.hookCategory || 'curiosidade' })
                });
                const d = await r.json();
                this.aiHooks = d.hooks || [];
            } catch(e) { showToast('Erro', 'error'); }
            this.generatingHooks = false;
        },

        async rateHook(id, rating) {
            try { await fetch(`/api/hooks/${id}/rate?rating=${rating}`, { method: 'POST' }); showToast('Avaliado!', 'success'); } catch(e) {}
        },

        // CTA
        async generateCTA() {
            if (!this.ctaTopic || this.generatingCta) return;
            this.generatingCta = true;
            try {
                const r = await fetch('/api/scripts/cta', {
                    method: 'POST', headers: {'Content-Type':'application/json'},
                    body: JSON.stringify({ topic: this.ctaTopic, goal: this.ctaGoal, platform: this.ctaPlatform })
                });
                const d = await r.json();
                this.ctaResults = d.ctas || [];
            } catch(e) { showToast('Erro', 'error'); }
            this.generatingCta = false;
        },

        // Scripts CRUD
        async loadScripts() {
            this.loadingScripts = true;
            try {
                const r = await fetch('/api/scripts');
                const d = await r.json();
                this.scripts = d.scripts || [];
            } catch(e) {}
            this.loadingScripts = false;
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

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

        async deleteScript(id) {
            if (!confirm('Excluir este script?')) return;
            try {
                await fetch(`/api/scripts/${id}`, { method: 'DELETE' });
                this.scripts = this.scripts.filter(s => s.id !== id);
                showToast('Script excluido', 'success');
            } catch(e) { showToast('Erro', 'error'); }
        },

        // TTS
        async loadVoices() {
            if (this.voices.length > 0) return;
            try {
                const r = await fetch('/api/tts/voices');
                const d = await r.json();
                this.voices = d.voices || [];
                if (this.voices.length > 0) this.ttsVoice = this.voices[0].name;
            } catch(e) {
                this.voices = [
                    { name: 'pt-BR-AntonioNeural', gender: 'Male', locale: 'pt-BR' },
                    { name: 'pt-BR-FranciscaNeural', gender: 'Female', locale: 'pt-BR' },
                ];
            }
        },

        async generateTTS() {
            if (!this.ttsText || this.generatingTts) return;
            this.generatingTts = true;
            showToast('Gerando audio...', 'info');
            try {
                const r = await fetch('/api/tts/generate', {
                    method: 'POST', headers: {'Content-Type':'application/json'},
                    body: JSON.stringify({ text: this.ttsText, voice: this.ttsVoice })
                });
                const d = await r.json();
                if (d.path) {
                    const filename = d.path.split('/').pop();
                    d.download_url = '/api/tts/download/' + filename;
                }
                this.ttsResult = d;
                if (d.error) showToast('Erro: ' + d.error, 'error');
                else showToast('Audio gerado!', 'success');
            } catch(e) { showToast('Erro ao gerar audio', 'error'); }
            this.generatingTts = false;
        },

        copyText(text) {
            navigator.clipboard.writeText(text);
            showToast('Copiado!', 'success');
        },
    };
}
</script>
{% endblock %}
