{% extends "base.html" %}
{% block title %}CreatorCRM - Viral Social Pro{% endblock %}
{% block nav_crm %}active{% endblock %}
{% block page_title %}CreatorCRM{% endblock %}
{% block page_subtitle %}Gestao Inteligente de Influenciadores{% endblock %}

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

    <!-- TABS -->
    <div class="flex gap-2 mb-6 overflow-x-auto pb-1 animate-fade-up">
        <button class="tab-btn" :class="activeTab === 'discover' && 'active'" @click="activeTab = 'discover'">
            <i data-lucide="search" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Descobrir
        </button>
        <button class="tab-btn" :class="activeTab === 'contacts' && 'active'" @click="activeTab = 'contacts'; loadContacts()">
            <i data-lucide="contact" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Contatos
        </button>
        <button class="tab-btn" :class="activeTab === 'campaigns' && 'active'" @click="activeTab = 'campaigns'; loadCampaigns()">
            <i data-lucide="megaphone" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Campanhas
        </button>
        <button class="tab-btn" :class="activeTab === 'outreach' && 'active'" @click="activeTab = 'outreach'">
            <i data-lucide="mail" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Outreach IA
        </button>
        <button class="tab-btn" :class="activeTab === 'revenue' && 'active'" @click="activeTab = 'revenue'; loadRevenue()">
            <i data-lucide="dollar-sign" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Revenue
        </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> Stats
        </button>
    </div>

    <!-- ================================================================ -->
    <!-- TAB: DISCOVER                                                     -->
    <!-- ================================================================ -->
    <div x-show="activeTab === 'discover'" x-transition>

        <!-- Search Form -->
        <div class="glass-card rounded-2xl p-5 mb-6 animate-fade-up">
            <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 flex-shrink-0">
                    <i data-lucide="radar" class="w-5 h-5"></i>
                </div>
                Descobrir Influenciadores
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
                <div>
                    <label class="text-xs text-white/50 mb-1 block">Nicho</label>
                    <input x-model="searchNiche" type="text" placeholder="Ex: fitness, beleza, tech..."
                           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 block">Plataforma</label>
                    <select x-model="searchPlatform"
                            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="">Todas</option>
                        <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">Min Seguidores: <span class="text-brand-300" x-text="formatNumber(minFollowers)"></span></label>
                    <input x-model.number="minFollowers" type="range" min="0" max="10000000" step="10000"
                           class="w-full accent-brand-500 h-2 bg-dark-600 rounded-lg appearance-none cursor-pointer">
                </div>
                <div>
                    <label class="text-xs text-white/50 mb-1 block">Max Seguidores: <span class="text-brand-300" x-text="maxFollowers === 0 ? 'Sem limite' : formatNumber(maxFollowers)"></span></label>
                    <input x-model.number="maxFollowers" type="range" min="0" max="10000000" step="10000"
                           class="w-full accent-brand-500 h-2 bg-dark-600 rounded-lg appearance-none cursor-pointer">
                </div>
            </div>
            <button @click="discoverInfluencers()" :disabled="discoverLoading"
                    class="px-6 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition flex items-center gap-2 disabled:opacity-50">
                <div x-show="discoverLoading" class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                <i x-show="!discoverLoading" data-lucide="search" class="w-4 h-4"></i>
                <span x-text="discoverLoading ? 'Buscando...' : 'Descobrir'"></span>
            </button>
        </div>

        <!-- Loading Skeleton -->
        <template x-if="discoverLoading">
            <div class="grid-cards">
                <template x-for="i in 6">
                    <div class="skeleton h-64 rounded-2xl"></div>
                </template>
            </div>
        </template>

        <!-- Discover Results -->
        <template x-if="!discoverLoading && discoverResults.length > 0">
            <div class="grid-cards">
                <template x-for="(creator, idx) in discoverResults" :key="idx">
                    <div class="glass-card rounded-2xl overflow-hidden animate-fade-up" :style="'animation-delay:' + (idx * 30) + 'ms'">
                        <!-- Header -->
                        <div class="p-4 flex items-center gap-3 border-b border-white/5">
                            <div class="w-12 h-12 rounded-full flex items-center justify-center text-white font-bold text-lg flex-shrink-0"
                                 :class="creator.platform === 'youtube' ? 'bg-red-500' : creator.platform === 'instagram' ? 'bg-gradient-to-br from-purple-500 to-pink-500' : 'bg-white/10'">
                                <span x-text="(creator.username || creator.name || '?')[0].toUpperCase()"></span>
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="font-bold text-white/90 truncate text-sm" x-text="'@' + (creator.username || creator.name)"></p>
                                <div class="flex items-center gap-2 mt-0.5">
                                    <span class="px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wide"
                                          :class="creator.platform === 'youtube' ? 'badge-youtube' : creator.platform === 'instagram' ? 'badge-instagram' : 'badge-tiktok'"
                                          x-text="creator.platform || 'tiktok'"></span>
                                    <span x-show="creator.niche" class="text-[10px] text-white/30" x-text="creator.niche"></span>
                                </div>
                            </div>
                        </div>

                        <!-- Stats -->
                        <div class="p-4 grid grid-cols-3 gap-2 text-center">
                            <div class="glass-light rounded-lg py-2">
                                <p class="text-[10px] text-white/30 uppercase tracking-wide">Seguidores</p>
                                <p class="text-sm font-bold text-white/90" x-text="formatNumber(creator.followers || 0)"></p>
                            </div>
                            <div class="glass-light rounded-lg py-2">
                                <p class="text-[10px] text-white/30 uppercase tracking-wide">Engage</p>
                                <p class="text-sm font-bold text-accent-green" x-text="(creator.engagement_rate || 0).toFixed(1) + '%'"></p>
                            </div>
                            <div class="glass-light rounded-lg py-2">
                                <p class="text-[10px] text-white/30 uppercase tracking-wide">Score</p>
                                <p class="text-sm font-bold text-brand-300" x-text="creator.influence_score || creator.score || '--'"></p>
                            </div>
                        </div>

                        <!-- Actions -->
                        <div class="p-4 pt-0 flex gap-2">
                            <button @click="addToCRM(creator)"
                                    class="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 text-xs font-medium rounded-xl gradient-brand text-white hover:opacity-90 transition">
                                <i data-lucide="user-plus" class="w-3.5 h-3.5"></i> Adicionar ao CRM
                            </button>
                            <button @click="getMediaKit(creator)"
                                    class="flex items-center justify-center gap-1.5 px-3 py-2 text-xs font-medium rounded-xl glass-light text-white/60 hover:text-white/80 transition"
                                    title="Media Kit">
                                <i data-lucide="file-badge" class="w-3.5 h-3.5"></i>
                            </button>
                            <button @click="detectFake(creator)"
                                    class="flex items-center justify-center gap-1.5 px-3 py-2 text-xs font-medium rounded-xl glass-light text-white/60 hover:text-white/80 transition"
                                    title="Deteccao de Fakes">
                                <i data-lucide="shield-alert" class="w-3.5 h-3.5"></i>
                            </button>
                        </div>
                    </div>
                </template>
            </div>
        </template>

        <!-- Empty State -->
        <div x-show="!discoverLoading && discoverResults.length === 0" class="flex flex-col items-center justify-center py-16 text-center">
            <div class="w-20 h-20 rounded-2xl glass-light flex items-center justify-center mb-5">
                <i data-lucide="search" class="w-10 h-10 text-white/20"></i>
            </div>
            <h3 class="text-lg font-bold text-white/60 mb-2">Descubra influenciadores</h3>
            <p class="text-sm text-white/30 max-w-md">Preencha os filtros acima e clique em Descobrir para encontrar criadores no seu nicho.</p>
        </div>

        <!-- Media Kit Modal -->
        <div x-show="showMediaKit" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
             @click.self="showMediaKit = false" @keydown.escape.window="showMediaKit = false"
             x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100">
            <div class="glass rounded-2xl w-full max-w-2xl max-h-[80vh] overflow-y-auto" @click.stop>
                <div class="p-5 border-b border-white/5 flex items-center justify-between sticky top-0 glass z-10 rounded-t-2xl">
                    <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                        <i data-lucide="file-badge" class="w-5 h-5 text-brand-400"></i> Media Kit IA
                    </h2>
                    <button @click="showMediaKit = false" class="p-1.5 rounded-lg hover:bg-white/10"><i data-lucide="x" class="w-5 h-5"></i></button>
                </div>
                <div class="p-5">
                    <template x-if="mediaKitLoading">
                        <div class="space-y-3">
                            <div class="skeleton h-6 w-3/4 rounded-lg"></div>
                            <div class="skeleton h-4 w-full rounded-lg"></div>
                            <div class="skeleton h-4 w-5/6 rounded-lg"></div>
                            <div class="skeleton h-32 rounded-xl mt-4"></div>
                        </div>
                    </template>
                    <template x-if="!mediaKitLoading && mediaKitData">
                        <div class="space-y-4">
                            <div class="glass-light rounded-xl p-4">
                                <h4 class="text-sm font-bold text-white/80 mb-2">Resumo</h4>
                                <p class="text-sm text-white/60 leading-relaxed" x-text="mediaKitData.summary || mediaKitData.bio || '--'"></p>
                            </div>
                            <div class="grid grid-cols-2 gap-3">
                                <div class="glass-light rounded-xl p-3 text-center">
                                    <p class="text-xs text-white/40">Seguidores</p>
                                    <p class="text-lg font-bold text-white" x-text="formatNumber(mediaKitData.followers || 0)"></p>
                                </div>
                                <div class="glass-light rounded-xl p-3 text-center">
                                    <p class="text-xs text-white/40">Engagement</p>
                                    <p class="text-lg font-bold text-accent-green" x-text="(mediaKitData.engagement_rate || 0).toFixed(2) + '%'"></p>
                                </div>
                                <div class="glass-light rounded-xl p-3 text-center">
                                    <p class="text-xs text-white/40">Media Views</p>
                                    <p class="text-lg font-bold text-accent-cyan" x-text="formatNumber(mediaKitData.avg_views || 0)"></p>
                                </div>
                                <div class="glass-light rounded-xl p-3 text-center">
                                    <p class="text-xs text-white/40">Nicho</p>
                                    <p class="text-lg font-bold text-brand-300" x-text="mediaKitData.niche || '--'"></p>
                                </div>
                            </div>
                            <template x-if="mediaKitData.top_content && mediaKitData.top_content.length">
                                <div class="glass-light rounded-xl p-4">
                                    <h4 class="text-sm font-bold text-white/80 mb-2">Top Conteudos</h4>
                                    <div class="space-y-2">
                                        <template x-for="(item, i) in mediaKitData.top_content" :key="i">
                                            <div class="flex items-center gap-2 text-sm text-white/60">
                                                <span class="text-brand-300 font-bold" x-text="(i+1) + '.'"></span>
                                                <span x-text="item.title || item"></span>
                                            </div>
                                        </template>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </template>
                </div>
            </div>
        </div>

        <!-- Fake Detection Modal -->
        <div x-show="showFakeDetection" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
             @click.self="showFakeDetection = false" @keydown.escape.window="showFakeDetection = false"
             x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100">
            <div class="glass rounded-2xl w-full max-w-lg max-h-[80vh] overflow-y-auto" @click.stop>
                <div class="p-5 border-b border-white/5 flex items-center justify-between sticky top-0 glass z-10 rounded-t-2xl">
                    <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                        <i data-lucide="shield-alert" class="w-5 h-5 text-accent-orange"></i> Deteccao de Fakes
                    </h2>
                    <button @click="showFakeDetection = false" class="p-1.5 rounded-lg hover:bg-white/10"><i data-lucide="x" class="w-5 h-5"></i></button>
                </div>
                <div class="p-5">
                    <template x-if="fakeDetectionLoading">
                        <div class="flex flex-col items-center py-8">
                            <div class="w-8 h-8 border-2 border-brand-400 border-t-transparent rounded-full animate-spin mb-3"></div>
                            <p class="text-sm text-white/40">Analisando perfil...</p>
                        </div>
                    </template>
                    <template x-if="!fakeDetectionLoading && fakeDetectionData">
                        <div class="space-y-4">
                            <div class="flex items-center justify-center">
                                <div class="score-ring text-white"
                                     :style="'--score:' + (fakeDetectionData.authenticity_score || 0) + '; --ring-color:' + scoreColor(fakeDetectionData.authenticity_score || 0)">
                                    <span x-text="(fakeDetectionData.authenticity_score || 0)"></span>
                                </div>
                                <div class="ml-4">
                                    <p class="text-sm font-bold text-white/80">Score de Autenticidade</p>
                                    <p class="text-xs text-white/40" x-text="(fakeDetectionData.authenticity_score || 0) >= 70 ? 'Perfil parece autentico' : 'Sinais de seguidores falsos'"></p>
                                </div>
                            </div>
                            <div class="grid grid-cols-2 gap-3">
                                <div class="glass-light rounded-xl p-3 text-center">
                                    <p class="text-xs text-white/40">Seguidores Reais</p>
                                    <p class="text-lg font-bold text-accent-green" x-text="(fakeDetectionData.real_followers_pct || 0) + '%'"></p>
                                </div>
                                <div class="glass-light rounded-xl p-3 text-center">
                                    <p class="text-xs text-white/40">Seguidores Fakes</p>
                                    <p class="text-lg font-bold text-accent-red" x-text="(fakeDetectionData.fake_followers_pct || 0) + '%'"></p>
                                </div>
                            </div>
                            <template x-if="fakeDetectionData.flags && fakeDetectionData.flags.length">
                                <div class="glass-light rounded-xl p-4">
                                    <h4 class="text-sm font-bold text-white/80 mb-2">Alertas</h4>
                                    <div class="space-y-1.5">
                                        <template x-for="(flag, i) in fakeDetectionData.flags" :key="i">
                                            <div class="flex items-center gap-2 text-xs text-accent-orange">
                                                <i data-lucide="alert-triangle" class="w-3.5 h-3.5 flex-shrink-0"></i>
                                                <span x-text="flag"></span>
                                            </div>
                                        </template>
                                    </div>
                                </div>
                            </template>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- ================================================================ -->
    <!-- TAB: CONTACTS                                                     -->
    <!-- ================================================================ -->
    <div x-show="activeTab === 'contacts'" x-transition>

        <!-- Filters + Add -->
        <div class="glass-card rounded-2xl p-5 mb-6 animate-fade-up">
            <div class="flex flex-col md:flex-row md:items-end gap-4">
                <div class="flex-1">
                    <h3 class="text-lg font-bold text-white/90 mb-3 flex items-center gap-2">
                        <div class="w-10 h-10 rounded-xl gradient-ocean flex items-center justify-center flex-shrink-0">
                            <i data-lucide="contact" class="w-5 h-5"></i>
                        </div>
                        Contatos CRM
                    </h3>
                    <div class="flex flex-wrap gap-3">
                        <select x-model="contactFilter" @change="loadContacts()"
                                class="bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none transition min-w-[150px]">
                            <option value="">Todos Status</option>
                            <option value="lead">Lead</option>
                            <option value="contacted">Contatado</option>
                            <option value="negotiating">Negociando</option>
                            <option value="active">Ativo</option>
                            <option value="inactive">Inativo</option>
                        </select>
                        <input x-model="contactTag" @keyup.enter="loadContacts()" type="text" placeholder="Filtrar por tag..."
                               class="bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none transition min-w-[150px]">
                        <button @click="loadContacts()" class="px-4 py-2.5 rounded-xl glass-light text-white/60 hover:text-white text-sm font-medium transition flex items-center gap-2">
                            <i data-lucide="refresh-cw" class="w-3.5 h-3.5"></i> Filtrar
                        </button>
                    </div>
                </div>
                <button @click="showAddContact = true"
                        class="px-5 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition flex items-center gap-2">
                    <i data-lucide="user-plus" class="w-4 h-4"></i> Novo Contato
                </button>
            </div>
        </div>

        <!-- Loading -->
        <template x-if="contactsLoading">
            <div class="grid-cards">
                <template x-for="i in 4">
                    <div class="skeleton h-48 rounded-2xl"></div>
                </template>
            </div>
        </template>

        <!-- Contacts Grid -->
        <template x-if="!contactsLoading && contacts.length > 0">
            <div class="grid-cards">
                <template x-for="(contact, idx) in contacts" :key="contact.id || idx">
                    <div class="glass-card rounded-2xl overflow-hidden animate-fade-up" :style="'animation-delay:' + (idx * 30) + 'ms'">
                        <!-- Header -->
                        <div class="p-4 flex items-center gap-3 border-b border-white/5">
                            <div class="w-10 h-10 rounded-full gradient-ocean flex items-center justify-center text-white font-bold flex-shrink-0">
                                <span x-text="(contact.name || '?')[0].toUpperCase()"></span>
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="font-bold text-white/90 truncate text-sm" x-text="contact.name"></p>
                                <p class="text-xs text-white/40 truncate" x-text="contact.email || '--'"></p>
                            </div>
                            <span class="px-2 py-0.5 rounded-lg text-[10px] font-semibold uppercase tracking-wide"
                                  :class="{
                                      'bg-blue-500/15 text-blue-400 border border-blue-500/20': contact.status === 'lead',
                                      'bg-yellow-500/15 text-yellow-400 border border-yellow-500/20': contact.status === 'contacted',
                                      'bg-orange-500/15 text-orange-400 border border-orange-500/20': contact.status === 'negotiating',
                                      'bg-green-500/15 text-green-400 border border-green-500/20': contact.status === 'active',
                                      'bg-gray-500/15 text-gray-400 border border-gray-500/20': contact.status === 'inactive'
                                  }" x-text="contact.status || 'lead'"></span>
                        </div>

                        <!-- Tags -->
                        <div class="px-4 pt-3 flex flex-wrap gap-1.5" x-show="contact.tags && contact.tags.length">
                            <template x-for="(tag, ti) in (contact.tags || []).slice(0, 5)" :key="ti">
                                <span class="px-2 py-0.5 rounded-lg text-[10px] font-medium glass-light text-brand-300" x-text="tag"></span>
                            </template>
                        </div>

                        <!-- Notes Preview -->
                        <div class="px-4 pt-2" x-show="contact.notes">
                            <p class="text-xs text-white/30 line-clamp-2" x-text="contact.notes"></p>
                        </div>

                        <!-- Actions -->
                        <div class="p-4 flex gap-2">
                            <button @click="selectContact(contact)"
                                    class="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 text-xs font-medium rounded-xl gradient-brand text-white hover:opacity-90 transition">
                                <i data-lucide="eye" class="w-3.5 h-3.5"></i> Detalhes
                            </button>
                            <button @click="editContact(contact)"
                                    class="flex items-center justify-center gap-1.5 px-3 py-2 text-xs font-medium rounded-xl glass-light text-white/60 hover:text-white/80 transition">
                                <i data-lucide="pencil" class="w-3.5 h-3.5"></i>
                            </button>
                            <button @click="deleteContact(contact.id)"
                                    class="flex items-center justify-center gap-1.5 px-3 py-2 text-xs font-medium rounded-xl glass-light text-red-400/60 hover:text-red-400 transition">
                                <i data-lucide="trash-2" class="w-3.5 h-3.5"></i>
                            </button>
                        </div>
                    </div>
                </template>
            </div>
        </template>

        <!-- Empty -->
        <div x-show="!contactsLoading && contacts.length === 0" class="flex flex-col items-center justify-center py-16 text-center">
            <div class="w-20 h-20 rounded-2xl glass-light flex items-center justify-center mb-5">
                <i data-lucide="contact" class="w-10 h-10 text-white/20"></i>
            </div>
            <h3 class="text-lg font-bold text-white/60 mb-2">Nenhum contato encontrado</h3>
            <p class="text-sm text-white/30 max-w-md">Adicione influenciadores ao CRM pela aba Descobrir ou clique em Novo Contato.</p>
        </div>

        <!-- Contact Detail Modal -->
        <div x-show="selectedContact" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
             @click.self="selectedContact = null" @keydown.escape.window="selectedContact = null"
             x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100">
            <div class="glass rounded-2xl w-full max-w-2xl max-h-[80vh] overflow-y-auto" @click.stop>
                <div class="p-5 border-b border-white/5 flex items-center justify-between sticky top-0 glass z-10 rounded-t-2xl">
                    <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                        <i data-lucide="user" class="w-5 h-5 text-brand-400"></i>
                        <span x-text="selectedContact?.name"></span>
                    </h2>
                    <button @click="selectedContact = null" class="p-1.5 rounded-lg hover:bg-white/10"><i data-lucide="x" class="w-5 h-5"></i></button>
                </div>
                <div class="p-5 space-y-4">
                    <!-- Contact Info -->
                    <div class="grid grid-cols-2 gap-3">
                        <div class="glass-light rounded-xl p-3">
                            <p class="text-xs text-white/40 mb-1">Email</p>
                            <p class="text-sm text-white/80" x-text="selectedContact?.email || '--'"></p>
                        </div>
                        <div class="glass-light rounded-xl p-3">
                            <p class="text-xs text-white/40 mb-1">Status</p>
                            <p class="text-sm font-semibold capitalize" :class="{
                                'text-blue-400': selectedContact?.status === 'lead',
                                'text-yellow-400': selectedContact?.status === 'contacted',
                                'text-orange-400': selectedContact?.status === 'negotiating',
                                'text-green-400': selectedContact?.status === 'active',
                                'text-gray-400': selectedContact?.status === 'inactive'
                            }" x-text="selectedContact?.status || 'lead'"></p>
                        </div>
                    </div>

                    <!-- Tags -->
                    <div x-show="selectedContact?.tags && selectedContact.tags.length" class="flex flex-wrap gap-1.5">
                        <template x-for="(tag, i) in (selectedContact?.tags || [])" :key="i">
                            <span class="px-2.5 py-1 rounded-lg text-xs font-medium glass-light text-brand-300" x-text="tag"></span>
                        </template>
                    </div>

                    <!-- Notes -->
                    <div x-show="selectedContact?.notes" class="glass-light rounded-xl p-4">
                        <h4 class="text-sm font-bold text-white/80 mb-2">Notas</h4>
                        <p class="text-sm text-white/60 leading-relaxed whitespace-pre-wrap" x-text="selectedContact?.notes"></p>
                    </div>

                    <!-- Interactions Timeline -->
                    <div>
                        <h4 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2">
                            <i data-lucide="message-circle" class="w-4 h-4 text-brand-400"></i> Interacoes
                        </h4>
                        <div x-show="selectedContact?.interactions && selectedContact.interactions.length" class="space-y-2 max-h-60 overflow-y-auto mb-3">
                            <template x-for="(inter, i) in (selectedContact?.interactions || [])" :key="i">
                                <div class="glass-light rounded-xl p-3 flex items-start gap-3">
                                    <div class="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0"
                                         :class="inter.type === 'email' ? 'bg-blue-500/15' : inter.type === 'call' ? 'bg-green-500/15' : inter.type === 'meeting' ? 'bg-purple-500/15' : 'bg-white/5'">
                                        <i :data-lucide="inter.type === 'email' ? 'mail' : inter.type === 'call' ? 'phone' : inter.type === 'meeting' ? 'video' : 'message-circle'" class="w-4 h-4"></i>
                                    </div>
                                    <div class="flex-1 min-w-0">
                                        <p class="text-xs font-semibold text-white/70 capitalize" x-text="inter.type"></p>
                                        <p class="text-xs text-white/50 mt-0.5" x-text="inter.content"></p>
                                        <p class="text-[10px] text-white/25 mt-1" x-text="inter.created_at ? timeAgo(inter.created_at) : ''"></p>
                                    </div>
                                </div>
                            </template>
                        </div>
                        <p x-show="!selectedContact?.interactions || selectedContact.interactions.length === 0" class="text-xs text-white/30 mb-3">Nenhuma interacao registrada.</p>

                        <!-- Add Interaction -->
                        <div class="flex gap-2">
                            <select x-model="newInteractionType" class="bg-dark-700 border border-white/10 rounded-xl px-3 py-2 text-xs text-white/80 focus:border-brand-400 focus:outline-none">
                                <option value="note">Nota</option>
                                <option value="email">Email</option>
                                <option value="call">Ligacao</option>
                                <option value="meeting">Reuniao</option>
                            </select>
                            <input x-model="newInteraction" type="text" placeholder="Adicionar interacao..."
                                   @keyup.enter="addInteraction()"
                                   class="flex-1 bg-dark-700 border border-white/10 rounded-xl px-4 py-2 text-xs text-white/80 focus:border-brand-400 focus:outline-none transition">
                            <button @click="addInteraction()"
                                    class="px-4 py-2 rounded-xl gradient-brand text-white text-xs font-semibold hover:opacity-90 transition">
                                <i data-lucide="plus" class="w-3.5 h-3.5"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Add Contact Modal -->
        <div x-show="showAddContact" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
             @click.self="showAddContact = false" @keydown.escape.window="showAddContact = false"
             x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100">
            <div class="glass rounded-2xl w-full max-w-lg" @click.stop>
                <div class="p-5 border-b border-white/5 flex items-center justify-between">
                    <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                        <i data-lucide="user-plus" class="w-5 h-5 text-brand-400"></i> Novo Contato
                    </h2>
                    <button @click="showAddContact = false" class="p-1.5 rounded-lg hover:bg-white/10"><i data-lucide="x" class="w-5 h-5"></i></button>
                </div>
                <div class="p-5 space-y-4">
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Nome *</label>
                        <input x-model="newContactName" type="text" placeholder="Nome do influenciador"
                               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 block">Email</label>
                        <input x-model="newContactEmail" type="email" placeholder="email@exemplo.com"
                               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 block">Tags (separadas por virgula)</label>
                        <input x-model="newContactTags" type="text" placeholder="fitness, lifestyle, micro"
                               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 block">Notas</label>
                        <textarea x-model="newContactNotes" placeholder="Observacoes sobre o criador..."
                                  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 h-24 resize-none"></textarea>
                    </div>
                    <button @click="createContact()" :disabled="!newContactName"
                            class="w-full px-6 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-50">
                        Adicionar Contato
                    </button>
                </div>
            </div>
        </div>

        <!-- Edit Contact Modal -->
        <div x-show="showEditContact" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
             @click.self="showEditContact = false" @keydown.escape.window="showEditContact = false"
             x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100">
            <div class="glass rounded-2xl w-full max-w-lg" @click.stop>
                <div class="p-5 border-b border-white/5 flex items-center justify-between">
                    <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                        <i data-lucide="pencil" class="w-5 h-5 text-brand-400"></i> Editar Contato
                    </h2>
                    <button @click="showEditContact = false" class="p-1.5 rounded-lg hover:bg-white/10"><i data-lucide="x" class="w-5 h-5"></i></button>
                </div>
                <div class="p-5 space-y-4">
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Nome *</label>
                        <input x-model="editContactData.name" type="text"
                               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 block">Email</label>
                        <input x-model="editContactData.email" type="email"
                               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 block">Status</label>
                        <select x-model="editContactData.status"
                                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="lead">Lead</option>
                            <option value="contacted">Contatado</option>
                            <option value="negotiating">Negociando</option>
                            <option value="active">Ativo</option>
                            <option value="inactive">Inativo</option>
                        </select>
                    </div>
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Tags (separadas por virgula)</label>
                        <input x-model="editContactData.tags_str" type="text"
                               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 block">Notas</label>
                        <textarea x-model="editContactData.notes"
                                  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 h-24 resize-none"></textarea>
                    </div>
                    <button @click="updateContact()" :disabled="!editContactData.name"
                            class="w-full px-6 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-50">
                        Salvar Alteracoes
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- ================================================================ -->
    <!-- TAB: CAMPAIGNS                                                    -->
    <!-- ================================================================ -->
    <div x-show="activeTab === 'campaigns'" x-transition>

        <!-- Create Campaign -->
        <div class="glass-card rounded-2xl p-5 mb-6 animate-fade-up">
            <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 flex-shrink-0">
                    <i data-lucide="megaphone" class="w-5 h-5"></i>
                </div>
                Nova Campanha
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
                <div>
                    <label class="text-xs text-white/50 mb-1 block">Nome *</label>
                    <input x-model="newCampaignName" type="text" placeholder="Nome da campanha"
                           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 block">Tipo</label>
                    <select x-model="newCampaignType"
                            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="review">Review</option>
                        <option value="unboxing">Unboxing</option>
                        <option value="affiliate">Afiliado</option>
                        <option value="ambassador">Embaixador</option>
                    </select>
                </div>
                <div>
                    <label class="text-xs text-white/50 mb-1 block">Orcamento (R$)</label>
                    <input x-model.number="newCampaignBudget" type="number" placeholder="5000" min="0"
                           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 block">Metas</label>
                    <input x-model="newCampaignGoals" type="text" placeholder="Ex: 100k views, 5% engage"
                           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>
            <!-- Creator IDs -->
            <div class="mb-4">
                <label class="text-xs text-white/50 mb-1 block">IDs dos Criadores (separados por virgula)</label>
                <input x-model="newCampaignCreatorIds" type="text" placeholder="1, 2, 3"
                       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>
            <button @click="createCampaign()" :disabled="!newCampaignName || campaignsLoading"
                    class="px-6 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition flex items-center gap-2 disabled:opacity-50">
                <i data-lucide="plus-circle" class="w-4 h-4"></i> Criar Campanha
            </button>
        </div>

        <!-- Campaign Filter -->
        <div class="flex gap-3 mb-4">
            <select x-model="campaignStatusFilter" @change="loadCampaigns()"
                    class="bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none transition">
                <option value="">Todos Status</option>
                <option value="draft">Rascunho</option>
                <option value="active">Ativa</option>
                <option value="paused">Pausada</option>
                <option value="completed">Concluida</option>
            </select>
        </div>

        <!-- Loading -->
        <template x-if="campaignsLoading">
            <div class="space-y-4">
                <template x-for="i in 3">
                    <div class="skeleton h-32 rounded-2xl"></div>
                </template>
            </div>
        </template>

        <!-- Campaigns List -->
        <template x-if="!campaignsLoading && campaigns.length > 0">
            <div class="space-y-4">
                <template x-for="(campaign, idx) in campaigns" :key="campaign.id || idx">
                    <div class="glass-card rounded-2xl p-5 animate-fade-up" :style="'animation-delay:' + (idx * 30) + 'ms'">
                        <div class="flex flex-col md:flex-row md:items-center justify-between gap-4">
                            <div class="flex items-center gap-4">
                                <div class="w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0"
                                     :class="campaign.campaign_type === 'review' ? 'gradient-brand' : campaign.campaign_type === 'unboxing' ? 'gradient-fire' : campaign.campaign_type === 'affiliate' ? 'gradient-success' : 'gradient-ocean'">
                                    <i :data-lucide="campaign.campaign_type === 'review' ? 'star' : campaign.campaign_type === 'unboxing' ? 'package-open' : campaign.campaign_type === 'affiliate' ? 'link' : 'crown'" class="w-5 h-5 text-white"></i>
                                </div>
                                <div>
                                    <h4 class="font-bold text-white/90" x-text="campaign.name"></h4>
                                    <div class="flex items-center gap-3 mt-1">
                                        <span class="px-2 py-0.5 rounded-lg text-[10px] font-semibold uppercase tracking-wide"
                                              :class="{
                                                  'bg-blue-500/15 text-blue-400 border border-blue-500/20': campaign.status === 'draft',
                                                  'bg-green-500/15 text-green-400 border border-green-500/20': campaign.status === 'active',
                                                  'bg-yellow-500/15 text-yellow-400 border border-yellow-500/20': campaign.status === 'paused',
                                                  'bg-gray-500/15 text-gray-400 border border-gray-500/20': campaign.status === 'completed'
                                              }" x-text="campaign.status || 'draft'"></span>
                                        <span class="text-xs text-white/40 capitalize" x-text="campaign.campaign_type"></span>
                                        <span x-show="campaign.creator_ids" class="text-xs text-white/30">
                                            <i data-lucide="users" class="w-3 h-3 inline-block mr-0.5"></i>
                                            <span x-text="(campaign.creator_ids || []).length + ' criadores'"></span>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="flex items-center gap-4">
                                <div class="text-right">
                                    <p class="text-xs text-white/40">Orcamento</p>
                                    <p class="text-lg font-bold text-accent-green" x-text="'R$ ' + (campaign.budget || 0).toLocaleString('pt-BR')"></p>
                                </div>
                                <button @click="viewCampaignROI(campaign)"
                                        class="px-4 py-2 rounded-xl glass-light text-brand-300 text-xs font-semibold hover:bg-brand-500/10 transition flex items-center gap-1.5">
                                    <i data-lucide="trending-up" class="w-3.5 h-3.5"></i> ROI
                                </button>
                            </div>
                        </div>
                        <!-- Goals -->
                        <div x-show="campaign.goals" class="mt-3 pt-3 border-t border-white/5">
                            <p class="text-xs text-white/40">Metas: <span class="text-white/60" x-text="campaign.goals"></span></p>
                        </div>
                    </div>
                </template>
            </div>
        </template>

        <!-- Empty -->
        <div x-show="!campaignsLoading && campaigns.length === 0" class="flex flex-col items-center justify-center py-16 text-center">
            <div class="w-20 h-20 rounded-2xl glass-light flex items-center justify-center mb-5">
                <i data-lucide="megaphone" class="w-10 h-10 text-white/20"></i>
            </div>
            <h3 class="text-lg font-bold text-white/60 mb-2">Nenhuma campanha</h3>
            <p class="text-sm text-white/30 max-w-md">Crie sua primeira campanha com influenciadores acima.</p>
        </div>

        <!-- ROI Modal -->
        <div x-show="showROI" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
             @click.self="showROI = false" @keydown.escape.window="showROI = false"
             x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100">
            <div class="glass rounded-2xl w-full max-w-lg" @click.stop>
                <div class="p-5 border-b border-white/5 flex items-center justify-between">
                    <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                        <i data-lucide="trending-up" class="w-5 h-5 text-accent-green"></i> ROI da Campanha
                    </h2>
                    <button @click="showROI = false" class="p-1.5 rounded-lg hover:bg-white/10"><i data-lucide="x" class="w-5 h-5"></i></button>
                </div>
                <div class="p-5">
                    <template x-if="roiLoading">
                        <div class="flex flex-col items-center py-8">
                            <div class="w-8 h-8 border-2 border-brand-400 border-t-transparent rounded-full animate-spin mb-3"></div>
                            <p class="text-sm text-white/40">Calculando ROI...</p>
                        </div>
                    </template>
                    <template x-if="!roiLoading && roiData">
                        <div class="space-y-4">
                            <div class="grid grid-cols-2 gap-3">
                                <div class="glass-light rounded-xl p-4 text-center">
                                    <p class="text-xs text-white/40">Investimento</p>
                                    <p class="text-xl font-bold text-white mt-1" x-text="'R$ ' + (roiData.investment || 0).toLocaleString('pt-BR')"></p>
                                </div>
                                <div class="glass-light rounded-xl p-4 text-center">
                                    <p class="text-xs text-white/40">Retorno</p>
                                    <p class="text-xl font-bold text-accent-green mt-1" x-text="'R$ ' + (roiData.revenue || 0).toLocaleString('pt-BR')"></p>
                                </div>
                                <div class="glass-light rounded-xl p-4 text-center">
                                    <p class="text-xs text-white/40">ROI</p>
                                    <p class="text-xl font-bold mt-1" :class="(roiData.roi || 0) >= 0 ? 'text-accent-green' : 'text-accent-red'"
                                       x-text="(roiData.roi || 0).toFixed(1) + '%'"></p>
                                </div>
                                <div class="glass-light rounded-xl p-4 text-center">
                                    <p class="text-xs text-white/40">CPM</p>
                                    <p class="text-xl font-bold text-brand-300 mt-1" x-text="'R$ ' + (roiData.cpm || 0).toFixed(2)"></p>
                                </div>
                            </div>
                            <div x-show="roiData.total_views" class="glass-light rounded-xl p-4">
                                <div class="flex justify-between text-sm">
                                    <span class="text-white/50">Total Views</span>
                                    <span class="text-white/80 font-semibold" x-text="formatNumber(roiData.total_views || 0)"></span>
                                </div>
                                <div class="flex justify-between text-sm mt-2">
                                    <span class="text-white/50">Total Engajamento</span>
                                    <span class="text-white/80 font-semibold" x-text="formatNumber(roiData.total_engagement || 0)"></span>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- ================================================================ -->
    <!-- TAB: OUTREACH                                                     -->
    <!-- ================================================================ -->
    <div x-show="activeTab === 'outreach'" x-transition>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- Generator Form -->
            <div class="glass-card rounded-2xl p-5 animate-fade-up">
                <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 flex-shrink-0">
                        <i data-lucide="sparkles" class="w-5 h-5"></i>
                    </div>
                    Gerador de Outreach IA
                </h3>
                <div class="space-y-4">
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Username do Criador *</label>
                        <input x-model="outreachUsername" type="text" placeholder="@username"
                               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 block">Nome da Marca *</label>
                        <input x-model="outreachBrand" type="text" placeholder="Sua marca"
                               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 block">Tipo de Campanha</label>
                        <select x-model="outreachType"
                                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="review">Review de Produto</option>
                            <option value="unboxing">Unboxing</option>
                            <option value="affiliate">Programa de Afiliados</option>
                            <option value="ambassador">Embaixador da Marca</option>
                            <option value="sponsored">Post Patrocinado</option>
                            <option value="collab">Colaboracao</option>
                        </select>
                    </div>
                    <div>
                        <label class="text-xs text-white/50 mb-1 block">Tom</label>
                        <select x-model="outreachTone"
                                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="profissional">Profissional</option>
                            <option value="casual">Casual</option>
                            <option value="entusiasmado">Entusiasmado</option>
                            <option value="direto">Direto ao Ponto</option>
                        </select>
                    </div>
                    <button @click="generateOutreach()" :disabled="!outreachUsername || !outreachBrand || outreachLoading"
                            class="w-full px-6 py-3 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition flex items-center justify-center gap-2 disabled:opacity-50">
                        <div x-show="outreachLoading" class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                        <i x-show="!outreachLoading" data-lucide="sparkles" class="w-4 h-4"></i>
                        <span x-text="outreachLoading ? 'Gerando...' : 'Gerar Mensagem'"></span>
                    </button>
                </div>
            </div>

            <!-- Preview -->
            <div class="glass-card rounded-2xl p-5 animate-fade-up-delay">
                <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
                </h3>
                <template x-if="outreachResult">
                    <div>
                        <div x-show="outreachResult.subject" class="mb-3">
                            <p class="text-xs text-white/40 mb-1">Assunto:</p>
                            <p class="text-sm font-semibold text-white/80" x-text="outreachResult.subject"></p>
                        </div>
                        <div class="glass-light rounded-xl p-4 mb-4">
                            <p class="text-sm text-white/70 leading-relaxed whitespace-pre-wrap" x-text="outreachResult.message || outreachResult.body || outreachResult.content || JSON.stringify(outreachResult)"></p>
                        </div>
                        <div class="flex gap-2">
                            <button @click="copyOutreach()"
                                    class="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition">
                                <i data-lucide="copy" class="w-4 h-4"></i> Copiar Mensagem
                            </button>
                            <button @click="outreachResult = null"
                                    class="flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl glass-light text-white/60 font-medium text-sm hover:text-white/80 transition">
                                <i data-lucide="refresh-cw" class="w-4 h-4"></i> Limpar
                            </button>
                        </div>
                    </div>
                </template>
                <div x-show="!outreachResult" class="flex flex-col items-center justify-center py-12 text-center">
                    <div class="w-16 h-16 rounded-2xl glass-light flex items-center justify-center mb-4">
                        <i data-lucide="mail" class="w-8 h-8 text-white/15"></i>
                    </div>
                    <p class="text-sm text-white/30">Preencha os dados e gere uma mensagem personalizada com IA</p>
                </div>
            </div>
        </div>
    </div>

    <!-- ================================================================ -->
    <!-- TAB: REVENUE                                                      -->
    <!-- ================================================================ -->
    <div x-show="activeTab === 'revenue'" x-transition>

        <!-- Revenue Dashboard -->
        <div class="mb-6 animate-fade-up">
            <div class="flex flex-wrap gap-3 mb-4 items-end">
                <div>
                    <label class="text-xs text-white/50 mb-1 block">Creator ID (opcional)</label>
                    <input x-model="revenueCreatorId" type="number" placeholder="Todos"
                           class="bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none transition w-36">
                </div>
                <div>
                    <label class="text-xs text-white/50 mb-1 block">Periodo</label>
                    <select x-model="revenueDays" @change="loadRevenue()"
                            class="bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 focus:border-brand-400 focus:outline-none transition">
                        <option value="7">7 dias</option>
                        <option value="14">14 dias</option>
                        <option value="30">30 dias</option>
                        <option value="90">90 dias</option>
                    </select>
                </div>
                <button @click="loadRevenue()"
                        class="px-4 py-2.5 rounded-xl glass-light text-white/60 hover:text-white text-sm font-medium transition flex items-center gap-2">
                    <i data-lucide="refresh-cw" class="w-3.5 h-3.5"></i> Atualizar
                </button>
            </div>

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

            <!-- Revenue Cards -->
            <template x-if="!revenueLoading && revenueData">
                <div>
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                        <div class="glass-card rounded-2xl p-5">
                            <div class="flex items-center gap-3 mb-3">
                                <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center">
                                    <i data-lucide="play-circle" class="w-5 h-5"></i>
                                </div>
                                <span class="text-xs text-white/40">Ad Revenue</span>
                            </div>
                            <p class="stat-number text-white" x-text="'R$ ' + (revenueData.ad_revenue || 0).toLocaleString('pt-BR')"></p>
                            <p class="text-xs text-white/30 mt-1" x-text="(revenueData.ad_revenue_change || 0) > 0 ? '+' + revenueData.ad_revenue_change + '%' : (revenueData.ad_revenue_change || 0) + '%'"></p>
                        </div>
                        <div class="glass-card rounded-2xl p-5">
                            <div class="flex items-center gap-3 mb-3">
                                <div class="w-10 h-10 rounded-xl gradient-fire flex items-center justify-center">
                                    <i data-lucide="shopping-bag" class="w-5 h-5"></i>
                                </div>
                                <span class="text-xs text-white/40">Shop Comissoes</span>
                            </div>
                            <p class="stat-number text-accent-orange" x-text="'R$ ' + (revenueData.shop_commissions || 0).toLocaleString('pt-BR')"></p>
                            <p class="text-xs text-white/30 mt-1" x-text="(revenueData.shop_commissions_change || 0) > 0 ? '+' + revenueData.shop_commissions_change + '%' : (revenueData.shop_commissions_change || 0) + '%'"></p>
                        </div>
                        <div class="glass-card rounded-2xl p-5">
                            <div class="flex items-center gap-3 mb-3">
                                <div class="w-10 h-10 rounded-xl gradient-success flex items-center justify-center">
                                    <i data-lucide="link" class="w-5 h-5"></i>
                                </div>
                                <span class="text-xs text-white/40">Afiliados</span>
                            </div>
                            <p class="stat-number text-accent-green" x-text="'R$ ' + (revenueData.affiliate_revenue || 0).toLocaleString('pt-BR')"></p>
                            <p class="text-xs text-white/30 mt-1" x-text="(revenueData.affiliate_change || 0) > 0 ? '+' + revenueData.affiliate_change + '%' : (revenueData.affiliate_change || 0) + '%'"></p>
                        </div>
                        <div class="glass-card rounded-2xl p-5">
                            <div class="flex items-center gap-3 mb-3">
                                <div class="w-10 h-10 rounded-xl gradient-ocean flex items-center justify-center">
                                    <i data-lucide="handshake" class="w-5 h-5"></i>
                                </div>
                                <span class="text-xs text-white/40">Patrocinios</span>
                            </div>
                            <p class="stat-number text-accent-cyan" x-text="'R$ ' + (revenueData.sponsorship_revenue || 0).toLocaleString('pt-BR')"></p>
                            <p class="text-xs text-white/30 mt-1" x-text="(revenueData.sponsorship_change || 0) > 0 ? '+' + revenueData.sponsorship_change + '%' : (revenueData.sponsorship_change || 0) + '%'"></p>
                        </div>
                    </div>

                    <!-- Total -->
                    <div class="glass-card rounded-2xl p-5 mb-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-xs text-white/40 mb-1">Receita Total</p>
                                <p class="text-3xl font-extrabold text-white" x-text="'R$ ' + (revenueData.total_revenue || 0).toLocaleString('pt-BR')"></p>
                            </div>
                            <div class="text-right">
                                <p class="text-xs text-white/40 mb-1">Variacao</p>
                                <p class="text-lg font-bold" :class="(revenueData.total_change || 0) >= 0 ? 'text-accent-green' : 'text-accent-red'"
                                   x-text="((revenueData.total_change || 0) >= 0 ? '+' : '') + (revenueData.total_change || 0) + '%'"></p>
                            </div>
                        </div>
                    </div>
                </div>
            </template>
        </div>

        <!-- Sponsorship Rate Calculator -->
        <div class="glass-card rounded-2xl p-5 animate-fade-up-delay">
            <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 flex-shrink-0">
                    <i data-lucide="calculator" class="w-5 h-5"></i>
                </div>
                Calculadora de Taxas de Patrocinio
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-4">
                <div>
                    <label class="text-xs text-white/50 mb-1 block">Seguidores: <span class="text-brand-300" x-text="formatNumber(sponsorFollowers)"></span></label>
                    <input x-model.number="sponsorFollowers" type="range" min="1000" max="10000000" step="1000"
                           class="w-full accent-brand-500 h-2 bg-dark-600 rounded-lg appearance-none cursor-pointer">
                </div>
                <div>
                    <label class="text-xs text-white/50 mb-1 block">Engagement Rate: <span class="text-accent-green" x-text="sponsorEngagement.toFixed(1) + '%'"></span></label>
                    <input x-model.number="sponsorEngagement" type="range" min="0.1" max="20" step="0.1"
                           class="w-full accent-green-500 h-2 bg-dark-600 rounded-lg appearance-none cursor-pointer">
                </div>
                <div>
                    <label class="text-xs text-white/50 mb-1 block">Plataforma</label>
                    <select x-model="sponsorPlatform"
                            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="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">Nicho</label>
                    <select x-model="sponsorNiche"
                            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="geral">Geral</option>
                        <option value="beleza">Beleza</option>
                        <option value="fitness">Fitness</option>
                        <option value="tech">Tecnologia</option>
                        <option value="games">Games</option>
                        <option value="food">Gastronomia</option>
                        <option value="fashion">Moda</option>
                        <option value="travel">Viagem</option>
                        <option value="finance">Financas</option>
                    </select>
                </div>
            </div>
            <button @click="calculateSponsorRate()" :disabled="sponsorLoading"
                    class="px-6 py-2.5 rounded-xl gradient-success text-white font-semibold text-sm hover:opacity-90 transition flex items-center gap-2 disabled:opacity-50 mb-4">
                <div x-show="sponsorLoading" class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                <i x-show="!sponsorLoading" data-lucide="calculator" class="w-4 h-4"></i>
                <span x-text="sponsorLoading ? 'Calculando...' : 'Calcular Taxa'"></span>
            </button>

            <!-- Sponsor Result -->
            <template x-if="sponsorResult">
                <div class="grid grid-cols-1 sm:grid-cols-3 gap-4 mt-4">
                    <div class="glass-light rounded-xl p-4 text-center">
                        <p class="text-xs text-white/40 mb-1">Post/Video</p>
                        <p class="text-xl font-bold text-white" x-text="'R$ ' + (sponsorResult.rate_per_post || 0).toLocaleString('pt-BR')"></p>
                    </div>
                    <div class="glass-light rounded-xl p-4 text-center">
                        <p class="text-xs text-white/40 mb-1">Stories/Reels</p>
                        <p class="text-xl font-bold text-accent-pink" x-text="'R$ ' + (sponsorResult.rate_per_story || 0).toLocaleString('pt-BR')"></p>
                    </div>
                    <div class="glass-light rounded-xl p-4 text-center">
                        <p class="text-xs text-white/40 mb-1">Pacote Mensal</p>
                        <p class="text-xl font-bold text-accent-green" x-text="'R$ ' + (sponsorResult.monthly_package || 0).toLocaleString('pt-BR')"></p>
                    </div>
                </div>
            </template>
        </div>
    </div>

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

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

        <!-- Stats Cards -->
        <template x-if="!statsLoading && stats">
            <div>
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6 animate-fade-up">
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center">
                                <i data-lucide="contact" class="w-5 h-5"></i>
                            </div>
                            <span class="text-xs text-white/40">Total Contatos</span>
                        </div>
                        <p class="stat-number text-white" x-text="stats.total_contacts || 0"></p>
                    </div>
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl gradient-fire flex items-center justify-center">
                                <i data-lucide="megaphone" class="w-5 h-5"></i>
                            </div>
                            <span class="text-xs text-white/40">Campanhas Ativas</span>
                        </div>
                        <p class="stat-number text-accent-orange" x-text="stats.active_campaigns || 0"></p>
                    </div>
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl gradient-success flex items-center justify-center">
                                <i data-lucide="user-check" class="w-5 h-5"></i>
                            </div>
                            <span class="text-xs text-white/40">Criadores Ativos</span>
                        </div>
                        <p class="stat-number text-accent-green" x-text="stats.active_creators || 0"></p>
                    </div>
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl gradient-ocean flex items-center justify-center">
                                <i data-lucide="dollar-sign" class="w-5 h-5"></i>
                            </div>
                            <span class="text-xs text-white/40">Receita Total</span>
                        </div>
                        <p class="stat-number text-accent-cyan" x-text="'R$ ' + (stats.total_revenue || 0).toLocaleString('pt-BR')"></p>
                    </div>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 animate-fade-up-delay">
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl bg-blue-500/20 flex items-center justify-center">
                                <i data-lucide="inbox" class="w-5 h-5 text-blue-400"></i>
                            </div>
                            <span class="text-xs text-white/40">Leads</span>
                        </div>
                        <p class="stat-number text-blue-400" x-text="stats.leads || 0"></p>
                    </div>
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl bg-yellow-500/20 flex items-center justify-center">
                                <i data-lucide="send" class="w-5 h-5 text-yellow-400"></i>
                            </div>
                            <span class="text-xs text-white/40">Contatados</span>
                        </div>
                        <p class="stat-number text-yellow-400" x-text="stats.contacted || 0"></p>
                    </div>
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl bg-orange-500/20 flex items-center justify-center">
                                <i data-lucide="message-square" class="w-5 h-5 text-orange-400"></i>
                            </div>
                            <span class="text-xs text-white/40">Negociando</span>
                        </div>
                        <p class="stat-number text-orange-400" x-text="stats.negotiating || 0"></p>
                    </div>
                    <div class="glass-card rounded-2xl p-5">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-xl bg-purple-500/20 flex items-center justify-center">
                                <i data-lucide="bar-chart-3" class="w-5 h-5 text-purple-400"></i>
                            </div>
                            <span class="text-xs text-white/40">ROI Medio</span>
                        </div>
                        <p class="stat-number text-purple-400" x-text="(stats.avg_roi || 0).toFixed(1) + '%'"></p>
                    </div>
                </div>
            </div>
        </template>

        <!-- Empty -->
        <div x-show="!statsLoading && !stats" class="flex flex-col items-center justify-center py-16 text-center">
            <div class="w-20 h-20 rounded-2xl glass-light flex items-center justify-center mb-5">
                <i data-lucide="bar-chart-3" class="w-10 h-10 text-white/20"></i>
            </div>
            <h3 class="text-lg font-bold text-white/60 mb-2">Sem dados ainda</h3>
            <p class="text-sm text-white/30 max-w-md">Adicione contatos e crie campanhas para ver as estatisticas.</p>
        </div>
    </div>

