{% extends "base.html" %}
{% block title %}Espiao de Concorrentes - Viral Social Pro{% endblock %}
{% block nav_competitors %}active{% endblock %}
{% block page_title %}Espiao de Concorrentes{% endblock %}
{% block page_subtitle %}Monitore seus concorrentes em tempo real{% endblock %}

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

    <!-- HEADER + ADD FORM -->
    <div class="animate-fade-up mb-6">
        <div class="glass-card rounded-2xl p-5">
            <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-1 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="user-plus" class="w-5 h-5"></i>
                        </div>
                        Adicionar Concorrente
                    </h3>
                    <p class="text-xs text-white/40 ml-12">Acompanhe o crescimento e estrategias dos seus concorrentes</p>
                </div>
                <form @submit.prevent="addCompetitor()" class="flex flex-col sm:flex-row gap-3 w-full md:w-auto">
                    <select x-model="newPlatform" 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-[140px]">
                        <option value="tiktok">TikTok</option>
                        <option value="instagram">Instagram</option>
                        <option value="youtube">YouTube</option>
                    </select>
                    <div class="relative flex-1 min-w-[200px]">
                        <i data-lucide="at-sign" class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/30"></i>
                        <input type="text" x-model="newUsername" placeholder="Nome de usuario" required
                               class="w-full bg-dark-700 border border-white/10 rounded-xl pl-9 pr-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none transition"
                               @keydown.enter.prevent="addCompetitor()">
                    </div>
                    <button type="submit" :disabled="addingCompetitor || !newUsername.trim()"
                            class="flex items-center justify-center gap-2 px-6 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-40 disabled:cursor-not-allowed whitespace-nowrap">
                        <template x-if="addingCompetitor">
                            <svg class="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                        </template>
                        <template x-if="!addingCompetitor">
                            <i data-lucide="plus" class="w-4 h-4"></i>
                        </template>
                        <span x-text="addingCompetitor ? 'Adicionando...' : 'Adicionar'"></span>
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- STATS SUMMARY -->
    <div x-show="competitors.length > 0" x-transition class="animate-fade-up-delay grid grid-cols-2 md:grid-cols-4 gap-3 mb-6">
        <div class="glass-card rounded-xl p-4 text-center">
            <div class="flex items-center justify-center gap-2 mb-1">
                <i data-lucide="users" class="w-4 h-4 text-brand-300"></i>
            </div>
            <p class="stat-number text-brand-300" x-text="competitors.length"></p>
            <p class="text-xs text-white/40 mt-1">Concorrentes</p>
        </div>
        <div class="glass-card rounded-xl p-4 text-center">
            <div class="flex items-center justify-center gap-2 mb-1">
                <i data-lucide="user-check" class="w-4 h-4 text-accent-pink"></i>
            </div>
            <p class="stat-number text-accent-pink" x-text="formatNumber(totalFollowers)"></p>
            <p class="text-xs text-white/40 mt-1">Seguidores Total</p>
        </div>
        <div class="glass-card rounded-xl p-4 text-center">
            <div class="flex items-center justify-center gap-2 mb-1">
                <i data-lucide="heart" class="w-4 h-4 text-accent-cyan"></i>
            </div>
            <p class="stat-number text-accent-cyan" x-text="formatNumber(totalLikes)"></p>
            <p class="text-xs text-white/40 mt-1">Likes Total</p>
        </div>
        <div class="glass-card rounded-xl p-4 text-center">
            <div class="flex items-center justify-center gap-2 mb-1">
                <i data-lucide="video" class="w-4 h-4 text-accent-green"></i>
            </div>
            <p class="stat-number text-accent-green" x-text="formatNumber(totalVideos)"></p>
            <p class="text-xs text-white/40 mt-1">Videos Total</p>
        </div>
    </div>

    <!-- LOADING STATE -->
    <div x-show="loading" class="grid-cards">
        <template x-for="i in 6">
            <div class="glass-card rounded-2xl p-5">
                <div class="flex items-center gap-3 mb-4">
                    <div class="skeleton w-12 h-12 rounded-full"></div>
                    <div class="flex-1">
                        <div class="skeleton h-4 w-24 mb-2"></div>
                        <div class="skeleton h-3 w-16"></div>
                    </div>
                </div>
                <div class="grid grid-cols-3 gap-3">
                    <div class="skeleton h-16 rounded-lg"></div>
                    <div class="skeleton h-16 rounded-lg"></div>
                    <div class="skeleton h-16 rounded-lg"></div>
                </div>
            </div>
        </template>
    </div>

    <!-- EMPTY STATE -->
    <div x-show="!loading && competitors.length === 0" x-transition class="animate-fade-up">
        <div class="glass-card rounded-2xl p-12 text-center max-w-lg mx-auto">
            <div class="w-20 h-20 rounded-full gradient-brand mx-auto flex items-center justify-center mb-5 opacity-60 animate-pulse-glow">
                <i data-lucide="eye" class="w-10 h-10 text-white"></i>
            </div>
            <h3 class="text-xl font-bold text-white/80 mb-2">Nenhum concorrente monitorado</h3>
            <p class="text-sm text-white/40 mb-6 leading-relaxed">Adicione concorrentes para acompanhar seu crescimento, estrategias e melhores videos em tempo real.</p>
            <div class="flex items-center justify-center gap-6 text-xs text-white/30">
                <span class="flex items-center gap-1.5"><i data-lucide="trending-up" class="w-3.5 h-3.5"></i> Crescimento</span>
                <span class="flex items-center gap-1.5"><i data-lucide="bar-chart-3" class="w-3.5 h-3.5"></i> Analise</span>
                <span class="flex items-center gap-1.5"><i data-lucide="video" class="w-3.5 h-3.5"></i> Videos</span>
            </div>
        </div>
    </div>

    <!-- COMPETITORS GRID -->
    <div x-show="!loading && competitors.length > 0" x-transition class="grid-cards animate-fade-up-delay">
        <template x-for="comp in competitors" :key="comp.id">
            <div class="glass-card rounded-2xl p-5 cursor-pointer group relative overflow-hidden" @click="openDetail(comp)">
                <!-- Gradient top accent -->
                <div class="absolute top-0 left-0 right-0 h-1 opacity-0 group-hover:opacity-100 transition-opacity duration-300"
                     :class="comp.platform === 'youtube' ? 'gradient-fire' : comp.platform === 'instagram' ? 'bg-gradient-to-r from-purple-500 via-pink-500 to-orange-500' : 'gradient-brand'"></div>

                <!-- Refresh / Delete buttons -->
                <div class="absolute top-3 right-3 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10">
                    <button @click.stop="refreshCompetitor(comp)" :disabled="comp._refreshing"
                            class="p-1.5 rounded-lg hover:bg-white/10 transition text-white/40 hover:text-brand-300" title="Atualizar dados">
                        <i data-lucide="refresh-cw" class="w-4 h-4" :class="comp._refreshing && 'animate-spin'"></i>
                    </button>
                    <button @click.stop="deleteCompetitor(comp)" class="p-1.5 rounded-lg hover:bg-red-500/20 transition text-white/40 hover:text-red-400" title="Remover">
                        <i data-lucide="trash-2" class="w-4 h-4"></i>
                    </button>
                </div>

                <!-- Header -->
                <div class="flex items-center gap-3 mb-4">
                    <div class="relative flex-shrink-0">
                        <img :src="comp.avatar_url || ''" :alt="comp.display_name"
                             class="w-12 h-12 rounded-full object-cover ring-2 ring-white/10 group-hover:ring-brand-400/30 transition-all"
                             onerror="this.style.display='none'; this.nextElementSibling.style.display='flex'">
                        <div class="hidden w-12 h-12 rounded-full items-center justify-center text-white font-bold text-lg ring-2 ring-white/10"
                             :class="comp.platform === 'youtube' ? 'bg-red-500/80' : comp.platform === 'instagram' ? 'bg-gradient-to-br from-purple-500 to-pink-500' : 'bg-gradient-to-br from-brand-400 to-accent-cyan'"
                             x-text="(comp.display_name || comp.username || '?')[0].toUpperCase()"></div>
                        <!-- Platform indicator dot -->
                        <div class="absolute -bottom-0.5 -right-0.5 w-5 h-5 rounded-full flex items-center justify-center text-[9px] font-black border-2 border-dark-800"
                             :class="comp.platform === 'youtube' ? 'bg-red-500 text-white' : comp.platform === 'instagram' ? 'bg-gradient-to-br from-purple-500 to-pink-500 text-white' : 'bg-white text-black'"
                             x-text="comp.platform === 'youtube' ? 'Y' : comp.platform === 'instagram' ? 'I' : 'T'"></div>
                    </div>
                    <div class="flex-1 min-w-0">
                        <h4 class="font-bold text-white/90 truncate text-sm group-hover:text-white transition" x-text="comp.display_name || comp.username"></h4>
                        <p class="text-xs text-white/40 truncate" x-text="'@' + comp.username"></p>
                    </div>
                </div>

                <!-- Platform Badge + Last Updated -->
                <div class="flex items-center gap-2 mb-4">
                    <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg text-[11px] font-semibold"
                          :class="'badge-' + comp.platform"
                          x-text="platformLabel(comp.platform)"></span>
                    <span x-show="comp.last_updated || comp.last_checked" class="text-[10px] text-white/25 ml-auto flex items-center gap-1">
                        <i data-lucide="clock" class="w-3 h-3"></i>
                        <span x-text="timeAgo(comp.last_updated || comp.last_checked)"></span>
                    </span>
                </div>

                <!-- Stats -->
                <div class="grid grid-cols-3 gap-2">
                    <div class="bg-dark-800/50 rounded-xl p-3 text-center">
                        <p class="text-sm font-bold text-white/90" x-text="formatNumber(comp.followers || 0)"></p>
                        <p class="text-[10px] text-white/40 mt-0.5">Seguidores</p>
                        <div x-show="comp.followers_growth != null && comp.followers_growth !== 0" class="mt-1">
                            <span class="text-[10px] font-semibold inline-flex items-center gap-0.5"
                                  :class="comp.followers_growth > 0 ? 'text-accent-green' : 'text-accent-red'">
                                <i :data-lucide="comp.followers_growth > 0 ? 'trending-up' : 'trending-down'" class="w-3 h-3"></i>
                                <span x-text="(comp.followers_growth > 0 ? '+' : '') + formatNumber(comp.followers_growth)"></span>
                            </span>
                        </div>
                    </div>
                    <div class="bg-dark-800/50 rounded-xl p-3 text-center">
                        <p class="text-sm font-bold text-accent-pink" x-text="formatNumber(comp.total_likes || 0)"></p>
                        <p class="text-[10px] text-white/40 mt-0.5">Likes</p>
                        <div x-show="comp.likes_growth != null && comp.likes_growth !== 0" class="mt-1">
                            <span class="text-[10px] font-semibold inline-flex items-center gap-0.5"
                                  :class="comp.likes_growth > 0 ? 'text-accent-green' : 'text-accent-red'">
                                <i :data-lucide="comp.likes_growth > 0 ? 'trending-up' : 'trending-down'" class="w-3 h-3"></i>
                                <span x-text="(comp.likes_growth > 0 ? '+' : '') + formatNumber(comp.likes_growth)"></span>
                            </span>
                        </div>
                    </div>
                    <div class="bg-dark-800/50 rounded-xl p-3 text-center">
                        <p class="text-sm font-bold text-accent-cyan" x-text="formatNumber(comp.video_count || 0)"></p>
                        <p class="text-[10px] text-white/40 mt-0.5">Videos</p>
                        <div x-show="comp.videos_growth != null && comp.videos_growth !== 0" class="mt-1">
                            <span class="text-[10px] font-semibold inline-flex items-center gap-0.5"
                                  :class="comp.videos_growth > 0 ? 'text-accent-green' : 'text-accent-red'">
                                <i :data-lucide="comp.videos_growth > 0 ? 'trending-up' : 'trending-down'" class="w-3 h-3"></i>
                                <span x-text="(comp.videos_growth > 0 ? '+' : '') + formatNumber(comp.videos_growth)"></span>
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Bottom hover indicator -->
                <div class="absolute bottom-0 left-0 right-0 h-0.5 rounded-b-2xl gradient-brand opacity-0 group-hover:opacity-100 transition-opacity"></div>
            </div>
        </template>
    </div>

    <!-- DETAIL MODAL -->
    <div x-show="showDetail" x-cloak
         class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
         @click.self="closeDetail()" @keydown.escape.window="closeDetail()"
         x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0" x-transition:enter-end="opacity-100"
         x-transition:leave="transition ease-in duration-150" x-transition:leave-start="opacity-100" x-transition:leave-end="opacity-0">

        <div class="glass rounded-2xl w-full max-w-4xl max-h-[90vh] overflow-hidden flex flex-col" @click.stop
             x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 scale-95" x-transition:enter-end="opacity-100 scale-100">

            <!-- Modal Header -->
            <div class="p-5 border-b border-white/5 flex items-center justify-between flex-shrink-0">
                <div class="flex items-center gap-3" x-show="selectedCompetitor">
                    <div class="relative flex-shrink-0">
                        <img :src="selectedCompetitor?.avatar_url || ''" class="w-10 h-10 rounded-full object-cover ring-2 ring-white/10"
                             onerror="this.style.display='none'; this.nextElementSibling.style.display='flex'">
                        <div class="hidden w-10 h-10 rounded-full items-center justify-center text-white font-bold"
                             :class="selectedCompetitor?.platform === 'youtube' ? 'bg-red-500/80' : selectedCompetitor?.platform === 'instagram' ? 'bg-gradient-to-br from-purple-500 to-pink-500' : 'bg-gradient-to-br from-brand-400 to-accent-cyan'"
                             x-text="(selectedCompetitor?.display_name || selectedCompetitor?.username || '?')[0].toUpperCase()"></div>
                    </div>
                    <div>
                        <h3 class="font-bold text-white/90" x-text="selectedCompetitor?.display_name || selectedCompetitor?.username"></h3>
                        <p class="text-xs text-white/40" x-text="'@' + (selectedCompetitor?.username || '')"></p>
                    </div>
                    <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg text-[11px] font-semibold ml-2"
                          :class="'badge-' + (selectedCompetitor?.platform || '')"
                          x-text="platformLabel(selectedCompetitor?.platform)"></span>
                </div>
                <button @click="closeDetail()" class="p-1.5 rounded-lg hover:bg-white/10 transition flex-shrink-0">
                    <i data-lucide="x" class="w-5 h-5 text-white/60"></i>
                </button>
            </div>

            <!-- Tabs -->
            <div class="px-5 pt-3 pb-0 flex gap-2 border-b border-white/5 flex-shrink-0 overflow-x-auto">
                <button class="tab-btn pb-3 relative" :class="detailTab === 'growth' && 'active'" @click="detailTab = 'growth'">
                    <i data-lucide="trending-up" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Crescimento
                    <div x-show="detailTab === 'growth'" class="absolute bottom-0 left-0 right-0 h-0.5 gradient-brand rounded-full"></div>
                </button>
                <button class="tab-btn pb-3 relative" :class="detailTab === 'videos' && 'active'" @click="detailTab = 'videos'; loadVideos()">
                    <i data-lucide="video" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Videos
                    <div x-show="detailTab === 'videos'" class="absolute bottom-0 left-0 right-0 h-0.5 gradient-brand rounded-full"></div>
                </button>
                <button class="tab-btn pb-3 relative" :class="detailTab === 'analysis' && 'active'" @click="detailTab = 'analysis'; loadAnalysis()">
                    <i data-lucide="bar-chart-3" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Analise
                    <div x-show="detailTab === 'analysis'" class="absolute bottom-0 left-0 right-0 h-0.5 gradient-brand rounded-full"></div>
                </button>
                <button class="tab-btn pb-3 relative" :class="detailTab === 'ai' && 'active'" @click="detailTab = 'ai'">
                    <i data-lucide="sparkles" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> IA Intel
                    <div x-show="detailTab === 'ai'" class="absolute bottom-0 left-0 right-0 h-0.5 gradient-brand rounded-full"></div>
                </button>
                <button class="tab-btn pb-3 relative" :class="detailTab === 'revenue' && 'active'" @click="detailTab = 'revenue'; loadRevenue()">
                    <i data-lucide="dollar-sign" class="w-4 h-4 inline-block mr-1 -mt-0.5"></i> Receita
                    <div x-show="detailTab === 'revenue'" class="absolute bottom-0 left-0 right-0 h-0.5 gradient-brand rounded-full"></div>
                </button>
            </div>

            <!-- Modal Body -->
            <div class="flex-1 overflow-y-auto p-5">

                <!-- GROWTH TAB -->
                <div x-show="detailTab === 'growth'">
                    <!-- Growth Summary Cards -->
                    <div x-show="growthData && growthData.growth" x-transition class="grid grid-cols-1 md:grid-cols-3 gap-3 mb-6">
                        <div class="glass-light rounded-xl p-4">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-xs text-white/40 flex items-center gap-1"><i data-lucide="users" class="w-3.5 h-3.5"></i> Seguidores</span>
                                <span class="text-[10px] text-white/25" x-text="growthData?.growth?.period_days ? growthData.growth.period_days + ' dias' : ''"></span>
                            </div>
                            <div class="flex items-baseline gap-2">
                                <span class="text-xl font-bold"
                                      :class="(growthData?.growth?.followers_change || 0) >= 0 ? 'text-accent-green' : 'text-accent-red'"
                                      x-text="((growthData?.growth?.followers_change || 0) >= 0 ? '+' : '') + formatNumber(growthData?.growth?.followers_change || 0)"></span>
                                <span class="text-xs font-semibold px-1.5 py-0.5 rounded-md"
                                      :class="(growthData?.growth?.followers_pct || 0) >= 0 ? 'text-accent-green bg-green-500/10' : 'text-accent-red bg-red-500/10'"
                                      x-text="((growthData?.growth?.followers_pct || 0) >= 0 ? '+' : '') + (growthData?.growth?.followers_pct || 0).toFixed(1) + '%'"></span>
                            </div>
                        </div>
                        <div class="glass-light rounded-xl p-4">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-xs text-white/40 flex items-center gap-1"><i data-lucide="heart" class="w-3.5 h-3.5"></i> Likes</span>
                            </div>
                            <div class="flex items-baseline gap-2">
                                <span class="text-xl font-bold"
                                      :class="(growthData?.growth?.likes_change || 0) >= 0 ? 'text-accent-green' : 'text-accent-red'"
                                      x-text="((growthData?.growth?.likes_change || 0) >= 0 ? '+' : '') + formatNumber(growthData?.growth?.likes_change || 0)"></span>
                                <span class="text-xs font-semibold px-1.5 py-0.5 rounded-md"
                                      :class="(growthData?.growth?.likes_pct || 0) >= 0 ? 'text-accent-green bg-green-500/10' : 'text-accent-red bg-red-500/10'"
                                      x-text="((growthData?.growth?.likes_pct || 0) >= 0 ? '+' : '') + (growthData?.growth?.likes_pct || 0).toFixed(1) + '%'"></span>
                            </div>
                        </div>
                        <div class="glass-light rounded-xl p-4">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-xs text-white/40 flex items-center gap-1"><i data-lucide="play-circle" class="w-3.5 h-3.5"></i> Videos</span>
                            </div>
                            <div class="flex items-baseline gap-2">
                                <span class="text-xl font-bold"
                                      :class="(growthData?.growth?.videos_change || 0) >= 0 ? 'text-accent-green' : 'text-accent-red'"
                                      x-text="((growthData?.growth?.videos_change || 0) >= 0 ? '+' : '') + formatNumber(growthData?.growth?.videos_change || 0)"></span>
                                <span class="text-xs font-semibold px-1.5 py-0.5 rounded-md"
                                      :class="(growthData?.growth?.videos_pct || 0) >= 0 ? 'text-accent-green bg-green-500/10' : 'text-accent-red bg-red-500/10'"
                                      x-text="((growthData?.growth?.videos_pct || 0) >= 0 ? '+' : '') + (growthData?.growth?.videos_pct || 0).toFixed(1) + '%'"></span>
                            </div>
                        </div>
                    </div>

                    <!-- Chart Area -->
                    <div class="glass-light rounded-xl p-4">
                        <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 mb-4">
                            <h4 class="text-sm font-semibold text-white/70 flex items-center gap-2">
                                <i data-lucide="line-chart" class="w-4 h-4 text-brand-300"></i>
                                Historico de Crescimento
                            </h4>
                            <div class="flex gap-1 bg-dark-800/50 rounded-lg p-0.5">
                                <button class="text-[11px] py-1.5 px-3 rounded-md font-medium transition-all"
                                        :class="chartMetric === 'followers' ? 'bg-brand-500/20 text-brand-300' : 'text-white/40 hover:text-white/60'"
                                        @click="chartMetric = 'followers'; renderChart()">Seguidores</button>
                                <button class="text-[11px] py-1.5 px-3 rounded-md font-medium transition-all"
                                        :class="chartMetric === 'total_likes' ? 'bg-pink-500/20 text-accent-pink' : 'text-white/40 hover:text-white/60'"
                                        @click="chartMetric = 'total_likes'; renderChart()">Likes</button>
                                <button class="text-[11px] py-1.5 px-3 rounded-md font-medium transition-all"
                                        :class="chartMetric === 'video_count' ? 'bg-cyan-500/20 text-accent-cyan' : 'text-white/40 hover:text-white/60'"
                                        @click="chartMetric = 'video_count'; renderChart()">Videos</button>
                            </div>
                        </div>

                        <!-- Loading chart -->
                        <div x-show="loadingGrowth" class="flex items-center justify-center py-16">
                            <div class="flex flex-col items-center gap-3">
                                <svg class="animate-spin w-8 h-8 text-brand-400" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                                <span class="text-xs text-white/30">Carregando dados...</span>
                            </div>
                        </div>

                        <!-- Empty chart -->
                        <div x-show="!loadingGrowth && (!growthData?.snapshots || growthData.snapshots.length === 0)" class="text-center py-12">
                            <i data-lucide="bar-chart-3" class="w-12 h-12 text-white/10 mx-auto mb-3"></i>
                            <p class="text-sm text-white/30">Dados insuficientes para gerar o grafico</p>
                            <p class="text-xs text-white/20 mt-1">Os dados de crescimento aparecerao apos coletas ao longo do tempo</p>
                        </div>

                        <!-- Chart canvas -->
                        <div x-show="!loadingGrowth && growthData?.snapshots?.length > 0" class="relative" style="height: 300px;">
                            <canvas id="growthChart"></canvas>
                        </div>
                    </div>

                    <!-- Snapshots Table -->
                    <div x-show="growthData?.snapshots?.length > 0" x-transition class="glass-light rounded-xl p-4 mt-4">
                        <h4 class="text-sm font-semibold text-white/70 mb-3 flex items-center gap-2">
                            <i data-lucide="table" class="w-4 h-4 text-brand-300"></i>
                            Historico Detalhado
                        </h4>
                        <div class="overflow-x-auto">
                            <table class="w-full text-sm">
                                <thead>
                                    <tr class="text-white/40 text-xs border-b border-white/5">
                                        <th class="text-left py-2 px-3 font-medium">Data</th>
                                        <th class="text-right py-2 px-3 font-medium">Seguidores</th>
                                        <th class="text-right py-2 px-3 font-medium">Likes</th>
                                        <th class="text-right py-2 px-3 font-medium">Videos</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <template x-for="(snap, idx) in (growthData?.snapshots || []).slice().reverse().slice(0, 15)" :key="idx">
                                        <tr class="border-b border-white/3 hover:bg-white/3 transition">
                                            <td class="py-2 px-3 text-white/60" x-text="new Date(snap.captured_at).toLocaleDateString('pt-BR', { day:'2-digit', month:'2-digit', year:'numeric', hour:'2-digit', minute:'2-digit' })"></td>
                                            <td class="py-2 px-3 text-right text-white/80 font-medium" x-text="(snap.followers || 0).toLocaleString('pt-BR')"></td>
                                            <td class="py-2 px-3 text-right text-accent-pink font-medium" x-text="(snap.total_likes || 0).toLocaleString('pt-BR')"></td>
                                            <td class="py-2 px-3 text-right text-accent-cyan font-medium" x-text="(snap.video_count || 0).toLocaleString('pt-BR')"></td>
                                        </tr>
                                    </template>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- VIDEOS TAB -->
                <div x-show="detailTab === 'videos'">
                    <div x-show="loadingVideos" class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <template x-for="i in 4"><div class="glass-light rounded-xl overflow-hidden"><div class="skeleton w-full aspect-video"></div><div class="p-3"><div class="skeleton h-4 w-3/4 mb-2"></div><div class="skeleton h-3 w-1/2"></div></div></div></template>
                    </div>
                    <div x-show="!loadingVideos && competitorVideos.length === 0" class="text-center py-12">
                        <i data-lucide="video-off" class="w-12 h-12 text-white/10 mx-auto mb-3"></i>
                        <p class="text-sm text-white/30">Nenhum video encontrado</p>
                    </div>
                    <div x-show="!loadingVideos && competitorVideos.length > 0" class="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <template x-for="video in competitorVideos" :key="video.id || video.url">
                            <a :href="video.url || video.share_url || '#'" target="_blank" rel="noopener"
                               class="glass-light rounded-xl overflow-hidden group/vid hover:border-brand-400/30 transition-all block">
                                <div class="relative aspect-video bg-dark-800 overflow-hidden">
                                    <img :src="video.thumbnail_url || video.cover || ''" class="w-full h-full object-cover group-hover/vid:scale-105 transition-transform duration-500" :alt="video.title" onerror="this.style.display='none'">
                                    <div class="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent"></div>
                                    <div x-show="video.duration" class="absolute bottom-2 left-2"><span class="bg-black/70 backdrop-blur-sm text-white text-[10px] px-1.5 py-0.5 rounded font-medium" x-text="formatDuration(video.duration)"></span></div>
                                </div>
                                <div class="p-3">
                                    <h5 class="text-sm font-semibold text-white/80 line-clamp-2 mb-2 leading-snug" x-text="video.title || video.description || 'Sem titulo'" style="display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;"></h5>
                                    <div class="flex items-center gap-3 text-[11px] text-white/40">
                                        <span class="flex items-center gap-1"><i data-lucide="eye" class="w-3 h-3"></i><span x-text="formatNumber(video.views || video.play_count || 0)"></span></span>
                                        <span class="flex items-center gap-1"><i data-lucide="heart" class="w-3 h-3 text-accent-pink/60"></i><span x-text="formatNumber(video.likes || video.digg_count || 0)"></span></span>
                                        <span class="flex items-center gap-1"><i data-lucide="message-circle" class="w-3 h-3"></i><span x-text="formatNumber(video.comments || video.comment_count || 0)"></span></span>
                                    </div>
                                </div>
                            </a>
                        </template>
                    </div>
                </div>

                <!-- ANALYSIS TAB -->
                <div x-show="detailTab === 'analysis'">
                    <div x-show="loadingAnalysis" class="space-y-4">
                        <div class="skeleton h-32 w-full rounded-xl"></div>
                        <div class="skeleton h-48 w-full rounded-xl"></div>
                    </div>
                    <div x-show="!loadingAnalysis && analysisData" x-transition>
                        <!-- Cadence -->
                        <div class="glass-light rounded-xl p-4 mb-4">
                            <h4 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2"><i data-lucide="calendar-clock" class="w-4 h-4 text-brand-400"></i> Cadencia de Posts</h4>
                            <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                                <div class="text-center"><p class="text-lg font-bold text-brand-300" x-text="analysisData?.cadence?.posts_per_week || 0"></p><p class="text-[10px] text-white/40">Posts/semana</p></div>
                                <div class="text-center"><p class="text-lg font-bold text-white" x-text="analysisData?.cadence?.total_posts || 0"></p><p class="text-[10px] text-white/40">Total analisado</p></div>
                                <div class="text-center"><p class="text-sm font-bold text-accent-green" x-text="(analysisData?.cadence?.best_days || []).slice(0,2).join(', ') || '-'"></p><p class="text-[10px] text-white/40">Melhores dias</p></div>
                                <div class="text-center"><p class="text-sm font-bold text-accent-cyan" x-text="(analysisData?.cadence?.best_hours || []).map(h => h+'h').join(', ') || '-'"></p><p class="text-[10px] text-white/40">Melhores horas</p></div>
                            </div>
                        </div>
                        <!-- Content Formats -->
                        <div class="glass-light rounded-xl p-4 mb-4">
                            <h4 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2"><i data-lucide="layout-grid" class="w-4 h-4 text-accent-pink"></i> Formatos de Conteudo</h4>
                            <div class="grid grid-cols-3 gap-3 mb-2">
                                <div class="text-center glass-card rounded-xl p-3"><p class="text-lg font-bold text-accent-green" x-text="analysisData?.formats?.formats?.short || 0"></p><p class="text-[10px] text-white/40">Curto (&lt;15s)</p></div>
                                <div class="text-center glass-card rounded-xl p-3"><p class="text-lg font-bold text-brand-300" x-text="analysisData?.formats?.formats?.medium || 0"></p><p class="text-[10px] text-white/40">Medio (15-60s)</p></div>
                                <div class="text-center glass-card rounded-xl p-3"><p class="text-lg font-bold text-accent-orange" x-text="analysisData?.formats?.formats?.long || 0"></p><p class="text-[10px] text-white/40">Longo (&gt;60s)</p></div>
                            </div>
                            <p class="text-xs text-white/40 text-center">Duracao media: <span class="text-white/70" x-text="(analysisData?.formats?.avg_duration || 0) + 's'"></span></p>
                        </div>
                        <!-- Top Hashtags -->
                        <div class="glass-light rounded-xl p-4 mb-4">
                            <h4 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2"><i data-lucide="hash" class="w-4 h-4 text-accent-cyan"></i> Nuvem de Hashtags</h4>
                            <div class="flex flex-wrap gap-2">
                                <template x-for="tag in (analysisData?.hashtags?.top_hashtags || []).slice(0, 25)" :key="tag.tag">
                                    <span class="px-2.5 py-1 rounded-lg text-xs font-medium glass-card text-brand-300 cursor-default"
                                          :style="'font-size:' + Math.max(10, Math.min(18, 10 + tag.count * 2)) + 'px'"
                                          :title="'Views medio: ' + formatNumber(tag.avg_views || 0)"
                                          x-text="'#' + tag.tag + ' (' + tag.count + ')'"></span>
                                </template>
                            </div>
                            <p class="text-xs text-white/30 mt-3" x-text="'Total unico: ' + (analysisData?.hashtags?.total_unique_tags || 0) + ' | Media por post: ' + (analysisData?.hashtags?.avg_tags_per_post || 0)"></p>
                        </div>
                        <!-- Top Content -->
                        <div class="glass-light rounded-xl p-4">
                            <h4 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2"><i data-lucide="trophy" class="w-4 h-4 text-accent-orange"></i> Top Conteudo</h4>
                            <div class="space-y-2">
                                <template x-for="(item, idx) in (analysisData?.top_content || []).slice(0, 5)" :key="idx">
                                    <div class="flex items-center gap-3 glass-card rounded-xl p-3">
                                        <span class="text-lg font-bold text-white/20 w-6 text-center" x-text="idx + 1"></span>
                                        <img :src="item.thumbnail" class="w-16 h-10 rounded-lg object-cover bg-dark-800" onerror="this.style.display='none'">
                                        <div class="flex-1 min-w-0">
                                            <p class="text-xs text-white/70 truncate" x-text="item.title || 'Sem titulo'"></p>
                                            <div class="flex items-center gap-3 text-[10px] text-white/40 mt-1">
                                                <span x-text="formatNumber(item.views) + ' views'"></span>
                                                <span x-text="item.engagement_rate + '% eng'"></span>
                                                <span x-text="item.duration + 's'"></span>
                                            </div>
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- AI INTEL TAB -->
                <div x-show="detailTab === 'ai'">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-3 mb-4">
                        <button @click="generateAiReport()" :disabled="loadingAiReport" class="glass-card rounded-xl p-4 text-left hover:border-brand-400/30 transition group">
                            <div class="flex items-center gap-2 mb-2">
                                <div class="w-8 h-8 rounded-lg gradient-brand flex items-center justify-center"><i data-lucide="file-text" class="w-4 h-4"></i></div>
                                <span class="text-sm font-bold text-white/80">Relatorio IA</span>
                            </div>
                            <p class="text-[11px] text-white/40">Analise completa com pontos fortes, fracos e recomendacoes</p>
                            <span x-show="loadingAiReport" class="text-[10px] text-brand-300 mt-2 block animate-pulse">Gerando...</span>
                        </button>
                        <button @click="generateGapAnalysis()" :disabled="loadingGap" class="glass-card rounded-xl p-4 text-left hover:border-brand-400/30 transition group">
                            <div class="flex items-center gap-2 mb-2">
                                <div class="w-8 h-8 rounded-lg gradient-ocean flex items-center justify-center"><i data-lucide="git-compare" class="w-4 h-4"></i></div>
                                <span class="text-sm font-bold text-white/80">Gap Analysis</span>
                            </div>
                            <p class="text-[11px] text-white/40">Identifique lacunas entre voce e este concorrente</p>
                            <span x-show="loadingGap" class="text-[10px] text-brand-300 mt-2 block animate-pulse">Analisando...</span>
                        </button>
                        <button @click="generateViralReverse()" :disabled="loadingViral" class="glass-card rounded-xl p-4 text-left hover:border-brand-400/30 transition group">
                            <div class="flex items-center gap-2 mb-2">
                                <div class="w-8 h-8 rounded-lg gradient-fire flex items-center justify-center"><i data-lucide="flask-conical" class="w-4 h-4"></i></div>
                                <span class="text-sm font-bold text-white/80">Viral Reverse</span>
                            </div>
                            <p class="text-[11px] text-white/40">Engenharia reversa dos videos virais</p>
                            <span x-show="loadingViral" class="text-[10px] text-brand-300 mt-2 block animate-pulse">Decifrando...</span>
                        </button>
                    </div>
                    <!-- AI Report Result -->
                    <div x-show="aiReport" x-transition class="glass-light rounded-xl p-5 mb-4">
                        <h4 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2"><i data-lucide="sparkles" class="w-4 h-4 text-brand-400"></i> Relatorio IA</h4>
                        <div class="prose prose-invert prose-sm max-w-none text-white/70 text-sm leading-relaxed whitespace-pre-wrap" x-text="aiReport?.report || ''"></div>
                        <p class="text-[10px] text-white/20 mt-3" x-text="'Gerado em: ' + (aiReport?.generated_at || '')"></p>
                    </div>
                    <!-- Gap Analysis Result -->
                    <div x-show="gapData" x-transition class="glass-light rounded-xl p-5 mb-4">
                        <h4 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2"><i data-lucide="git-compare" class="w-4 h-4 text-accent-cyan"></i> Gap Analysis</h4>
                        <div class="prose prose-invert prose-sm max-w-none text-white/70 text-sm leading-relaxed whitespace-pre-wrap" x-text="gapData?.analysis || ''"></div>
                        <div x-show="gapData?.missing_hashtags?.length" class="mt-3">
                            <p class="text-xs text-white/50 mb-1">Hashtags que voce nao usa:</p>
                            <div class="flex flex-wrap gap-1">
                                <template x-for="tag in (gapData?.missing_hashtags || []).slice(0,15)">
                                    <span class="px-2 py-0.5 rounded text-[10px] bg-accent-cyan/10 text-accent-cyan" x-text="'#' + tag"></span>
                                </template>
                            </div>
                        </div>
                    </div>
                    <!-- Viral Reverse Result -->
                    <div x-show="viralData" x-transition class="glass-light rounded-xl p-5">
                        <h4 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2"><i data-lucide="flask-conical" class="w-4 h-4 text-accent-orange"></i> Engenharia Reversa Viral</h4>
                        <div class="prose prose-invert prose-sm max-w-none text-white/70 text-sm leading-relaxed whitespace-pre-wrap" x-text="viralData?.analysis || ''"></div>
                        <div class="flex gap-3 mt-3">
                            <span class="text-[10px] glass-card px-2 py-1 rounded" x-text="'Videos analisados: ' + (viralData?.top_videos_analyzed || 0)"></span>
                            <span class="text-[10px] glass-card px-2 py-1 rounded" x-text="'Views medio top: ' + formatNumber(viralData?.avg_views_top || 0)"></span>
                        </div>
                    </div>
                </div>

                <!-- REVENUE TAB -->
                <div x-show="detailTab === 'revenue'">
                    <div x-show="loadingRevenue" class="space-y-4"><div class="skeleton h-32 w-full rounded-xl"></div><div class="skeleton h-32 w-full rounded-xl"></div></div>
                    <div x-show="!loadingRevenue && revenueData" x-transition>
                        <div class="glass-light rounded-xl p-4 mb-4">
                            <h4 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2"><i data-lucide="badge-dollar-sign" class="w-4 h-4 text-accent-green"></i> Estimativa de Receita</h4>
                            <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                                <div class="text-center glass-card rounded-xl p-3">
                                    <p class="text-[10px] text-white/40 mb-1">Tier</p>
                                    <p class="text-lg font-bold text-brand-300 uppercase" x-text="revenueData?.tier || '-'"></p>
                                </div>
                                <div class="text-center glass-card rounded-xl p-3">
                                    <p class="text-[10px] text-white/40 mb-1">Views/mes</p>
                                    <p class="text-lg font-bold text-white" x-text="formatNumber(revenueData?.estimated_monthly_views || 0)"></p>
                                </div>
                                <div class="text-center glass-card rounded-xl p-3">
                                    <p class="text-[10px] text-white/40 mb-1">Posts/mes</p>
                                    <p class="text-lg font-bold text-accent-cyan" x-text="revenueData?.posts_per_month || 0"></p>
                                </div>
                                <div class="text-center glass-card rounded-xl p-3">
                                    <p class="text-[10px] text-white/40 mb-1">Views/video</p>
                                    <p class="text-lg font-bold text-accent-orange" x-text="formatNumber(revenueData?.avg_views_per_video || 0)"></p>
                                </div>
                            </div>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div class="glass-light rounded-xl p-4">
                                <h5 class="text-xs font-bold text-white/60 mb-3 flex items-center gap-1"><i data-lucide="tv" class="w-3.5 h-3.5"></i> Receita de Ads (mensal)</h5>
                                <div class="space-y-2">
                                    <div class="flex justify-between text-sm"><span class="text-white/50">Conservador</span><span class="text-white font-bold" x-text="'$' + (revenueData?.ad_revenue?.low || 0).toFixed(2)"></span></div>
                                    <div class="flex justify-between text-sm"><span class="text-white/50">Medio</span><span class="text-accent-green font-bold" x-text="'$' + (revenueData?.ad_revenue?.mid || 0).toFixed(2)"></span></div>
                                    <div class="flex justify-between text-sm"><span class="text-white/50">Otimista</span><span class="text-brand-300 font-bold" x-text="'$' + (revenueData?.ad_revenue?.high || 0).toFixed(2)"></span></div>
                                </div>
                            </div>
                            <div class="glass-light rounded-xl p-4">
                                <h5 class="text-xs font-bold text-white/60 mb-3 flex items-center gap-1"><i data-lucide="handshake" class="w-3.5 h-3.5"></i> Patrocinios (por post)</h5>
                                <div class="space-y-2">
                                    <div class="flex justify-between text-sm"><span class="text-white/50">Minimo</span><span class="text-white font-bold" x-text="'$' + formatNumber(revenueData?.sponsorship_per_post?.low || 0)"></span></div>
                                    <div class="flex justify-between text-sm"><span class="text-white/50">Maximo</span><span class="text-accent-green font-bold" x-text="'$' + formatNumber(revenueData?.sponsorship_per_post?.high || 0)"></span></div>
                                </div>
                                <div class="border-t border-white/5 mt-3 pt-3">
                                    <p class="text-[10px] text-white/40">Estimativa mensal com patrocinios:</p>
                                    <p class="text-sm font-bold text-brand-300" x-text="'$' + formatNumber(revenueData?.estimated_sponsored_monthly?.low || 0) + ' - $' + formatNumber(revenueData?.estimated_sponsored_monthly?.high || 0)"></p>
                                </div>
                            </div>
                        </div>
                        <p class="text-[10px] text-white/20 mt-3 text-center">Estimativas baseadas em metricas publicas. Valores reais podem variar.</p>
                    </div>
                </div>

            </div>
        </div>
    </div>

    <!-- COMPARE SECTION -->
    <div x-show="competitors.length >= 2" class="animate-fade-up mt-6">
        <div class="glass-card rounded-2xl p-5">
            <h3 class="text-lg font-bold text-white/90 mb-3 flex items-center gap-2">
                <div class="w-10 h-10 rounded-xl gradient-ocean flex items-center justify-center flex-shrink-0"><i data-lucide="git-compare" class="w-5 h-5"></i></div>
                Comparar Concorrentes
            </h3>
            <div class="flex flex-wrap gap-2 mb-4">
                <template x-for="comp in competitors" :key="comp.id">
                    <label class="flex items-center gap-2 glass-light rounded-xl px-3 py-2 cursor-pointer hover:border-brand-400/30 transition" :class="compareIds.includes(comp.id) && 'border-brand-400/40 bg-brand-500/10'">
                        <input type="checkbox" :value="comp.id" x-model.number="compareIds" class="rounded border-white/20 bg-dark-700 text-brand-500 focus:ring-brand-500">
                        <span class="text-sm text-white/70" x-text="comp.display_name || comp.username"></span>
                    </label>
                </template>
            </div>
            <button @click="compareSelected()" :disabled="compareIds.length < 2 || loadingCompare" class="px-4 py-2 rounded-xl gradient-brand text-white text-sm font-semibold disabled:opacity-50 transition">
                <span x-show="!loadingCompare">Comparar Selecionados</span>
                <span x-show="loadingCompare" class="animate-pulse">Comparando...</span>
            </button>
            <!-- Compare Results -->
            <div x-show="compareData" x-transition class="mt-4 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                <template x-for="comp in (compareData?.competitors || [])" :key="comp.id">
                    <div class="glass-light rounded-xl p-4">
                        <div class="flex items-center gap-2 mb-3">
                            <img :src="comp.avatar" class="w-8 h-8 rounded-full object-cover bg-dark-800" onerror="this.style.display='none'">
                            <div>
                                <p class="text-sm font-bold text-white/80" x-text="comp.display_name || comp.username"></p>
                                <span class="text-[10px] px-1.5 py-0.5 rounded" :class="'badge-' + comp.platform" x-text="platformLabel(comp.platform)"></span>
                            </div>
                        </div>
                        <div class="space-y-1.5">
                            <div class="flex justify-between text-xs"><span class="text-white/40">Seguidores</span><span class="text-white font-bold" x-text="formatNumber(comp.followers)"></span></div>
                            <div class="flex justify-between text-xs"><span class="text-white/40">Likes</span><span class="text-accent-pink font-bold" x-text="formatNumber(comp.total_likes)"></span></div>
                            <div class="flex justify-between text-xs"><span class="text-white/40">Videos</span><span class="text-white/70" x-text="comp.video_count"></span></div>
                            <div class="flex justify-between text-xs"><span class="text-white/40">Crescimento</span><span class="font-bold" :class="comp.growth_percent >= 0 ? 'text-accent-green' : 'text-accent-red'" x-text="(comp.growth_percent >= 0 ? '+' : '') + comp.growth_percent + '%'"></span></div>
                        </div>
                    </div>
                </template>
            </div>
        </div>
    </div>