</div>
{% endblock %}

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

        // discover
        searchNiche: '',
        searchPlatform: '',
        minFollowers: 0,
        maxFollowers: 0,
        discoverResults: [],
        discoverLoading: false,

        // media kit
        showMediaKit: false,
        mediaKitLoading: false,
        mediaKitData: null,

        // fake detection
        showFakeDetection: false,
        fakeDetectionLoading: false,
        fakeDetectionData: null,

        // contacts
        contacts: [],
        contactsLoading: false,
        contactFilter: '',
        contactTag: '',
        selectedContact: null,
        newInteraction: '',
        newInteractionType: 'note',
        showAddContact: false,
        newContactName: '',
        newContactEmail: '',
        newContactTags: '',
        newContactNotes: '',
        showEditContact: false,
        editContactData: {},

        // campaigns
        campaigns: [],
        campaignsLoading: false,
        newCampaignName: '',
        newCampaignType: 'review',
        newCampaignBudget: 0,
        newCampaignGoals: '',
        newCampaignCreatorIds: '',
        campaignStatusFilter: '',
        showROI: false,
        roiLoading: false,
        roiData: null,

        // outreach
        outreachUsername: '',
        outreachBrand: '',
        outreachType: 'review',
        outreachTone: 'profissional',
        outreachLoading: false,
        outreachResult: null,

        // revenue
        revenueData: null,
        revenueLoading: false,
        revenueCreatorId: '',
        revenueDays: 30,
        sponsorFollowers: 10000,
        sponsorEngagement: 3.0,
        sponsorPlatform: 'tiktok',
        sponsorNiche: 'geral',
        sponsorResult: null,
        sponsorLoading: false,

        // stats
        stats: null,
        statsLoading: false,

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

        // ==================== DISCOVER ====================

        async discoverInfluencers() {
            this.discoverLoading = true;
            this.discoverResults = [];
            try {
                const params = new URLSearchParams();
                if (this.searchNiche) params.set('niche', this.searchNiche);
                if (this.searchPlatform) params.set('platform', this.searchPlatform);
                if (this.minFollowers > 0) params.set('min_followers', this.minFollowers);
                if (this.maxFollowers > 0) params.set('max_followers', this.maxFollowers);
                params.set('limit', 20);
                const data = await apiCall('/api/crm/discover?' + params.toString());
                this.discoverResults = data.creators || data.results || data || [];
                if (this.discoverResults.length === 0) showToast('Nenhum influenciador encontrado para esses filtros', 'warning');
                else showToast(`${this.discoverResults.length} influenciadores encontrados!`, 'success');
            } catch (e) {
                showToast('Erro ao buscar influenciadores: ' + e.message, 'error');
            }
            this.discoverLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async addToCRM(creator) {
            try {
                await apiCall('/api/crm/contacts', 'POST', {
                    creator_id: creator.id || null,
                    name: creator.username || creator.name,
                    email: creator.email || '',
                    tags: [creator.platform || 'tiktok', creator.niche || ''].filter(Boolean),
                    notes: 'Adicionado via Discover. Seguidores: ' + formatNumber(creator.followers || 0)
                });
                showToast(`${creator.username || creator.name} adicionado ao CRM!`, 'success');
            } catch (e) {
                showToast('Erro ao adicionar contato: ' + e.message, 'error');
            }
        },

        async getMediaKit(creator) {
            this.showMediaKit = true;
            this.mediaKitLoading = true;
            this.mediaKitData = null;
            try {
                const data = await apiCall('/api/crm/media-kit/' + (creator.id || 0));
                this.mediaKitData = data;
            } catch (e) {
                showToast('Erro ao gerar media kit: ' + e.message, 'error');
                this.showMediaKit = false;
            }
            this.mediaKitLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async detectFake(creator) {
            this.showFakeDetection = true;
            this.fakeDetectionLoading = true;
            this.fakeDetectionData = null;
            try {
                const data = await apiCall('/api/crm/fake-detection/' + (creator.id || 0));
                this.fakeDetectionData = data;
            } catch (e) {
                showToast('Erro na deteccao de fakes: ' + e.message, 'error');
                this.showFakeDetection = false;
            }
            this.fakeDetectionLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        // ==================== CONTACTS ====================

        async loadContacts() {
            this.contactsLoading = true;
            try {
                const params = new URLSearchParams();
                if (this.contactFilter) params.set('status', this.contactFilter);
                if (this.contactTag) params.set('tag', this.contactTag);
                params.set('limit', 50);
                const data = await apiCall('/api/crm/contacts?' + params.toString());
                this.contacts = data.contacts || data || [];
            } catch (e) {
                showToast('Erro ao carregar contatos: ' + e.message, 'error');
            }
            this.contactsLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async selectContact(contact) {
            try {
                const data = await apiCall('/api/crm/contacts/' + contact.id);
                this.selectedContact = data;
            } catch (e) {
                this.selectedContact = contact;
            }
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        editContact(contact) {
            this.editContactData = {
                id: contact.id,
                name: contact.name || '',
                email: contact.email || '',
                status: contact.status || 'lead',
                tags_str: (contact.tags || []).join(', '),
                notes: contact.notes || ''
            };
            this.showEditContact = true;
        },

        async updateContact() {
            try {
                const payload = {
                    name: this.editContactData.name,
                    email: this.editContactData.email,
                    status: this.editContactData.status,
                    tags: this.editContactData.tags_str ? this.editContactData.tags_str.split(',').map(t => t.trim()).filter(Boolean) : [],
                    notes: this.editContactData.notes
                };
                await apiCall('/api/crm/contacts/' + this.editContactData.id, 'PUT', payload);
                showToast('Contato atualizado!', 'success');
                this.showEditContact = false;
                this.loadContacts();
            } catch (e) {
                showToast('Erro ao atualizar contato: ' + e.message, 'error');
            }
        },

        async deleteContact(contactId) {
            if (!confirm('Deseja realmente excluir este contato?')) return;
            try {
                await apiCall('/api/crm/contacts/' + contactId, 'DELETE');
                showToast('Contato excluido!', 'success');
                this.loadContacts();
            } catch (e) {
                showToast('Erro ao excluir contato: ' + e.message, 'error');
            }
        },

        async addInteraction() {
            if (!this.newInteraction.trim() || !this.selectedContact?.id) return;
            try {
                await apiCall('/api/crm/contacts/' + this.selectedContact.id + '/interactions', 'POST', {
                    type: this.newInteractionType,
                    content: this.newInteraction
                });
                showToast('Interacao adicionada!', 'success');
                this.newInteraction = '';
                // Reload contact details
                const data = await apiCall('/api/crm/contacts/' + this.selectedContact.id);
                this.selectedContact = data;
            } catch (e) {
                showToast('Erro ao adicionar interacao: ' + e.message, 'error');
            }
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async createContact() {
            try {
                await apiCall('/api/crm/contacts', 'POST', {
                    name: this.newContactName,
                    email: this.newContactEmail,
                    tags: this.newContactTags ? this.newContactTags.split(',').map(t => t.trim()).filter(Boolean) : [],
                    notes: this.newContactNotes
                });
                showToast('Contato criado com sucesso!', 'success');
                this.showAddContact = false;
                this.newContactName = '';
                this.newContactEmail = '';
                this.newContactTags = '';
                this.newContactNotes = '';
                this.loadContacts();
            } catch (e) {
                showToast('Erro ao criar contato: ' + e.message, 'error');
            }
        },

        // ==================== CAMPAIGNS ====================

        async loadCampaigns() {
            this.campaignsLoading = true;
            try {
                const params = new URLSearchParams();
                if (this.campaignStatusFilter) params.set('status', this.campaignStatusFilter);
                const data = await apiCall('/api/crm/campaigns?' + params.toString());
                this.campaigns = data.campaigns || data || [];
            } catch (e) {
                showToast('Erro ao carregar campanhas: ' + e.message, 'error');
            }
            this.campaignsLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async createCampaign() {
            if (!this.newCampaignName) return;
            try {
                const creatorIds = this.newCampaignCreatorIds
                    ? this.newCampaignCreatorIds.split(',').map(id => parseInt(id.trim())).filter(Boolean)
                    : [];
                await apiCall('/api/crm/campaigns', 'POST', {
                    name: this.newCampaignName,
                    campaign_type: this.newCampaignType,
                    budget: this.newCampaignBudget,
                    creator_ids: creatorIds,
                    goals: this.newCampaignGoals
                });
                showToast('Campanha criada com sucesso!', 'success');
                this.newCampaignName = '';
                this.newCampaignBudget = 0;
                this.newCampaignGoals = '';
                this.newCampaignCreatorIds = '';
                this.loadCampaigns();
            } catch (e) {
                showToast('Erro ao criar campanha: ' + e.message, 'error');
            }
        },

        async viewCampaignROI(campaign) {
            this.showROI = true;
            this.roiLoading = true;
            this.roiData = null;
            try {
                const data = await apiCall('/api/crm/campaigns/' + campaign.id + '/roi');
                this.roiData = data;
            } catch (e) {
                showToast('Erro ao calcular ROI: ' + e.message, 'error');
                this.showROI = false;
            }
            this.roiLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        // ==================== OUTREACH ====================

        async generateOutreach() {
            this.outreachLoading = true;
            this.outreachResult = null;
            try {
                const data = await apiCall('/api/crm/outreach', 'POST', {
                    creator_username: this.outreachUsername,
                    brand_name: this.outreachBrand,
                    campaign_type: this.outreachType,
                    tone: this.outreachTone
                });
                this.outreachResult = data;
                showToast('Mensagem gerada com sucesso!', 'success');
            } catch (e) {
                showToast('Erro ao gerar outreach: ' + e.message, 'error');
            }
            this.outreachLoading = false;
        },

        copyOutreach() {
            const text = this.outreachResult?.message || this.outreachResult?.body || this.outreachResult?.content || '';
            if (!text) return;
            navigator.clipboard.writeText(text).then(() => {
                showToast('Mensagem copiada!', 'success');
            }).catch(() => {
                // Fallback
                const ta = document.createElement('textarea');
                ta.value = text;
                document.body.appendChild(ta);
                ta.select();
                document.execCommand('copy');
                document.body.removeChild(ta);
                showToast('Mensagem copiada!', 'success');
            });
        },

        // ==================== REVENUE ====================

        async loadRevenue() {
            this.revenueLoading = true;
            this.revenueData = null;
            try {
                const params = new URLSearchParams();
                if (this.revenueCreatorId) params.set('creator_id', this.revenueCreatorId);
                params.set('days', this.revenueDays);
                const data = await apiCall('/api/crm/revenue-dashboard?' + params.toString());
                this.revenueData = data;
            } catch (e) {
                showToast('Erro ao carregar revenue: ' + e.message, 'error');
            }
            this.revenueLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },

        async calculateSponsorRate() {
            this.sponsorLoading = true;
            this.sponsorResult = null;
            try {
                const data = await apiCall('/api/crm/sponsorship-rate', 'POST', {
                    followers: this.sponsorFollowers,
                    engagement_rate: this.sponsorEngagement,
                    platform: this.sponsorPlatform,
                    niche: this.sponsorNiche
                });
                this.sponsorResult = data;
                showToast('Taxa calculada!', 'success');
            } catch (e) {
                showToast('Erro ao calcular taxa: ' + e.message, 'error');
            }
            this.sponsorLoading = false;
        },

        // ==================== STATS ====================

        async loadStats() {
            this.statsLoading = true;
            this.stats = null;
            try {
                const data = await apiCall('/api/crm/stats');
                this.stats = data;
            } catch (e) {
                showToast('Erro ao carregar stats: ' + e.message, 'error');
            }
            this.statsLoading = false;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        }
    };
}
</script>
{% endblock %}