</div>
{% endblock %}

{% block scripts %}
<script>
function competitorsSpy() {
    return {
        // State
        competitors: [],
        loading: true,
        newPlatform: 'tiktok',
        newUsername: '',
        addingCompetitor: false,

        // Detail modal
        showDetail: false,
        selectedCompetitor: null,
        detailTab: 'growth',
        growthData: null,
        loadingGrowth: false,
        competitorVideos: [],
        loadingVideos: false,

        // Analysis
        analysisData: null,
        loadingAnalysis: false,

        // AI Intel
        aiReport: null,
        loadingAiReport: false,
        gapData: null,
        loadingGap: false,
        viralData: null,
        loadingViral: false,

        // Revenue
        revenueData: null,
        loadingRevenue: false,

        // Compare
        compareIds: [],
        compareData: null,
        loadingCompare: false,
        chartMetric: 'followers',
        growthChartInstance: null,

        // Computed
        get totalFollowers() {
            return this.competitors.reduce((s, c) => s + (c.followers || 0), 0);
        },
        get totalLikes() {
            return this.competitors.reduce((s, c) => s + (c.total_likes || 0), 0);
        },
        get totalVideos() {
            return this.competitors.reduce((s, c) => s + (c.video_count || 0), 0);
        },

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

        async loadCompetitors() {
            this.loading = true;
            try {
                const res = await fetch('/api/competitors/');
                if (!res.ok) throw new Error('Falha ao carregar');
                const data = await res.json();
                this.competitors = data.competitors || data || [];
            } catch (e) {
                console.error(e);
                showToast('Erro ao carregar concorrentes', 'error');
                this.competitors = [];
            } finally {
                this.loading = false;
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            }
        },

        async addCompetitor() {
            if (!this.newUsername.trim() || this.addingCompetitor) return;
            this.addingCompetitor = true;
            try {
                const res = await fetch('/api/competitors/add', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        platform: this.newPlatform,
                        username: this.newUsername.trim().replace(/^@/, '')
                    })
                });
                if (!res.ok) {
                    const err = await res.json().catch(() => ({}));
                    throw new Error(err.detail || 'Falha ao adicionar');
                }
                const data = await res.json();
                this.competitors.push(data);
                this.newUsername = '';
                showToast('Concorrente adicionado com sucesso!', 'success');
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            } catch (e) {
                showToast(e.message || 'Erro ao adicionar concorrente', 'error');
            } finally {
                this.addingCompetitor = false;
            }
        },

        async deleteCompetitor(comp) {
            if (!confirm(`Remover @${comp.username} da lista de concorrentes?`)) return;
            try {
                const res = await fetch(`/api/competitors/${comp.id}`, { method: 'DELETE' });
                if (!res.ok) throw new Error('Falha ao remover');
                this.competitors = this.competitors.filter(c => c.id !== comp.id);
                showToast('Concorrente removido', 'info');
            } catch (e) {
                showToast('Erro ao remover concorrente', 'error');
            }
        },

        async refreshCompetitor(comp) {
            comp._refreshing = true;
            showToast(`Atualizando @${comp.username}...`, 'info');
            try {
                const res = await fetch(`/api/competitors/${comp.id}/refresh`, { method: 'POST' });
                if (!res.ok) throw new Error('Falha ao atualizar');
                const updated = await res.json();
                const idx = this.competitors.findIndex(c => c.id === comp.id);
                if (idx !== -1) {
                    this.competitors[idx] = { ...updated, _refreshing: false };
                }
                showToast(`@${comp.username} atualizado!`, 'success');
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            } catch (e) {
                comp._refreshing = false;
                showToast('Erro ao atualizar dados', 'error');
            }
        },

        async openDetail(comp) {
            this.selectedCompetitor = comp;
            this.detailTab = 'growth';
            this.showDetail = true;
            this.growthData = null;
            this.competitorVideos = [];
            this.chartMetric = 'followers';
            this.analysisData = null;
            this.aiReport = null;
            this.gapData = null;
            this.viralData = null;
            this.revenueData = null;
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            await this.loadGrowth();
        },

        closeDetail() {
            this.showDetail = false;
            this.selectedCompetitor = null;
            if (this.growthChartInstance) {
                this.growthChartInstance.destroy();
                this.growthChartInstance = null;
            }
        },

        async loadGrowth() {
            if (!this.selectedCompetitor) return;
            this.loadingGrowth = true;
            try {
                const res = await fetch(`/api/competitors/${this.selectedCompetitor.id}/growth`);
                if (!res.ok) throw new Error('Falha');
                this.growthData = await res.json();
                this.$nextTick(() => {
                    this.renderChart();
                    if (window.lucide) lucide.createIcons();
                });
            } catch (e) {
                console.error(e);
                this.growthData = { snapshots: [], growth: {} };
            } finally {
                this.loadingGrowth = false;
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            }
        },

        async loadVideos() {
            if (!this.selectedCompetitor || this.competitorVideos.length > 0) return;
            this.loadingVideos = true;
            try {
                const res = await fetch(`/api/competitors/${this.selectedCompetitor.id}/videos`);
                if (!res.ok) throw new Error('Falha');
                const data = await res.json();
                this.competitorVideos = data.videos || data || [];
            } catch (e) {
                console.error(e);
                this.competitorVideos = [];
            } finally {
                this.loadingVideos = false;
                this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
            }
        },

        renderChart() {
            if (!this.growthData?.snapshots?.length) return;

            const canvas = document.getElementById('growthChart');
            if (!canvas) return;

            if (this.growthChartInstance) {
                this.growthChartInstance.destroy();
                this.growthChartInstance = null;
            }

            const snapshots = this.growthData.snapshots;
            const labels = snapshots.map(s => {
                const d = new Date(s.captured_at);
                return d.toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' });
            });
            const dataPoints = snapshots.map(s => s[this.chartMetric] || 0);

            const metricConfig = {
                followers: {
                    border: '#a78bfa',
                    bg: 'rgba(167,139,250,0.15)',
                    gradient: ['rgba(167,139,250,0.3)', 'rgba(167,139,250,0)'],
                    label: 'Seguidores'
                },
                total_likes: {
                    border: '#ec4899',
                    bg: 'rgba(236,72,153,0.15)',
                    gradient: ['rgba(236,72,153,0.3)', 'rgba(236,72,153,0)'],
                    label: 'Likes'
                },
                video_count: {
                    border: '#06b6d4',
                    bg: 'rgba(6,182,212,0.15)',
                    gradient: ['rgba(6,182,212,0.3)', 'rgba(6,182,212,0)'],
                    label: 'Videos'
                }
            };

            const config = metricConfig[this.chartMetric] || metricConfig.followers;

            // Create gradient fill
            const ctx = canvas.getContext('2d');
            const gradient = ctx.createLinearGradient(0, 0, 0, 280);
            gradient.addColorStop(0, config.gradient[0]);
            gradient.addColorStop(1, config.gradient[1]);

            this.growthChartInstance = new Chart(canvas, {
                type: 'line',
                data: {
                    labels,
                    datasets: [{
                        label: config.label,
                        data: dataPoints,
                        borderColor: config.border,
                        backgroundColor: gradient,
                        borderWidth: 2.5,
                        fill: true,
                        tension: 0.4,
                        pointBackgroundColor: config.border,
                        pointBorderColor: 'rgba(15,10,30,0.9)',
                        pointBorderWidth: 2,
                        pointRadius: dataPoints.length > 30 ? 0 : 4,
                        pointHoverRadius: 6,
                        pointHoverBackgroundColor: '#fff',
                        pointHoverBorderColor: config.border,
                        pointHoverBorderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    interaction: { intersect: false, mode: 'index' },
                    animation: { duration: 800, easing: 'easeOutQuart' },
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            backgroundColor: 'rgba(15,10,30,0.95)',
                            borderColor: 'rgba(124,58,237,0.3)',
                            borderWidth: 1,
                            titleColor: '#fff',
                            titleFont: { weight: '600', size: 12 },
                            bodyColor: 'rgba(255,255,255,0.7)',
                            bodyFont: { size: 13 },
                            cornerRadius: 10,
                            padding: 12,
                            displayColors: false,
                            callbacks: {
                                label: function(ctx) {
                                    return config.label + ': ' + (ctx.parsed.y || 0).toLocaleString('pt-BR');
                                }
                            }
                        }
                    },
                    scales: {
                        x: {
                            grid: { color: 'rgba(255,255,255,0.03)', drawBorder: false },
                            ticks: {
                                color: 'rgba(255,255,255,0.3)',
                                font: { size: 11 },
                                maxRotation: 0,
                                maxTicksLimit: 10
                            }
                        },
                        y: {
                            grid: { color: 'rgba(255,255,255,0.03)', drawBorder: false },
                            ticks: {
                                color: 'rgba(255,255,255,0.3)',
                                font: { size: 11 },
                                maxTicksLimit: 6,
                                callback: function(v) {
                                    if (v >= 1e9) return (v / 1e9).toFixed(1) + 'B';
                                    if (v >= 1e6) return (v / 1e6).toFixed(1) + 'M';
                                    if (v >= 1e3) return (v / 1e3).toFixed(1) + 'K';
                                    return v.toLocaleString('pt-BR');
                                }
                            }
                        }
                    }
                }
            });
        },

        // Analysis
        async loadAnalysis() {
            if (!this.selectedCompetitor || this.loadingAnalysis) return;
            if (this.analysisData) return;
            this.loadingAnalysis = true;
            try {
                const r = await fetch(`/api/competitors/${this.selectedCompetitor.id}/analysis`);
                this.analysisData = await r.json();
            } catch(e) { showToast('Erro ao carregar analise', 'error'); }
            this.loadingAnalysis = false;
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        // AI Intel
        async generateAiReport() {
            if (!this.selectedCompetitor || this.loadingAiReport) return;
            this.loadingAiReport = true;
            showToast('Gerando relatorio IA... pode demorar 30s', 'info');
            try {
                const r = await fetch(`/api/competitors/${this.selectedCompetitor.id}/ai-report`);
                this.aiReport = await r.json();
                showToast('Relatorio IA gerado!', 'success');
            } catch(e) { showToast('Erro ao gerar relatorio', 'error'); }
            this.loadingAiReport = false;
        },

        async generateGapAnalysis() {
            if (!this.selectedCompetitor || this.loadingGap) return;
            this.loadingGap = true;
            showToast('Analisando gaps... pode demorar 30s', 'info');
            try {
                const r = await fetch(`/api/competitors/${this.selectedCompetitor.id}/gap-analysis`);
                this.gapData = await r.json();
                showToast('Gap analysis concluida!', 'success');
            } catch(e) { showToast('Erro ao gerar gap analysis', 'error'); }
            this.loadingGap = false;
        },

        async generateViralReverse() {
            if (!this.selectedCompetitor || this.loadingViral) return;
            this.loadingViral = true;
            showToast('Decifrando padroes virais... pode demorar 30s', 'info');
            try {
                const r = await fetch(`/api/competitors/${this.selectedCompetitor.id}/viral-reverse`);
                this.viralData = await r.json();
                showToast('Engenharia reversa concluida!', 'success');
            } catch(e) { showToast('Erro ao analisar videos virais', 'error'); }
            this.loadingViral = false;
        },

        // Revenue
        async loadRevenue() {
            if (!this.selectedCompetitor || this.loadingRevenue) return;
            if (this.revenueData) return;
            this.loadingRevenue = true;
            try {
                const r = await fetch(`/api/competitors/${this.selectedCompetitor.id}/revenue`);
                this.revenueData = await r.json();
            } catch(e) { showToast('Erro ao estimar receita', 'error'); }
            this.loadingRevenue = false;
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        // Compare
        async compareSelected() {
            if (this.compareIds.length < 2 || this.loadingCompare) return;
            this.loadingCompare = true;
            try {
                const r = await fetch('/api/competitors/compare', {
                    method: 'POST', headers: {'Content-Type':'application/json'},
                    body: JSON.stringify({ competitor_ids: this.compareIds })
                });
                this.compareData = await r.json();
            } catch(e) { showToast('Erro ao comparar', 'error'); }
            this.loadingCompare = false;
            this.$nextTick(() => { if(window.lucide) lucide.createIcons(); });
        },

        // Helpers
        platformLabel(platform) {
            return { youtube: 'YouTube', tiktok: 'TikTok', instagram: 'Instagram' }[(platform || '').toLowerCase()] || platform;
        }
    };
}
</script>
{% endblock %}
