{% extends "base.html" %}
{% block title %}TikTok Shop Intelligence - Viral Social Pro{% endblock %}
{% block nav_shop %}active{% endblock %}
{% block page_title %}TikTok Shop Brasil{% endblock %}
{% block page_subtitle %}Inteligencia de produtos virais, revenue tracking e deteccao cross-platform{% endblock %}

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

    <!-- Tabs -->
    <div class="flex gap-2 mb-6 overflow-x-auto animate-fade-up pb-1">
        <button @click="activeTab = 'ranking'; loadRanking()" :class="activeTab === 'ranking' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="crown" class="w-4 h-4"></i> Top Produtos
        </button>
        <button @click="activeTab = 'top_sellers'; loadTopSellers()" :class="activeTab === 'top_sellers' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="store" class="w-4 h-4"></i> Top Lojas
        </button>
        <button @click="activeTab = 'top_creators'; loadTopCreators()" :class="activeTab === 'top_creators' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="users" class="w-4 h-4"></i> Top Creators
        </button>
        <button @click="activeTab = 'top_videos'; loadTopVideos()" :class="activeTab === 'top_videos' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="play-circle" class="w-4 h-4"></i> Top Videos
        </button>
        <button @click="activeTab = 'search'" :class="activeTab === 'search' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="search" class="w-4 h-4"></i> Buscar
        </button>
        <button @click="activeTab = 'spy_store'" :class="activeTab === 'spy_store' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="eye" class="w-4 h-4"></i> Espiar Loja
        </button>
        <button @click="activeTab = 'product_detail'" :class="activeTab === 'product_detail' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="package-search" class="w-4 h-4"></i> Detalhe Produto
        </button>
        <button @click="activeTab = 'trends_chart'; loadTrendsChart()" :class="activeTab === 'trends_chart' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="trending-up" class="w-4 h-4"></i> Tendencias BR
        </button>
        <button @click="activeTab = 'viral_videos'; loadViralVideos()" :class="activeTab === 'viral_videos' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="flame" class="w-4 h-4"></i> Videos Virais
            <span x-show="viralVideosTotal > 0" class="px-1.5 py-0.5 text-[10px] rounded-full gradient-fire" x-text="viralVideosTotal"></span>
        </button>
        <button @click="activeTab = 'reports'; loadReports()" :class="activeTab === 'reports' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="bar-chart-3" class="w-4 h-4"></i> Relatorios
        </button>
        <button @click="activeTab = 'analytics'; loadAnalytics()" :class="activeTab === 'analytics' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="brain" class="w-4 h-4"></i> Analise IA
        </button>
        <button @click="activeTab = 'affiliates'; loadAffiliates()" :class="activeTab === 'affiliates' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="network" class="w-4 h-4"></i> Afiliados
        </button>
        <button @click="activeTab = 'calculator'" :class="activeTab === 'calculator' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="calculator" class="w-4 h-4"></i> Calculadora
        </button>
        <button @click="activeTab = 'store_revenue'; loadStoreRevenue()" :class="activeTab === 'store_revenue' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="building-2" class="w-4 h-4"></i> Receita Lojas
        </button>
        <button @click="activeTab = 'matcher'; loadMatcher()" :class="activeTab === 'matcher' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="link-2" class="w-4 h-4"></i> Matcher
        </button>
        <button @click="activeTab = 'optimizer'; loadOptimizer()" :class="activeTab === 'optimizer' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="target" class="w-4 h-4"></i> Otimizador
        </button>
        <button @click="activeTab = 'seasonal'; loadSeasonal()" :class="activeTab === 'seasonal' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="calendar" class="w-4 h-4"></i> Sazonal
        </button>
        <button @click="activeTab = 'viral_predictor'; loadViralPredictor()" :class="activeTab === 'viral_predictor' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="rocket" class="w-4 h-4"></i> Preditor Viral
        </button>
        <button @click="activeTab = 'scripts'; " :class="activeTab === 'scripts' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="file-text" class="w-4 h-4"></i> Scripts Produto
        </button>
        <button @click="activeTab = 'live_planner'; " :class="activeTab === 'live_planner' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="radio" class="w-4 h-4"></i> Live Planner
        </button>
    </div>

    <!-- Cache Status Banner -->
    <div x-show="cacheStatus && cacheStatus.fresh === 0 && !loading" class="glass rounded-2xl p-4 mb-4 animate-fade-up border border-yellow-500/20">
        <div class="flex items-center justify-between flex-wrap gap-3">
            <div class="flex items-center gap-3">
                <i data-lucide="alert-triangle" class="w-5 h-5 text-yellow-400"></i>
                <div>
                    <p class="text-sm font-semibold text-yellow-300">Cache vazio - Dados nao carregados</p>
                    <p class="text-xs text-white/40">Sincronize para buscar dados do TikTok Shop via Apify.</p>
                </div>
            </div>
            <button @click="syncEchotik()" :disabled="syncing" class="px-4 py-2 rounded-xl gradient-brand text-white font-medium text-xs hover:opacity-90 transition flex items-center gap-2 disabled:opacity-50">
                <div x-show="syncing" class="w-3.5 h-3.5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                <i x-show="!syncing" data-lucide="refresh-cw" class="w-3.5 h-3.5"></i>
                <span x-text="syncing ? 'Sincronizando...' : 'Sincronizar Agora'"></span>
            </button>
        </div>
    </div>

    <!-- Loading -->
    <div x-show="loading" class="text-center py-12">
        <div class="inline-flex items-center gap-3 glass rounded-2xl px-6 py-4">
            <div class="w-5 h-5 border-2 border-brand-400 border-t-transparent rounded-full animate-spin"></div>
            <span class="text-white/60 text-sm" x-text="loadingMsg || 'Buscando...'"></span>
        </div>
    </div>

    <!-- ═══════════ TOP PRODUTOS (Apify Rankings) ═══════════ -->
    <div x-show="activeTab === 'ranking'" x-cloak>
        <div class="glass rounded-2xl p-4 mb-6 animate-fade-up">
            <div class="flex flex-wrap items-center gap-3">
                <h3 class="text-sm font-bold text-white/80 flex items-center gap-2">
                    <i data-lucide="crown" class="w-4 h-4 text-yellow-400"></i> Ranking Produtos Mais Vendidos BR
                </h3>
                <div class="flex items-center gap-1 bg-white/5 rounded-xl p-0.5 ml-auto">
                    <button @click="rankField = 1; loadRanking()" class="px-3 py-1.5 rounded-lg text-xs font-semibold transition"
                        :class="rankField === 1 ? 'gradient-brand text-white' : 'text-white/40 hover:text-white/70'">Vendas</button>
                    <button @click="rankField = 2; loadRanking()" class="px-3 py-1.5 rounded-lg text-xs font-semibold transition"
                        :class="rankField === 2 ? 'gradient-brand text-white' : 'text-white/40 hover:text-white/70'">Faturamento</button>
                </div>
                <p class="text-xs text-white/30"><span class="text-white font-semibold" x-text="rankProducts.length"></span> produtos</p>
            </div>
        </div>

        <div x-show="rankLoading" class="text-center py-12">
            <div class="inline-flex items-center gap-3 glass rounded-2xl px-6 py-4">
                <div class="w-5 h-5 border-2 border-yellow-400 border-t-transparent rounded-full animate-spin"></div>
                <span class="text-white/60 text-sm">Carregando ranking EchoTik...</span>
            </div>
        </div>

        <div x-show="!rankLoading" class="space-y-3">
            <template x-for="(p, idx) in rankProducts" :key="p.product_id">
                <div class="glass-card rounded-2xl p-4 hover:bg-white/5 transition cursor-pointer" @click="openProductDetail(p.product_id)">
                    <div class="flex items-center gap-4">
                        <!-- Rank -->
                        <div class="w-10 h-10 rounded-xl flex items-center justify-center text-sm font-black flex-shrink-0"
                             :class="idx < 3 ? 'gradient-fire text-white' : 'glass text-white/50'"
                             x-text="'#' + (idx + 1)"></div>
                        <!-- Image -->
                        <div class="w-16 h-16 rounded-xl bg-dark-800 overflow-hidden flex-shrink-0">
                            <img :src="p.image" class="w-full h-full object-cover" loading="lazy" onerror="this.style.display='none'">
                        </div>
                        <!-- Info -->
                        <div class="flex-1 min-w-0">
                            <h4 class="text-sm font-semibold text-white/90 line-clamp-1" x-text="p.title"></h4>
                            <div class="flex items-center gap-3 mt-1 text-xs text-white/40">
                                <span x-text="p.price_formatted" class="text-accent-green font-bold"></span>
                                <span x-show="p.commission_pct" class="text-accent-cyan" x-text="'Comissao: ' + p.commission_pct"></span>
                                <span x-show="p.rating > 0" class="text-yellow-400" x-text="p.rating.toFixed(1) + ' ★'"></span>
                            </div>
                        </div>
                        <!-- Stats -->
                        <div class="hidden md:grid grid-cols-4 gap-4 flex-shrink-0">
                            <div class="text-center">
                                <p class="text-sm font-bold text-white" x-text="p.sales_formatted"></p>
                                <p class="text-[10px] text-white/30">Vendas</p>
                            </div>
                            <div class="text-center">
                                <p class="text-sm font-bold text-accent-green" x-text="p.gmv_formatted"></p>
                                <p class="text-[10px] text-white/30">Faturamento</p>
                            </div>
                            <div class="text-center">
                                <p class="text-sm font-bold text-brand-300" x-text="p.influencer_count"></p>
                                <p class="text-[10px] text-white/30">Creators</p>
                            </div>
                            <div class="text-center">
                                <p class="text-sm font-bold text-accent-cyan" x-text="p.video_count"></p>
                                <p class="text-[10px] text-white/30">Videos</p>
                            </div>
                        </div>
                        <!-- Mobile stats -->
                        <div class="md:hidden flex flex-col items-end gap-0.5 flex-shrink-0">
                            <span class="text-xs font-bold text-white" x-text="p.sales_formatted + ' vendas'"></span>
                            <span class="text-xs font-bold text-accent-green" x-text="p.gmv_formatted"></span>
                        </div>
                    </div>
                </div>
            </template>
        </div>

        <div x-show="!rankLoading && rankProducts.length === 0" class="text-center py-16">
            <i data-lucide="crown" class="w-12 h-12 text-white/10 mx-auto mb-4"></i>
            <p class="text-white/40 text-sm mb-3">Nenhum produto no ranking</p>
            <p class="text-xs text-white/25 mb-3">Clique em Sincronizar para carregar dados da EchoTik API</p>
            <button @click="syncEchotik()" :disabled="syncing" class="px-4 py-2 rounded-xl gradient-brand text-white font-medium text-xs">
                <span x-text="syncing ? 'Sincronizando...' : 'Sincronizar Agora'"></span>
            </button>
        </div>
    </div>

    <!-- ═══════════ TOP LOJAS (EchoTik) ═══════════ -->
    <div x-show="activeTab === 'top_sellers'" x-cloak>
        <div class="glass rounded-2xl p-4 mb-6 animate-fade-up">
            <div class="flex flex-wrap items-center gap-3">
                <h3 class="text-sm font-bold text-white/80 flex items-center gap-2">
                    <i data-lucide="store" class="w-4 h-4 text-brand-400"></i> Top Lojas TikTok Shop BR
                </h3>
                <div class="flex items-center gap-1 bg-white/5 rounded-xl p-0.5 ml-auto">
                    <button @click="sellerRankField = 1; loadTopSellers()" class="px-3 py-1.5 rounded-lg text-xs font-semibold transition"
                        :class="sellerRankField === 1 ? 'gradient-brand text-white' : 'text-white/40'">Vendas</button>
                    <button @click="sellerRankField = 2; loadTopSellers()" class="px-3 py-1.5 rounded-lg text-xs font-semibold transition"
                        :class="sellerRankField === 2 ? 'gradient-brand text-white' : 'text-white/40'">Faturamento</button>
                </div>
            </div>
        </div>

        <div x-show="sellerLoading" class="text-center py-12">
            <div class="w-5 h-5 border-2 border-brand-400 border-t-transparent rounded-full animate-spin mx-auto"></div>
        </div>

        <div x-show="!sellerLoading" class="space-y-3">
            <template x-for="(s, idx) in topSellers" :key="s.seller_id">
                <div class="glass-card rounded-2xl p-4 hover:bg-white/5 transition cursor-pointer" @click="openSellerDetail(s.seller_id)">
                    <div class="flex items-center gap-4">
                        <div class="w-10 h-10 rounded-xl flex items-center justify-center text-sm font-black flex-shrink-0"
                             :class="idx < 3 ? 'gradient-fire text-white' : 'glass text-white/50'"
                             x-text="'#' + (idx + 1)"></div>
                        <div class="w-12 h-12 rounded-xl bg-dark-800 overflow-hidden flex-shrink-0">
                            <img :src="s.logo" class="w-full h-full object-cover" onerror="this.style.display='none'">
                        </div>
                        <div class="flex-1 min-w-0">
                            <h4 class="text-sm font-semibold text-white/90" x-text="s.name"></h4>
                            <p class="text-xs text-white/40 mt-0.5" x-text="s.category"></p>
                        </div>
                        <div class="hidden md:grid grid-cols-4 gap-4 flex-shrink-0">
                            <div class="text-center">
                                <p class="text-sm font-bold text-white" x-text="s.sales_formatted"></p>
                                <p class="text-[10px] text-white/30">Vendas</p>
                            </div>
                            <div class="text-center">
                                <p class="text-sm font-bold text-accent-green" x-text="s.gmv_formatted"></p>
                                <p class="text-[10px] text-white/30">Faturamento</p>
                            </div>
                            <div class="text-center">
                                <p class="text-sm font-bold text-brand-300" x-text="s.product_count"></p>
                                <p class="text-[10px] text-white/30">Produtos</p>
                            </div>
                            <div class="text-center">
                                <p class="text-sm font-bold text-accent-cyan" x-text="s.influencer_count"></p>
                                <p class="text-[10px] text-white/30">Creators</p>
                            </div>
                        </div>
                        <div class="md:hidden flex flex-col items-end gap-0.5">
                            <span class="text-xs font-bold text-white" x-text="s.sales_formatted + ' vendas'"></span>
                            <span class="text-xs font-bold text-accent-green" x-text="s.gmv_formatted"></span>
                        </div>
                    </div>
                </div>
            </template>
        </div>
        <div x-show="!sellerLoading && topSellers.length === 0" class="text-center py-16">
            <i data-lucide="store" class="w-12 h-12 text-white/10 mx-auto mb-4"></i>
            <p class="text-white/40 text-sm">Nenhuma loja no ranking. Clique em Sincronizar acima para carregar dados.</p>
        </div>
    </div>

    <!-- ═══════════ TOP CREATORS (Dados Locais BR) ═══════════ -->
    <div x-show="activeTab === 'top_creators'" x-cloak>
        <div class="glass rounded-2xl p-4 mb-6 animate-fade-up">
            <div class="flex flex-wrap items-center gap-3">
                <h3 class="text-sm font-bold text-white/80 flex items-center gap-2">
                    <i data-lucide="users" class="w-4 h-4 text-accent-pink"></i> Top Creators Brasil
                    <span class="text-[10px] text-white/30 font-normal ml-1">Dados do scanner local</span>
                </h3>
                <!-- Rank Field -->
                <div class="flex items-center gap-1 bg-white/5 rounded-xl p-0.5">
                    <button @click="creatorRankField = 1; loadTopCreators()" class="px-2.5 py-1 rounded-lg text-[11px] font-semibold transition"
                        :class="creatorRankField === 1 ? 'gradient-brand text-white' : 'text-white/40'">Views</button>
                    <button @click="creatorRankField = 2; loadTopCreators()" class="px-2.5 py-1 rounded-lg text-[11px] font-semibold transition"
                        :class="creatorRankField === 2 ? 'gradient-brand text-white' : 'text-white/40'">Virais</button>
                    <button @click="creatorRankField = 3; loadTopCreators()" class="px-2.5 py-1 rounded-lg text-[11px] font-semibold transition"
                        :class="creatorRankField === 3 ? 'gradient-brand text-white' : 'text-white/40'">Engajamento</button>
                </div>
                <!-- Days Filter -->
                <div class="flex items-center gap-1 bg-white/5 rounded-xl p-0.5 ml-auto">
                    <template x-for="d in [7, 15, 30, 60, 90]" :key="d">
                        <button @click="creatorDays = d; loadTopCreators()" class="px-2.5 py-1 rounded-lg text-[11px] font-semibold transition"
                            :class="creatorDays === d ? 'gradient-fire text-white' : 'text-white/40'" x-text="d + 'd'"></button>
                    </template>
                </div>
            </div>
        </div>

        <div x-show="creatorLoading" class="text-center py-12">
            <div class="w-5 h-5 border-2 border-accent-pink border-t-transparent rounded-full animate-spin mx-auto"></div>
        </div>

        <div x-show="!creatorLoading" class="space-y-3">
            <template x-for="(c, idx) in topCreators" :key="c.user_id">
                <div class="glass-card rounded-2xl p-4">
                    <div class="flex items-center gap-4">
                        <div class="w-10 h-10 rounded-xl flex items-center justify-center text-sm font-black flex-shrink-0"
                             :class="idx < 3 ? 'gradient-fire text-white' : 'glass text-white/50'"
                             x-text="'#' + (idx + 1)"></div>
                        <div class="w-12 h-12 rounded-full bg-dark-800 overflow-hidden flex-shrink-0">
                            <img :src="c.avatar" class="w-full h-full object-cover" onerror="this.style.display='none'">
                        </div>
                        <div class="flex-1 min-w-0">
                            <h4 class="text-sm font-semibold text-white/90" x-text="c.nickname"></h4>
                            <p class="text-xs text-white/40" x-text="'@' + c.username + (c.category ? ' • ' + c.category : '')"></p>
                        </div>
                        <div class="hidden md:grid grid-cols-5 gap-3 flex-shrink-0">
                            <div class="text-center">
                                <p class="text-sm font-bold text-brand-300" x-text="c.followers_formatted"></p>
                                <p class="text-[10px] text-white/30">Seguidores</p>
                            </div>
                            <div class="text-center">
                                <p class="text-sm font-bold text-white" x-text="c.total_views_formatted || formatNumber(c.total_views || 0)"></p>
                                <p class="text-[10px] text-white/30">Views BR</p>
                            </div>
                            <div class="text-center">
                                <p class="text-sm font-bold text-accent-orange" x-text="c.viral_count || 0"></p>
                                <p class="text-[10px] text-white/30">Virais</p>
                            </div>
                            <div class="text-center">
                                <p class="text-sm font-bold text-accent-green" x-text="c.shop_video_count || 0"></p>
                                <p class="text-[10px] text-white/30">Com Produto</p>
                            </div>
                            <div class="text-center">
                                <p class="text-sm font-bold text-yellow-400" x-text="c.avg_engagement ? c.avg_engagement.toFixed(1) + '%' : '-'"></p>
                                <p class="text-[10px] text-white/30">Engajamento</p>
                            </div>
                        </div>
                        <div class="md:hidden flex flex-col items-end gap-0.5">
                            <span class="text-xs font-bold text-white" x-text="(c.total_views_formatted || '0') + ' views'"></span>
                            <span class="text-xs font-bold text-accent-orange" x-text="(c.viral_count || 0) + ' virais'"></span>
                        </div>
                    </div>
                </div>
            </template>
        </div>
        <div x-show="!creatorLoading && topCreators.length === 0" class="text-center py-16">
            <i data-lucide="users" class="w-12 h-12 text-white/10 mx-auto mb-4"></i>
            <p class="text-white/40 text-sm">Nenhum creator BR encontrado no periodo selecionado.</p>
            <p class="text-xs text-white/25 mt-1">O scanner coleta creators automaticamente. Tente um periodo maior.</p>
        </div>
    </div>

    <!-- ═══════════ TOP VIDEOS (Dados Locais BR) ═══════════ -->
    <div x-show="activeTab === 'top_videos'" x-cloak>
        <div class="glass rounded-2xl p-4 mb-6 animate-fade-up">
            <div class="flex flex-wrap items-center gap-3">
                <h3 class="text-sm font-bold text-white/80 flex items-center gap-2">
                    <i data-lucide="play-circle" class="w-4 h-4 text-accent-orange"></i> Top Videos Brasil
                    <span class="text-[10px] text-white/30 font-normal ml-1">Dados do scanner local</span>
                </h3>
                <!-- Rank Field -->
                <div class="flex items-center gap-1 bg-white/5 rounded-xl p-0.5">
                    <button @click="videoRankField = 1; loadTopVideos()" class="px-2.5 py-1 rounded-lg text-[11px] font-semibold transition"
                        :class="videoRankField === 1 ? 'gradient-brand text-white' : 'text-white/40'">Views</button>
                    <button @click="videoRankField = 2; loadTopVideos()" class="px-2.5 py-1 rounded-lg text-[11px] font-semibold transition"
                        :class="videoRankField === 2 ? 'gradient-brand text-white' : 'text-white/40'">Viral Score</button>
                    <button @click="videoRankField = 3; loadTopVideos()" class="px-2.5 py-1 rounded-lg text-[11px] font-semibold transition"
                        :class="videoRankField === 3 ? 'gradient-brand text-white' : 'text-white/40'">Engajamento</button>
                </div>
                <!-- Days Filter -->
                <div class="flex items-center gap-1 bg-white/5 rounded-xl p-0.5 ml-auto">
                    <template x-for="d in [7, 15, 30, 60, 90]" :key="d">
                        <button @click="videoDays = d; loadTopVideos()" class="px-2.5 py-1 rounded-lg text-[11px] font-semibold transition"
                            :class="videoDays === d ? 'gradient-fire text-white' : 'text-white/40'" x-text="d + 'd'"></button>
                    </template>
                </div>
            </div>
        </div>

        <div x-show="videoRankLoading" class="text-center py-12">
            <div class="w-5 h-5 border-2 border-accent-orange border-t-transparent rounded-full animate-spin mx-auto"></div>
        </div>

        <div x-show="!videoRankLoading" class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
            <template x-for="(v, idx) in topVideos" :key="v.video_id">
                <div class="glass-card rounded-2xl overflow-hidden group">
                    <div class="relative bg-dark-800 overflow-hidden" style="aspect-ratio: 9/16;">
                        <!-- Playing -->
                        <template x-if="playingVideoId === v.video_id">
                            <iframe :src="'https://www.tiktok.com/player/v1/' + v.video_id + '?autoplay=1&loop=1&controls=1&music_info=0&description=0'"
                                class="w-full h-full" frameborder="0" allow="autoplay; encrypted-media; fullscreen" allowfullscreen></iframe>
                        </template>
                        <!-- Thumbnail -->
                        <template x-if="playingVideoId !== v.video_id">
                            <div class="relative w-full h-full">
                                <img :src="v.thumbnail" class="w-full h-full object-cover" loading="lazy" onerror="this.style.display='none'">
                                <div class="absolute top-2 left-2 w-7 h-7 rounded-full flex items-center justify-center text-[10px] font-bold"
                                     :class="idx < 3 ? 'gradient-fire text-white' : 'glass text-white/70'"
                                     x-text="'#' + (idx + 1)"></div>
                                <div class="absolute top-2 right-2 flex flex-col gap-1">
                                    <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold gradient-fire text-white" x-text="v.views_formatted + ' views'"></span>
                                    <span x-show="v.viral_score > 0" class="px-2 py-0.5 rounded-lg text-[10px] font-bold bg-purple-500/90 text-white" x-text="'Score: ' + v.viral_score"></span>
                                    <span x-show="v.has_shop" class="px-2 py-0.5 rounded-lg text-[10px] font-bold bg-green-500/90 text-white flex items-center gap-0.5"><i data-lucide="shopping-bag" class="w-2.5 h-2.5"></i> Produto</span>
                                    <span x-show="v.engagement_rate > 5" class="px-2 py-0.5 rounded-lg text-[10px] font-bold bg-cyan-500/90 text-white" x-text="v.engagement_rate + '% eng'"></span>
                                </div>
                                <div class="absolute inset-0 flex items-center justify-center cursor-pointer"
                                     @click="playingVideoId = v.video_id; $nextTick(() => { if(window.lucide) lucide.createIcons(); })">
                                    <div class="w-14 h-14 rounded-full bg-black/40 backdrop-blur-sm flex items-center justify-center group-hover:scale-110 transition-transform border border-white/20">
                                        <i data-lucide="play" class="w-7 h-7 text-white ml-0.5"></i>
                                    </div>
                                </div>
                                <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-2 pt-6">
                                    <div class="flex items-center justify-between text-[10px] text-white/80">
                                        <span class="flex items-center gap-0.5"><i data-lucide="heart" class="w-3 h-3"></i> <span x-text="formatNumber(v.likes)"></span></span>
                                        <span class="flex items-center gap-0.5"><i data-lucide="message-circle" class="w-3 h-3"></i> <span x-text="formatNumber(v.comments)"></span></span>
                                        <span class="flex items-center gap-0.5"><i data-lucide="share-2" class="w-3 h-3"></i> <span x-text="formatNumber(v.shares)"></span></span>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </div>
                    <div class="p-2.5">
                        <p class="text-xs text-white/80 font-medium line-clamp-2 mb-1" x-text="v.description || 'Sem descricao'"></p>
                        <p class="text-[10px] text-white/40 truncate" x-text="'@' + (v.creator_username || v.creator_nickname || 'creator')"></p>
                        <div x-show="v.gmv > 0" class="mt-1 text-[10px] font-bold text-accent-green" x-text="'GMV: ' + v.gmv_formatted"></div>
                    </div>
                </div>
            </template>
        </div>
        <div x-show="!videoRankLoading && topVideos.length === 0" class="text-center py-16">
            <i data-lucide="video" class="w-12 h-12 text-white/10 mx-auto mb-4"></i>
            <p class="text-white/40 text-sm">Nenhum video no ranking. Clique em Sincronizar acima para carregar dados.</p>
        </div>
    </div>

    <!-- ═══════════ TENDENCIAS BR (Grafico) ═══════════ -->
    <div x-show="activeTab === 'trends_chart'" x-cloak>
        <div class="glass rounded-2xl p-4 mb-6 animate-fade-up">
            <div class="flex flex-wrap items-center gap-3">
                <h3 class="text-sm font-bold text-white/80 flex items-center gap-2">
                    <i data-lucide="trending-up" class="w-4 h-4 text-accent-cyan"></i> Tendencias de Videos Brasil
                    <span class="text-[10px] text-white/30 font-normal ml-1">Volume diario de videos coletados</span>
                </h3>
                <div class="flex items-center gap-1 bg-white/5 rounded-xl p-0.5 ml-auto">
                    <template x-for="d in [7, 15, 30, 60, 90]" :key="d">
                        <button @click="trendsDays = d; loadTrendsChart()" class="px-2.5 py-1 rounded-lg text-[11px] font-semibold transition"
                            :class="trendsDays === d ? 'gradient-fire text-white' : 'text-white/40'" x-text="d + 'd'"></button>
                    </template>
                </div>
            </div>
        </div>

        <div x-show="trendsLoading" class="text-center py-12">
            <div class="w-5 h-5 border-2 border-accent-cyan border-t-transparent rounded-full animate-spin mx-auto"></div>
        </div>

        <div x-show="!trendsLoading && trendsData.length > 0" class="space-y-6">
            <!-- Main Chart -->
            <div class="glass rounded-2xl p-5 animate-fade-up">
                <canvas id="trendsMainChart" height="300"></canvas>
            </div>

            <!-- KPI Cards -->
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                <div class="glass-card rounded-2xl p-4 text-center">
                    <p class="text-2xl font-extrabold text-white" x-text="trendsData.reduce((s,t) => s + t.video_count, 0).toLocaleString()"></p>
                    <p class="text-[10px] text-white/40 mt-1">Total Videos BR</p>
                </div>
                <div class="glass-card rounded-2xl p-4 text-center">
                    <p class="text-2xl font-extrabold text-accent-cyan" x-text="formatNumber(trendsData.reduce((s,t) => s + t.total_views, 0))"></p>
                    <p class="text-[10px] text-white/40 mt-1">Total Views</p>
                </div>
                <div class="glass-card rounded-2xl p-4 text-center">
                    <p class="text-2xl font-extrabold text-accent-orange" x-text="(trendsData.reduce((s,t) => s + t.avg_viral_score, 0) / Math.max(trendsData.length, 1)).toFixed(1)"></p>
                    <p class="text-[10px] text-white/40 mt-1">Viral Score Medio</p>
                </div>
                <div class="glass-card rounded-2xl p-4 text-center">
                    <p class="text-2xl font-extrabold text-accent-green" x-text="trendsData.reduce((s,t) => s + t.shop_video_count, 0).toLocaleString()"></p>
                    <p class="text-[10px] text-white/40 mt-1">Videos com Produto</p>
                </div>
            </div>

            <!-- Viral Score Chart -->
            <div class="glass rounded-2xl p-5 animate-fade-up">
                <h4 class="text-xs font-bold text-white/60 mb-3 flex items-center gap-2">
                    <i data-lucide="zap" class="w-3.5 h-3.5 text-accent-orange"></i> Viral Score & Engajamento Medio Diario
                </h4>
                <canvas id="trendsViralChart" height="200"></canvas>
            </div>
        </div>

        <div x-show="!trendsLoading && trendsData.length === 0" class="text-center py-16">
            <i data-lucide="trending-up" class="w-12 h-12 text-white/10 mx-auto mb-4"></i>
            <p class="text-white/40 text-sm">Sem dados de tendencia para o periodo selecionado.</p>
        </div>
    </div>

    <!-- ═══════════ SPY STORE TAB (EchoTik) ═══════════ -->
    <div x-show="activeTab === 'spy_store'" x-cloak>
        <div class="glass rounded-2xl p-4 mb-6 animate-fade-up">
            <h3 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2">
                <i data-lucide="eye" class="w-4 h-4 text-brand-400"></i> Espiar Loja do TikTok Shop
            </h3>
            <div class="flex gap-3">
                <div class="flex-1 flex items-center glass-light rounded-xl px-3 py-2">
                    <i data-lucide="search" class="w-4 h-4 text-white/30 mr-2"></i>
                    <input type="text" x-model="spySellerSearch" @keyup.enter="searchSeller()" placeholder="Buscar loja por nome..."
                        class="bg-transparent border-none outline-none text-sm text-white/80 placeholder:text-white/25 w-full">
                </div>
                <button @click="searchSeller()" :disabled="spyLoading" class="px-4 py-2 rounded-xl gradient-brand text-white text-sm font-semibold hover:opacity-90 transition disabled:opacity-50 flex items-center gap-2">
                    <i data-lucide="search" class="w-4 h-4"></i> Buscar
                </button>
            </div>
        </div>

        <!-- Seller Detail -->
        <div x-show="spySellerDetail" class="glass rounded-2xl p-5 mb-6">
            <div class="flex items-center gap-4 mb-4">
                <img :src="spySellerDetail?.logo" class="w-14 h-14 rounded-xl object-cover" onerror="this.style.display='none'">
                <div>
                    <h3 class="text-lg font-bold text-white" x-text="spySellerDetail?.name"></h3>
                    <p class="text-xs text-white/40" x-text="spySellerDetail?.category"></p>
                </div>
            </div>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-3 mb-4">
                <div class="glass-light rounded-xl p-3 text-center">
                    <p class="text-lg font-bold text-white" x-text="spySellerDetail?.sales_formatted"></p>
                    <p class="text-[10px] text-white/30">Vendas Total</p>
                </div>
                <div class="glass-light rounded-xl p-3 text-center">
                    <p class="text-lg font-bold text-accent-green" x-text="spySellerDetail?.gmv_formatted"></p>
                    <p class="text-[10px] text-white/30">Faturamento Total</p>
                </div>
                <div class="glass-light rounded-xl p-3 text-center">
                    <p class="text-lg font-bold text-accent-green" x-text="spySellerDetail?.gmv_30d_formatted"></p>
                    <p class="text-[10px] text-white/30">Faturamento 30d</p>
                </div>
                <div class="glass-light rounded-xl p-3 text-center">
                    <p class="text-lg font-bold text-brand-300" x-text="spySellerDetail?.product_count"></p>
                    <p class="text-[10px] text-white/30">Produtos</p>
                </div>
            </div>
            <div class="grid grid-cols-4 gap-3">
                <div class="glass-light rounded-xl p-2 text-center">
                    <p class="text-sm font-bold text-white" x-text="formatNumber(spySellerDetail?.sales_1d || 0)"></p>
                    <p class="text-[10px] text-white/30">Vendas Hoje</p>
                </div>
                <div class="glass-light rounded-xl p-2 text-center">
                    <p class="text-sm font-bold text-white" x-text="formatNumber(spySellerDetail?.sales_7d || 0)"></p>
                    <p class="text-[10px] text-white/30">7 dias</p>
                </div>
                <div class="glass-light rounded-xl p-2 text-center">
                    <p class="text-sm font-bold text-white" x-text="formatNumber(spySellerDetail?.sales_30d || 0)"></p>
                    <p class="text-[10px] text-white/30">30 dias</p>
                </div>
                <div class="glass-light rounded-xl p-2 text-center">
                    <p class="text-sm font-bold text-white" x-text="formatNumber(spySellerDetail?.sales_90d || 0)"></p>
                    <p class="text-[10px] text-white/30">90 dias</p>
                </div>
            </div>
        </div>

        <!-- Seller Products -->
        <div x-show="spySellerProducts.length > 0">
            <h4 class="text-sm font-bold text-white/70 mb-3">Produtos da Loja (<span x-text="spySellerProducts.length"></span>)</h4>
            <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4">
                <template x-for="p in spySellerProducts" :key="p.product_id">
                    <div class="glass-card rounded-2xl overflow-hidden cursor-pointer" @click="openProductDetail(p.product_id)">
                        <div class="relative aspect-square bg-dark-800">
                            <img :src="p.image" class="w-full h-full object-cover" loading="lazy" onerror="this.style.display='none'">
                            <div class="absolute top-2 right-2 px-2 py-0.5 rounded-lg text-[10px] font-bold bg-green-500/90 text-white" x-text="p.sales_formatted + ' vendas'"></div>
                            <div class="absolute bottom-2 left-2 px-2 py-1 rounded-lg text-xs font-bold glass text-accent-green" x-text="p.price_formatted"></div>
                        </div>
                        <div class="p-2.5">
                            <h4 class="text-xs font-semibold text-white/90 line-clamp-2" x-text="p.title"></h4>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <!-- Search results -->
        <div x-show="spySearchResults.length > 0 && !spySellerDetail">
            <h4 class="text-sm font-bold text-white/70 mb-3">Lojas encontradas</h4>
            <div class="space-y-3">
                <template x-for="s in spySearchResults" :key="s.seller_id">
                    <div class="glass-card rounded-2xl p-4 cursor-pointer hover:bg-white/5 transition" @click="openSellerDetail(s.seller_id)">
                        <div class="flex items-center gap-4">
                            <img :src="s.logo" class="w-12 h-12 rounded-xl object-cover" onerror="this.style.display='none'">
                            <div class="flex-1">
                                <h4 class="text-sm font-semibold text-white/90" x-text="s.name"></h4>
                                <p class="text-xs text-white/40" x-text="s.category + ' • ' + s.sales_formatted + ' vendas • ' + s.gmv_formatted"></p>
                            </div>
                            <i data-lucide="chevron-right" class="w-4 h-4 text-white/30"></i>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <div x-show="spyLoading" class="text-center py-12">
            <div class="w-6 h-6 border-2 border-brand-400 border-t-transparent rounded-full animate-spin mx-auto"></div>
        </div>
    </div>

    <!-- ═══════════ PRODUCT DETAIL TAB (EchoTik) ═══════════ -->
    <div x-show="activeTab === 'product_detail'" x-cloak>
        <div class="glass rounded-2xl p-4 mb-6 animate-fade-up">
            <h3 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2">
                <i data-lucide="package-search" class="w-4 h-4 text-accent-cyan"></i> Analisar Produto (EchoTik)
            </h3>
            <div class="flex gap-3">
                <div class="flex-1 flex items-center glass-light rounded-xl px-3 py-2">
                    <i data-lucide="search" class="w-4 h-4 text-white/30 mr-2"></i>
                    <input type="text" x-model="detailSearch" @keyup.enter="searchProductDetail()" placeholder="Buscar produto por nome ou ID..."
                        class="bg-transparent border-none outline-none text-sm text-white/80 placeholder:text-white/25 w-full">
                </div>
                <button @click="searchProductDetail()" :disabled="detailLoading" class="px-4 py-2 rounded-xl gradient-brand text-white text-sm font-semibold hover:opacity-90 transition disabled:opacity-50 flex items-center gap-2">
                    <i data-lucide="search" class="w-4 h-4"></i> Buscar
                </button>
            </div>
        </div>

        <!-- Product Detail -->
        <div x-show="echoProduct" class="glass rounded-2xl p-5 mb-6">
            <div class="flex flex-col md:flex-row gap-6">
                <div class="w-full md:w-64 flex-shrink-0">
                    <img :src="echoProduct?.image" class="w-full rounded-xl object-cover" onerror="this.style.display='none'">
                </div>
                <div class="flex-1 space-y-4">
                    <h3 class="text-lg font-bold text-white" x-text="echoProduct?.title"></h3>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                        <div class="glass-light rounded-xl p-3 text-center">
                            <p class="text-xl font-extrabold text-accent-green" x-text="echoProduct?.price_formatted"></p>
                            <p class="text-[10px] text-white/30">Preco Medio</p>
                        </div>
                        <div class="glass-light rounded-xl p-3 text-center">
                            <p class="text-xl font-extrabold text-white" x-text="echoProduct?.sales_formatted"></p>
                            <p class="text-[10px] text-white/30">Vendas Total</p>
                        </div>
                        <div class="glass-light rounded-xl p-3 text-center">
                            <p class="text-xl font-extrabold text-accent-green" x-text="echoProduct?.gmv_formatted"></p>
                            <p class="text-[10px] text-white/30">Faturamento Total</p>
                        </div>
                        <div class="glass-light rounded-xl p-3 text-center">
                            <p class="text-xl font-extrabold text-yellow-400" x-text="echoProduct?.rating ? echoProduct.rating.toFixed(1) : '-'"></p>
                            <p class="text-[10px] text-white/30">Avaliacao (<span x-text="echoProduct?.review_count || 0"></span>)</p>
                        </div>
                    </div>
                    <!-- Period stats -->
                    <div class="grid grid-cols-2 md:grid-cols-5 gap-2">
                        <div class="glass-light rounded-xl p-2 text-center">
                            <p class="text-sm font-bold text-white" x-text="formatNumber(echoProduct?.sales_1d || 0)"></p>
                            <p class="text-[10px] text-white/30">Vendas Hoje</p>
                        </div>
                        <div class="glass-light rounded-xl p-2 text-center">
                            <p class="text-sm font-bold text-white" x-text="formatNumber(echoProduct?.sales_7d || 0)"></p>
                            <p class="text-[10px] text-white/30">7 dias</p>
                        </div>
                        <div class="glass-light rounded-xl p-2 text-center">
                            <p class="text-sm font-bold text-white" x-text="formatNumber(echoProduct?.sales_30d || 0)"></p>
                            <p class="text-[10px] text-white/30">30 dias</p>
                        </div>
                        <div class="glass-light rounded-xl p-2 text-center">
                            <p class="text-sm font-bold text-accent-green" x-text="echoProduct?.gmv_30d_formatted"></p>
                            <p class="text-[10px] text-white/30">GMV 30d</p>
                        </div>
                        <div class="glass-light rounded-xl p-2 text-center">
                            <p class="text-sm font-bold text-accent-cyan" x-text="formatNumber(echoProduct?.stock || 0)"></p>
                            <p class="text-[10px] text-white/30">Estoque</p>
                        </div>
                    </div>
                    <div class="flex items-center gap-3 text-xs text-white/40">
                        <span x-show="echoProduct?.commission_pct" class="text-accent-cyan font-semibold" x-text="'Comissao: ' + echoProduct?.commission_pct"></span>
                        <span x-show="echoProduct?.free_shipping" class="text-accent-green font-semibold">Frete Gratis</span>
                        <span x-text="echoProduct?.influencer_count + ' creators'"></span>
                        <span x-text="echoProduct?.video_count + ' videos'"></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Trend Chart -->
        <div x-show="echoTrend.length > 0" class="glass rounded-2xl p-5 mb-6">
            <h4 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2">
                <i data-lucide="trending-up" class="w-4 h-4 text-accent-green"></i> Historico de Vendas
                <span class="text-[10px] text-white/30 ml-auto" x-text="echoTrend.length + ' pontos de dados'"></span>
            </h4>
            <canvas id="echoTrendChart" height="200"></canvas>
            <p class="text-[10px] text-white/20 mt-2">Dados acumulados automaticamente a cada visita. Quanto mais acessar, mais historico tera.</p>
        </div>
        <!-- No trend data yet -->
        <div x-show="echoTrend.length === 0 && echoProduct" class="glass rounded-2xl p-5 mb-6">
            <div class="text-center py-4">
                <i data-lucide="bar-chart-2" class="w-8 h-8 text-white/20 mx-auto mb-2"></i>
                <p class="text-sm text-white/40">Grafico de tendencia sera construido automaticamente</p>
                <p class="text-xs text-white/20 mt-1">A cada visita, um snapshot e salvo. Volte amanha para ver a evolucao!</p>
            </div>
        </div>

        <!-- Product Videos -->
        <div x-show="echoProductVideos.length > 0" class="glass rounded-2xl p-5 mb-6">
            <h4 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2">
                <i data-lucide="video" class="w-4 h-4 text-accent-orange"></i> Videos Promovendo (<span x-text="echoProductVideos.length"></span>)
            </h4>
            <div class="space-y-2">
                <template x-for="v in echoProductVideos" :key="v.video_id">
                    <div class="glass-light rounded-xl p-3 flex items-center gap-3">
                        <div class="w-12 h-16 rounded-lg bg-dark-800 overflow-hidden flex-shrink-0 cursor-pointer" @click="playingVideoId = playingVideoId === v.video_id ? null : v.video_id">
                            <img :src="v.thumbnail" class="w-full h-full object-cover" onerror="this.style.display='none'">
                        </div>
                        <div class="flex-1 min-w-0">
                            <p class="text-xs text-white/70 line-clamp-1" x-text="v.description || 'Video promocional'"></p>
                            <div class="flex items-center gap-2 mt-1 text-[10px] text-white/40">
                                <span x-text="v.views_formatted + ' views'"></span>
                                <span x-text="formatNumber(v.likes) + ' likes'"></span>
                                <span x-show="v.sales > 0" class="text-accent-green font-bold" x-text="v.sales_formatted + ' vendas'"></span>
                                <span x-show="v.gmv > 0" class="text-accent-green" x-text="v.gmv_formatted"></span>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <!-- Search results list -->
        <div x-show="detailSearchResults.length > 0 && !echoProduct">
            <h4 class="text-sm font-bold text-white/70 mb-3">Produtos encontrados</h4>
            <div class="space-y-3">
                <template x-for="p in detailSearchResults" :key="p.product_id">
                    <div class="glass-card rounded-2xl p-4 cursor-pointer hover:bg-white/5 transition" @click="openProductDetail(p.product_id)">
                        <div class="flex items-center gap-4">
                            <img :src="p.image" class="w-14 h-14 rounded-xl object-cover" onerror="this.style.display='none'">
                            <div class="flex-1">
                                <h4 class="text-sm font-semibold text-white/90 line-clamp-1" x-text="p.title"></h4>
                                <p class="text-xs text-white/40" x-text="p.price_formatted + ' • ' + p.sales_formatted + ' vendas • ' + p.gmv_formatted"></p>
                            </div>
                            <i data-lucide="chevron-right" class="w-4 h-4 text-white/30"></i>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <div x-show="detailLoading" class="text-center py-12">
            <div class="w-6 h-6 border-2 border-accent-cyan border-t-transparent rounded-full animate-spin mx-auto"></div>
        </div>
    </div>

    <!-- ═══════════ SEARCH TAB ═══════════ -->
    <div x-show="activeTab === 'search'" x-cloak>
        <div class="glass rounded-2xl p-4 mb-6 animate-fade-up">
            <div class="flex flex-col md:flex-row gap-4">
                <div class="flex-1 flex gap-3">
                    <div class="flex-1 flex items-center glass-light rounded-xl px-4 py-2.5">
                        <i data-lucide="search" class="w-4 h-4 text-white/30 mr-3 flex-shrink-0"></i>
                        <input type="text" x-model="searchQuery" @keyup.enter="searchProducts()" placeholder="Buscar produtos (ex: skincare, gadgets, moda feminina...)" class="bg-transparent border-none outline-none text-sm text-white/80 placeholder:text-white/25 w-full">
                    </div>
                    <button @click="searchProducts()" :disabled="loading" 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 disabled:opacity-50">
                        <i data-lucide="search" class="w-4 h-4"></i>
                        <span class="hidden sm:inline">Buscar</span>
                    </button>
                </div>
            </div>
            <div class="flex flex-wrap gap-2 mt-3">
                <template x-for="tag in quickTags">
                    <button @click="searchQuery = tag; searchProducts()" class="px-3 py-1.5 rounded-lg text-xs font-medium glass-light text-white/60 hover:text-white hover:border-brand-400 transition" x-text="tag"></button>
                </template>
            </div>
        </div>

        <div x-show="!loading">
            <div x-show="products.length > 0" class="flex items-center justify-between mb-4">
                <p class="text-sm text-white/40"><span class="text-white font-semibold" x-text="products.length"></span> produtos encontrados</p>
                <div class="flex gap-2">
                    <button @click="sortProducts('sold')" :class="sortBy === 'sold' ? 'text-brand-400' : 'text-white/40'" class="text-xs font-medium hover:text-white/80 transition">Mais Vendidos</button>
                    <button @click="sortProducts('rating')" :class="sortBy === 'rating' ? 'text-brand-400' : 'text-white/40'" class="text-xs font-medium hover:text-white/80 transition">Melhor Avaliados</button>
                </div>
            </div>
            <div class="grid-cards" x-ref="searchGrid">
                <template x-for="product in products" :key="product.product_id">
                    <div class="glass-card rounded-2xl overflow-hidden">
                        <div class="relative aspect-square bg-dark-800">
                            <img :src="product.image" :alt="product.title" class="w-full h-full object-cover" onerror="this.style.display='none'">
                            <div class="absolute top-3 right-3 flex flex-col gap-1.5">
                                <span x-show="product.sold_count > 1000" class="px-2 py-1 rounded-lg text-[10px] font-bold gradient-fire text-white">
                                    <span x-text="formatNumber(product.sold_count)"></span> vendidos
                                </span>
                                <span x-show="product.rating > 0" class="px-2 py-1 rounded-lg text-[10px] font-bold glass text-yellow-400">
                                    <span x-text="product.rating.toFixed(1)"></span> ★
                                </span>
                            </div>
                            <div x-show="product.discount" class="absolute top-3 left-3">
                                <span class="px-2 py-1 rounded-lg text-[10px] font-bold gradient-success text-white" x-text="product.discount"></span>
                            </div>
                        </div>
                        <div class="p-4 space-y-3">
                            <h3 class="text-sm font-semibold text-white/90 line-clamp-2 leading-snug" x-text="product.title"></h3>
                            <div class="flex items-center justify-between">
                                <div>
                                    <span class="text-lg font-bold text-accent-green" x-text="product.price || 'N/A'"></span>
                                    <span x-show="product.original_price" class="text-xs text-white/30 line-through ml-2" x-text="product.original_price"></span>
                                </div>
                            </div>
                            <div class="flex items-center gap-2 text-xs text-white/40">
                                <i data-lucide="store" class="w-3.5 h-3.5"></i>
                                <span x-text="product.seller_name || 'Vendedor'"></span>
                            </div>
                            <div class="grid grid-cols-3 gap-2 pt-2 border-t border-white/5">
                                <div class="text-center">
                                    <p class="text-xs font-bold text-white/80" x-text="formatNumber(product.sold_count)"></p>
                                    <p class="text-[10px] text-white/30">Vendidos</p>
                                </div>
                                <div class="text-center">
                                    <p class="text-xs font-bold text-yellow-400" x-text="product.rating ? product.rating.toFixed(1) + ' ★' : '--'"></p>
                                    <p class="text-[10px] text-white/30">Rating</p>
                                </div>
                                <div class="text-center">
                                    <p class="text-xs font-bold text-white/80" x-text="formatNumber(product.review_count)"></p>
                                    <p class="text-[10px] text-white/30">Reviews</p>
                                </div>
                            </div>
                            <div class="flex gap-2">
                                <button @click="viewProduct(product)" class="flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-xl gradient-brand text-white font-medium text-xs hover:opacity-90 transition">
                                    <i data-lucide="eye" class="w-3.5 h-3.5"></i> Detalhes
                                </button>
                                <button @click="monitorProduct(product)" class="flex items-center justify-center px-3 py-2 rounded-xl glass-light text-white/60 hover:text-accent-green text-xs transition" title="Monitorar vendas">
                                    <i data-lucide="activity" class="w-3.5 h-3.5"></i>
                                </button>
                                <a x-show="product.url" :href="product.url" target="_blank" rel="noopener" class="flex items-center justify-center px-3 py-2 rounded-xl glass-light text-white/60 hover:text-white text-xs transition">
                                    <i data-lucide="external-link" class="w-3.5 h-3.5"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
            <div x-show="!loading && products.length === 0 && searchDone" class="text-center py-16">
                <div class="glass-card rounded-2xl inline-block p-8 max-w-md">
                    <i data-lucide="search-x" class="w-12 h-12 text-white/20 mx-auto mb-4"></i>
                    <h3 class="text-lg font-bold text-white/60 mb-2">Nenhum produto encontrado</h3>
                    <p class="text-sm text-white/30">Tente termos diferentes como "skincare", "gadgets", "moda feminina"</p>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══════════ CATEGORIES BR TAB ═══════════ -->
    <!-- categories tab removido - usar EchoTik product/search -->

    <!-- ═══════════ LEGACY TABS (hidden - no tab buttons) ═══════════ -->
    <div x-show="activeTab === 'crossplatform'" x-cloak>
        <div class="glass rounded-2xl p-4 mb-6 animate-fade-up">
            <h3 class="text-sm font-bold text-white/80 mb-3 flex items-center gap-2">
                <i data-lucide="scan-search" class="w-4 h-4 text-brand-400"></i>
                Detectar Videos Virais com Produtos TikTok Shop
            </h3>
            <p class="text-xs text-white/40 mb-4">Busca videos virais que promovem produtos do TikTok Shop. Detecta automaticamente o campo <code class="text-brand-300">shop_product_url</code> nos videos.</p>
            <div class="flex flex-col sm:flex-row gap-3">
                <div class="flex-1 flex items-center glass-light rounded-xl px-4 py-2.5">
                    <i data-lucide="tag" class="w-4 h-4 text-white/30 mr-3"></i>
                    <input type="text" x-model="crossKeywords" placeholder="Keywords separadas por virgula (ex: moda feminina, skincare, gadgets)" class="bg-transparent border-none outline-none text-sm text-white/80 placeholder:text-white/25 w-full">
                </div>
                <button @click="runCrossPlatform()" :disabled="loading" class="px-5 py-2.5 rounded-xl gradient-ocean text-white font-semibold text-sm hover:opacity-90 transition flex items-center gap-2 disabled:opacity-50">
                    <i data-lucide="scan-search" class="w-4 h-4"></i> Detectar
                </button>
            </div>
            <div class="flex flex-wrap gap-2 mt-3">
                <template x-for="tag in crossQuickTags">
                    <button @click="crossKeywords = tag; runCrossPlatform()" class="px-3 py-1.5 rounded-lg text-xs font-medium glass-light text-white/60 hover:text-white transition" x-text="tag"></button>
                </template>
            </div>
        </div>

        <!-- Auto-detect button -->
        <div class="glass rounded-2xl p-4 mb-6">
            <div class="flex items-center justify-between">
                <div>
                    <h4 class="text-sm font-bold text-white/80 flex items-center gap-2">
                        <i data-lucide="zap" class="w-4 h-4 text-accent-orange"></i>
                        Auto-Detectar Produtos Virais BR
                    </h4>
                    <p class="text-xs text-white/40 mt-1">Busca automatica em todas as categorias brasileiras</p>
                </div>
                <button @click="autoDetect()" :disabled="loading" class="px-5 py-2.5 rounded-xl gradient-fire text-white font-semibold text-sm hover:opacity-90 transition flex items-center gap-2 disabled:opacity-50">
                    <i data-lucide="zap" class="w-4 h-4"></i> Auto-Detectar
                </button>
            </div>
        </div>

        <!-- Cross-platform results -->
        <div x-show="!loading && crossResults">
            <!-- Stats -->
            <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
                <div class="glass-card rounded-xl p-4 text-center">
                    <p class="stat-number text-white" x-text="crossResults?.total_videos || 0"></p>
                    <p class="text-xs text-white/40 mt-1">Videos Analisados</p>
                </div>
                <div class="glass-card rounded-xl p-4 text-center">
                    <p class="stat-number text-accent-orange" x-text="crossResults?.videos_with_products || 0"></p>
                    <p class="text-xs text-white/40 mt-1">Com Produtos Shop</p>
                </div>
                <div class="glass-card rounded-xl p-4 text-center">
                    <p class="stat-number text-brand-300" x-text="crossResults?.keywords_searched?.length || 0"></p>
                    <p class="text-xs text-white/40 mt-1">Keywords</p>
                </div>
                <div class="glass-card rounded-xl p-4 text-center">
                    <p class="stat-number text-accent-green" x-text="autoDetected.length || 0"></p>
                    <p class="text-xs text-white/40 mt-1">Produtos Detectados</p>
                </div>
            </div>

            <!-- Shop videos -->
            <div x-show="crossResults?.shop_videos?.length > 0">
                <h4 class="text-sm font-bold text-white/70 mb-3 flex items-center gap-2">
                    <i data-lucide="shopping-bag" class="w-4 h-4 text-accent-orange"></i>
                    Videos Promovendo Produtos (<span x-text="crossResults?.shop_videos?.length || 0"></span>)
                </h4>
                <div class="space-y-3 mb-6">
                    <template x-for="(vid, i) in (crossResults?.shop_videos || [])" :key="i">
                        <div class="glass-card rounded-xl p-4">
                            <div class="flex items-start gap-4">
                                <div class="w-16 h-16 rounded-xl bg-dark-800 overflow-hidden flex-shrink-0">
                                    <img :src="vid.thumbnail_url" class="w-full h-full object-cover" onerror="this.style.display='none'">
                                </div>
                                <div class="flex-1 min-w-0">
                                    <p class="text-sm font-semibold text-white/90 line-clamp-2" x-text="vid.title || vid.description"></p>
                                    <div class="flex items-center gap-3 mt-1.5">
                                        <span class="text-xs text-white/40" x-text="'@' + (vid.creator_username || '')"></span>
                                        <span class="text-xs text-brand-300 font-medium" x-text="formatNumber(vid.views) + ' views'"></span>
                                        <span class="text-xs text-accent-pink" x-text="formatNumber(vid.likes) + ' likes'"></span>
                                    </div>
                                    <div class="flex items-center gap-2 mt-2">
                                        <span class="px-2 py-0.5 rounded-md text-[10px] font-bold gradient-fire text-white">PRODUTO SHOP</span>
                                        <a :href="vid.url" target="_blank" rel="noopener" class="text-xs text-brand-300 hover:text-white transition">Ver video</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
            </div>

            <!-- Auto-detected products -->
            <div x-show="autoDetected.length > 0">
                <h4 class="text-sm font-bold text-white/70 mb-3 flex items-center gap-2">
                    <i data-lucide="zap" class="w-4 h-4 text-accent-green"></i>
                    Produtos Detectados Automaticamente (<span x-text="autoDetected.length"></span>)
                </h4>
                <div class="grid-cards">
                    <template x-for="(p, i) in autoDetected" :key="i">
                        <div class="glass-card rounded-xl p-4">
                            <h4 class="text-sm font-semibold text-white/90 line-clamp-2 mb-2" x-text="p.title"></h4>
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-base font-bold text-accent-green" x-text="p.price || 'N/A'"></span>
                            </div>
                            <div class="flex items-center gap-2 text-xs text-white/40">
                                <i data-lucide="video" class="w-3.5 h-3.5"></i>
                                <span>Via: @<span x-text="p.video_creator"></span></span>
                                <span class="text-brand-300" x-text="formatNumber(p.video_views) + ' views'"></span>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══════════ MONITORED TAB ═══════════ -->
    <div x-show="activeTab === 'monitored'" x-cloak>
        <!-- Actions bar -->
        <div class="glass rounded-2xl p-4 mb-6 animate-fade-up">
            <div class="flex items-center justify-between flex-wrap gap-3">
                <div>
                    <h3 class="text-sm font-bold text-white/80 flex items-center gap-2">
                        <i data-lucide="activity" class="w-4 h-4 text-accent-green"></i>
                        Produtos Monitorados - Revenue Tracking
                    </h3>
                    <p class="text-xs text-white/40 mt-1">Acompanhe vendas reais via snapshots de estoque</p>
                </div>
                <button @click="snapshotAll()" :disabled="loading" class="px-4 py-2 rounded-xl gradient-success text-white font-semibold text-sm hover:opacity-90 transition flex items-center gap-2 disabled:opacity-50">
                    <i data-lucide="camera" class="w-4 h-4"></i> Atualizar Todos
                </button>
            </div>
        </div>

        <div x-show="!loading">
            <!-- Monitored products list -->
            <div x-show="monitoredProducts.length > 0" class="space-y-3">
                <template x-for="product in monitoredProducts" :key="product.product_id">
                    <div class="glass-card rounded-2xl p-4">
                        <div class="flex items-start gap-4">
                            <div class="w-20 h-20 rounded-xl bg-dark-800 overflow-hidden flex-shrink-0">
                                <img :src="product.image" class="w-full h-full object-cover" onerror="this.style.display='none'">
                            </div>
                            <div class="flex-1 min-w-0">
                                <h4 class="text-sm font-bold text-white/90 line-clamp-1" x-text="product.title"></h4>
                                <div class="flex items-center gap-3 mt-1.5 flex-wrap">
                                    <span class="text-base font-bold text-accent-green" x-text="product.price || 'N/A'"></span>
                                    <span class="text-xs text-white/40" x-text="product.sold_formatted + ' vendidos total'"></span>
                                </div>
                                <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 mt-3">
                                    <div class="glass-light rounded-lg p-2 text-center">
                                        <p class="text-sm font-bold" :class="product.delta_sold > 0 ? 'text-accent-green' : 'text-white/60'" x-text="'+' + formatNumber(product.delta_sold)"></p>
                                        <p class="text-[10px] text-white/30">Vendas (delta)</p>
                                    </div>
                                    <div class="glass-light rounded-lg p-2 text-center">
                                        <p class="text-sm font-bold text-white/80" x-text="formatNumber(product.stock)"></p>
                                        <p class="text-[10px] text-white/30">Estoque</p>
                                    </div>
                                    <div class="glass-light rounded-lg p-2 text-center">
                                        <p class="text-sm font-bold text-yellow-400" x-text="product.rating ? product.rating.toFixed(1) + ' ★' : '--'"></p>
                                        <p class="text-[10px] text-white/30">Rating</p>
                                    </div>
                                    <div class="glass-light rounded-lg p-2 text-center">
                                        <p class="text-sm font-bold text-brand-300" x-text="formatNumber(product.related_video_count)"></p>
                                        <p class="text-[10px] text-white/30">Videos</p>
                                    </div>
                                </div>
                            </div>
                            <div class="flex flex-col gap-2 flex-shrink-0">
                                <button @click="takeSnapshot(product.product_id)" class="p-2 rounded-lg glass-light hover:bg-white/10 transition" title="Novo snapshot">
                                    <i data-lucide="camera" class="w-4 h-4 text-white/60"></i>
                                </button>
                                <button @click="viewRevenue(product.product_id)" class="p-2 rounded-lg glass-light hover:bg-white/10 transition" title="Ver revenue">
                                    <i data-lucide="bar-chart-3" class="w-4 h-4 text-accent-green"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
            <div x-show="monitoredProducts.length === 0" class="text-center py-16">
                <i data-lucide="activity" class="w-12 h-12 text-white/20 mx-auto mb-4"></i>
                <h3 class="text-lg font-bold text-white/60 mb-2">Nenhum produto monitorado</h3>
                <p class="text-sm text-white/30 mb-4">Busque produtos e clique no icone <i data-lucide="activity" class="w-4 h-4 inline text-accent-green"></i> para comecar a monitorar vendas</p>
                <button @click="activeTab = 'crossplatform'" class="px-4 py-2 rounded-xl gradient-brand text-white text-sm font-medium">Detectar produtos virais</button>
            </div>
        </div>
    </div>

    <!-- ═══════════ VIRAL VIDEOS WITH PRODUCTS TAB ═══════════ -->
    <div x-show="activeTab === 'viral_videos'" x-cloak>
        <div class="flex items-center justify-between mb-4 animate-fade-up">
            <div>
                <p class="text-sm text-white/40">Videos virais que promovem produtos TikTok Shop</p>
                <p class="text-xs text-white/30 mt-1">Detectados automaticamente pelo scanner</p>
            </div>
            <div class="flex gap-2">
                <button @click="autoLinkProducts()" :disabled="loading" class="px-4 py-2 rounded-xl gradient-brand text-white font-semibold text-xs hover:opacity-90 transition flex items-center gap-2 disabled:opacity-50">
                    <i data-lucide="link" class="w-3.5 h-3.5"></i> Importar Produtos
                </button>
            </div>
        </div>

        <!-- Filters Bar -->
        <div class="glass-card rounded-2xl p-4 mb-4 space-y-3">
            <!-- Row 1: Search + Region + Sort -->
            <div class="flex flex-wrap items-center gap-3">
                <div class="flex-1 min-w-[180px] flex items-center glass-light rounded-xl px-3 py-2">
                    <i data-lucide="search" class="w-4 h-4 text-white/30 mr-2 flex-shrink-0"></i>
                    <input type="text" x-model="viralFilters.description_contains" @keyup.enter="loadViralVideos()" placeholder="Buscar por titulo, descricao..." class="bg-transparent border-none outline-none text-xs text-white/80 placeholder:text-white/25 w-full">
                </div>
                <div class="flex items-center gap-2">
                    <button @click="viralFilters.region_filter = 'br'; loadViralVideos()" :class="viralFilters.region_filter === 'br' ? 'bg-brand-500 text-white' : 'glass-light text-white/50'" class="px-3 py-1.5 rounded-lg text-xs font-medium transition">Brasil/PT</button>
                    <button @click="viralFilters.region_filter = 'all'; loadViralVideos()" :class="viralFilters.region_filter === 'all' ? 'bg-brand-500 text-white' : 'glass-light text-white/50'" class="px-3 py-1.5 rounded-lg text-xs font-medium transition">Todos</button>
                </div>
                <select x-model="viralFilters.sort_by" @change="loadViralVideos()" class="bg-white/5 border border-white/10 rounded-lg px-3 py-1.5 text-xs text-white/70 outline-none">
                    <option value="views">Mais Views</option>
                    <option value="viral_score">Viral Score</option>
                    <option value="recent">Recente</option>
                    <option value="engagement">Engagement</option>
                    <option value="likes">Mais Likes</option>
                </select>
            </div>

            <!-- Row 2: Category -->
            <div>
                <p class="text-[10px] text-white/30 uppercase tracking-widest font-semibold mb-1.5">Categoria</p>
                <div class="flex flex-wrap gap-1.5">
                    <button @click="viralFilters.category = ''; loadViralVideos()" class="px-2.5 py-1 rounded-lg text-[10px] font-semibold transition"
                            :class="!viralFilters.category ? 'bg-brand-500/30 text-brand-300 border border-brand-500/50' : 'glass-light text-white/50 hover:text-white/80'">Todas</button>
                    <template x-for="cat in shopCategories">
                        <button @click="viralFilters.category = viralFilters.category === cat.id ? '' : cat.id; loadViralVideos()"
                                class="px-2.5 py-1 rounded-lg text-[10px] font-semibold transition flex items-center gap-1"
                                :class="viralFilters.category === cat.id ? 'bg-brand-500/30 text-brand-300 border border-brand-500/50' : 'glass-light text-white/50 hover:text-white/80'">
                            <span x-text="cat.icon"></span> <span x-text="cat.name"></span>
                        </button>
                    </template>
                </div>
            </div>

            <!-- Row 3: Style -->
            <div>
                <p class="text-[10px] text-white/30 uppercase tracking-widest font-semibold mb-1.5">Estilo de Video</p>
                <div class="flex flex-wrap gap-1.5">
                    <button @click="viralFilters.style = ''; loadViralVideos()" class="px-2.5 py-1 rounded-lg text-[10px] font-semibold transition"
                            :class="!viralFilters.style ? 'bg-cyan-500/30 text-cyan-300 border border-cyan-500/50' : 'glass-light text-white/50 hover:text-white/80'">Todos</button>
                    <template x-for="st in shopStyles">
                        <button @click="viralFilters.style = viralFilters.style === st.id ? '' : st.id; loadViralVideos()"
                                class="px-2.5 py-1 rounded-lg text-[10px] font-semibold transition flex items-center gap-1"
                                :class="viralFilters.style === st.id ? 'bg-cyan-500/30 text-cyan-300 border border-cyan-500/50' : 'glass-light text-white/50 hover:text-white/80'">
                            <span x-text="st.icon"></span> <span x-text="st.name"></span>
                        </button>
                    </template>
                </div>
            </div>

            <!-- Row 4: Quick filters -->
            <div class="flex flex-wrap items-center gap-3">
                <div class="flex flex-wrap gap-1.5">
                    <span class="text-[10px] text-white/30 self-center mr-1">Views:</span>
                    <template x-for="v in [50000, 100000, 500000, 1000000]">
                        <button @click="viralFilters.min_views = viralFilters.min_views === v ? 10000 : v; loadViralVideos()"
                                class="px-2 py-0.5 rounded text-[10px] font-semibold transition"
                                :class="viralFilters.min_views === v ? 'bg-brand-500/30 text-brand-300' : 'bg-white/5 text-white/50'"
                                x-text="formatNumber(v) + '+'"></button>
                    </template>
                </div>
                <div class="flex flex-wrap gap-1.5">
                    <span class="text-[10px] text-white/30 self-center mr-1">Score:</span>
                    <template x-for="s in [40, 60, 80]">
                        <button @click="viralFilters.min_viral_score = viralFilters.min_viral_score === s ? 0 : s; loadViralVideos()"
                                class="px-2 py-0.5 rounded text-[10px] font-semibold transition"
                                :class="viralFilters.min_viral_score === s ? 'bg-orange-500/30 text-orange-300' : 'bg-white/5 text-white/50'"
                                x-text="s + '+'"></button>
                    </template>
                </div>
                <div class="flex flex-wrap gap-1.5">
                    <span class="text-[10px] text-white/30 self-center mr-1">Duracao:</span>
                    <button @click="viralFilters.min_duration = 0; viralFilters.max_duration = 0; loadViralVideos()"
                            class="px-2 py-0.5 rounded text-[10px] font-semibold transition"
                            :class="!viralFilters.max_duration ? 'bg-cyan-500/30 text-cyan-300' : 'bg-white/5 text-white/50'">Todas</button>
                    <button @click="viralFilters.min_duration = 0; viralFilters.max_duration = 30; loadViralVideos()"
                            class="px-2 py-0.5 rounded text-[10px] font-semibold transition"
                            :class="viralFilters.max_duration === 30 ? 'bg-cyan-500/30 text-cyan-300' : 'bg-white/5 text-white/50'">0-30s</button>
                    <button @click="viralFilters.min_duration = 30; viralFilters.max_duration = 60; loadViralVideos()"
                            class="px-2 py-0.5 rounded text-[10px] font-semibold transition"
                            :class="viralFilters.max_duration === 60 ? 'bg-cyan-500/30 text-cyan-300' : 'bg-white/5 text-white/50'">30-60s</button>
                    <button @click="viralFilters.min_duration = 60; viralFilters.max_duration = 9999; loadViralVideos()"
                            class="px-2 py-0.5 rounded text-[10px] font-semibold transition"
                            :class="viralFilters.max_duration === 9999 ? 'bg-cyan-500/30 text-cyan-300' : 'bg-white/5 text-white/50'">1min+</button>
                </div>
                <p class="text-xs text-white/40 ml-auto"><span class="text-white font-semibold" x-text="viralVideosTotal"></span> videos</p>
            </div>
        </div>

        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
            <template x-for="video in viralVideos" :key="video.id">
                <div class="glass-card rounded-2xl overflow-hidden group">
                    <!-- Video Area (9:16) -->
                    <div class="relative bg-dark-800 overflow-hidden" style="aspect-ratio: 9/16;">
                        <!-- Playing: TikTok Embed -->
                        <template x-if="playingVideoId === video.id && getTikTokVideoId(video)">
                            <iframe :src="'https://www.tiktok.com/player/v1/' + getTikTokVideoId(video) + '?autoplay=1&loop=1&controls=1&music_info=0&description=0'"
                                class="w-full h-full" frameborder="0" allow="autoplay; encrypted-media; fullscreen" allowfullscreen style="border:0;"></iframe>
                        </template>
                        <!-- Playing: YouTube Embed -->
                        <template x-if="playingVideoId === video.id && !getTikTokVideoId(video) && getYouTubeVideoId(video)">
                            <iframe :src="'https://www.youtube-nocookie.com/embed/' + getYouTubeVideoId(video) + '?autoplay=1&loop=1&rel=0&modestbranding=1&playsinline=1'"
                                class="w-full h-full" frameborder="0" allow="autoplay; encrypted-media; fullscreen" allowfullscreen style="border:0;"></iframe>
                        </template>
                        <!-- Not playing: Thumbnail + Play -->
                        <template x-if="playingVideoId !== video.id || !getEmbeddableVideoId(video)">
                            <div class="relative w-full h-full">
                                <img :src="video.thumbnail_url" :alt="video.title" class="w-full h-full object-cover" loading="lazy" onerror="this.style.display='none'">
                                <!-- Score -->
                                <div class="absolute top-2 left-2">
                                    <div class="w-9 h-9 rounded-full flex items-center justify-center text-[10px] font-bold"
                                         :style="'background:' + (video.viral_score >= 80 ? '#ef4444' : video.viral_score >= 60 ? '#f97316' : video.viral_score >= 40 ? '#eab308' : '#3b82f6') + '22; color:' + (video.viral_score >= 80 ? '#ef4444' : video.viral_score >= 60 ? '#f97316' : video.viral_score >= 40 ? '#eab308' : '#3b82f6') + '; border: 2px solid ' + (video.viral_score >= 80 ? '#ef4444' : video.viral_score >= 60 ? '#f97316' : video.viral_score >= 40 ? '#eab308' : '#3b82f6') + '44'"
                                         x-text="Math.round(video.viral_score)"></div>
                                </div>
                                <!-- Badges -->
                                <div class="absolute top-2 right-2 flex flex-col gap-1">
                                    <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold gradient-fire text-white">
                                        <span x-text="video.views_formatted"></span>
                                    </span>
                                    <span class="px-2 py-0.5 rounded-lg text-[10px] font-bold bg-green-500/80 text-white flex items-center gap-1">
                                        <i data-lucide="shopping-bag" class="w-3 h-3"></i> Produto
                                    </span>
                                </div>
                                <!-- Play button -->
                                <div class="absolute inset-0 flex items-center justify-center cursor-pointer"
                                     @click="playingVideoId = video.id; $nextTick(() => { if(window.lucide) lucide.createIcons(); })">
                                    <div class="w-14 h-14 rounded-full bg-black/40 backdrop-blur-sm flex items-center justify-center group-hover:scale-110 transition-transform border border-white/20">
                                        <i data-lucide="play" class="w-7 h-7 text-white ml-0.5"></i>
                                    </div>
                                </div>
                                <!-- Bottom stats -->
                                <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent p-2 pt-6">
                                    <div class="flex items-center justify-between text-[10px] text-white/80">
                                        <span class="flex items-center gap-0.5"><i data-lucide="heart" class="w-3 h-3"></i> <span x-text="formatNumber(video.likes)"></span></span>
                                        <span class="flex items-center gap-0.5"><i data-lucide="message-circle" class="w-3 h-3"></i> <span x-text="formatNumber(video.comments)"></span></span>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </div>
                    <!-- Info -->
                    <div class="p-2.5">
                        <p class="text-xs text-white/80 font-medium line-clamp-2 mb-1.5" x-text="video.title || 'Sem titulo'"></p>
                        <div class="flex items-center justify-between text-[10px] text-white/40 mb-2">
                            <span class="truncate" x-text="'@' + (video.creator_username || 'unknown')"></span>
                            <span class="px-1.5 py-0.5 rounded text-[10px] font-semibold flex-shrink-0"
                                  :style="'background:' + (video.engagement_rate >= 5 ? '#22c55e' : '#3b82f6') + '15; color:' + (video.engagement_rate >= 5 ? '#22c55e' : '#3b82f6')"
                                  x-text="(video.engagement_rate || 0).toFixed(1) + '%'"></span>
                        </div>
                        <a :href="video.shop_product_url" target="_blank" class="block w-full px-3 py-1.5 rounded-lg gradient-brand text-white text-[10px] font-semibold text-center hover:opacity-90 transition">
                            <i data-lucide="external-link" class="w-3 h-3 inline mr-1"></i> Ver Produto
                        </a>
                    </div>
                </div>
            </template>
        </div>

        <div x-show="viralVideos.length < viralVideosTotal" class="text-center mt-6">
            <button @click="loadMoreViralVideos()" class="px-6 py-2.5 rounded-xl glass-light text-white/60 font-medium text-sm hover:text-white transition">
                Carregar mais...
            </button>
        </div>

        <div x-show="viralVideosTotal === 0 && !loading" class="text-center py-12">
            <i data-lucide="package-search" class="w-12 h-12 text-white/10 mx-auto mb-4"></i>
            <p class="text-white/30 text-sm">Nenhum video com produto encontrado ainda</p>
            <p class="text-white/20 text-xs mt-2">O scanner detecta automaticamente videos que promovem produtos TikTok Shop</p>
        </div>
    </div>

    <!-- ═══════════ RELATORIOS (Cross-Reference Reports) ═══════════ -->
    <div x-show="activeTab === 'reports'" x-cloak>
        <!-- Header with period filter -->
        <div class="glass rounded-2xl p-4 mb-6 animate-fade-up">
            <div class="flex flex-wrap items-center gap-3">
                <h3 class="text-sm font-bold text-white/80 flex items-center gap-2">
                    <i data-lucide="bar-chart-3" class="w-4 h-4 text-brand-400"></i> Relatorios Brasil
                    <span class="text-[10px] text-white/30 font-normal ml-1">Dados cruzados Scanner + Shop</span>
                </h3>
                <div class="flex items-center gap-1 bg-white/5 rounded-xl p-0.5 ml-auto">
                    <template x-for="d in [7, 15, 30, 60, 90]" :key="d">
                        <button @click="reportsDays = d; loadReports()" class="px-2.5 py-1 rounded-lg text-[11px] font-semibold transition"
                            :class="reportsDays === d ? 'gradient-brand text-white' : 'text-white/40'" x-text="d + 'd'"></button>
                    </template>
                </div>
            </div>
        </div>

        <div x-show="reportsLoading" class="text-center py-12">
            <div class="w-5 h-5 border-2 border-brand-400 border-t-transparent rounded-full animate-spin mx-auto"></div>
        </div>

        <div x-show="!reportsLoading && reportsData">
            <!-- KPI Cards -->
            <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 mb-6 animate-fade-up">
                <div class="glass-card rounded-2xl p-4 text-center">
                    <p class="text-2xl font-black text-white" x-text="reportsData.kpis.total_videos"></p>
                    <p class="text-[10px] text-white/40 mt-1">Videos BR</p>
                </div>
                <div class="glass-card rounded-2xl p-4 text-center">
                    <p class="text-2xl font-black text-brand-300" x-text="reportsData.kpis.total_creators"></p>
                    <p class="text-[10px] text-white/40 mt-1">Creators BR</p>
                </div>
                <div class="glass-card rounded-2xl p-4 text-center">
                    <p class="text-2xl font-black text-accent-green" x-text="reportsData.kpis.videos_with_product"></p>
                    <p class="text-[10px] text-white/40 mt-1">Videos com Produto</p>
                </div>
                <div class="glass-card rounded-2xl p-4 text-center">
                    <p class="text-2xl font-black text-accent-orange" x-text="reportsData.kpis.shop_rate + '%'"></p>
                    <p class="text-[10px] text-white/40 mt-1">Taxa Shop</p>
                </div>
                <div class="glass-card rounded-2xl p-4 text-center">
                    <p class="text-2xl font-black text-white" x-text="reportsData.kpis.total_views_formatted"></p>
                    <p class="text-[10px] text-white/40 mt-1">Total Views</p>
                </div>
                <div class="glass-card rounded-2xl p-4 text-center">
                    <p class="text-2xl font-black text-yellow-400" x-text="reportsData.kpis.avg_viral_score"></p>
                    <p class="text-[10px] text-white/40 mt-1">Avg Viral Score</p>
                </div>
            </div>

            <!-- Nicho Performance Chart + Cards -->
            <div class="glass rounded-2xl p-5 mb-6 animate-fade-up">
                <h4 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                    <i data-lucide="pie-chart" class="w-4 h-4 text-brand-400"></i> Performance por Nicho
                </h4>
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <div class="h-[350px]">
                        <canvas id="reportNichoChart"></canvas>
                    </div>
                    <div class="space-y-2 overflow-y-auto max-h-[350px]">
                        <template x-for="n in reportsData.nicho_performance" :key="n.category">
                            <div class="glass-card rounded-xl p-3 flex items-center justify-between">
                                <div>
                                    <p class="text-sm font-semibold text-white/90" x-text="n.category_name"></p>
                                    <p class="text-[10px] text-white/40" x-text="n.video_count + ' videos • ' + n.shop_count + ' com shop (' + n.shop_rate + '%)'"></p>
                                </div>
                                <div class="text-right">
                                    <p class="text-sm font-bold text-white" x-text="n.total_views_formatted"></p>
                                    <p class="text-[10px] text-white/40" x-text="'Viral: ' + n.avg_viral + ' • Eng: ' + n.avg_eng + '%'"></p>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
            </div>

            <!-- Creator x Produto -->
            <div class="glass rounded-2xl p-5 mb-6 animate-fade-up">
                <h4 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                    <i data-lucide="shopping-bag" class="w-4 h-4 text-accent-green"></i> Top Creators com Produtos na Shop
                    <span class="text-[10px] text-white/30 font-normal">Creators com mais videos promovendo produtos</span>
                </h4>
                <div class="space-y-2">
                    <template x-for="(c, idx) in reportsData.creator_x_produto" :key="c.username">
                        <div class="glass-card rounded-xl p-3">
                            <div class="flex items-center gap-3">
                                <div class="w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold flex-shrink-0"
                                     :class="idx < 3 ? 'gradient-fire text-white' : 'glass text-white/50'" x-text="'#' + (idx + 1)"></div>
                                <div class="w-10 h-10 rounded-full bg-dark-800 overflow-hidden flex-shrink-0">
                                    <img :src="c.avatar" class="w-full h-full object-cover" onerror="this.style.display='none'">
                                </div>
                                <div class="flex-1 min-w-0">
                                    <p class="text-sm font-semibold text-white/90" x-text="c.display_name"></p>
                                    <p class="text-[10px] text-white/40" x-text="'@' + c.username + ' • ' + c.followers_formatted + ' seguidores • ' + c.size_tier"></p>
                                </div>
                                <div class="hidden md:grid grid-cols-4 gap-4 flex-shrink-0 text-center">
                                    <div>
                                        <p class="text-sm font-bold text-accent-green" x-text="c.shop_videos"></p>
                                        <p class="text-[10px] text-white/30">Videos Shop</p>
                                    </div>
                                    <div>
                                        <p class="text-sm font-bold text-white" x-text="c.total_views_formatted"></p>
                                        <p class="text-[10px] text-white/30">Views</p>
                                    </div>
                                    <div>
                                        <p class="text-sm font-bold text-purple-400" x-text="c.avg_viral"></p>
                                        <p class="text-[10px] text-white/30">Viral Score</p>
                                    </div>
                                    <div>
                                        <p class="text-sm font-bold text-yellow-400" x-text="c.avg_eng + '%'"></p>
                                        <p class="text-[10px] text-white/30">Engajamento</p>
                                    </div>
                                </div>
                                <div class="md:hidden flex flex-col items-end gap-0.5">
                                    <span class="text-xs font-bold text-accent-green" x-text="c.shop_videos + ' shop'"></span>
                                    <span class="text-xs text-white/60" x-text="c.total_views_formatted"></span>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
                <div x-show="reportsData.creator_x_produto.length === 0" class="text-center py-8">
                    <p class="text-white/30 text-sm">Nenhum creator com produtos detectado no periodo</p>
                </div>
            </div>

            <!-- Growth Insights -->
            <div class="glass rounded-2xl p-5 mb-6 animate-fade-up">
                <h4 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                    <i data-lucide="rocket" class="w-4 h-4 text-accent-orange"></i> Creators em Crescimento
                    <span class="text-[10px] text-white/30 font-normal">Maior velocidade de views/dia no periodo</span>
                </h4>
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    <div class="h-[300px]">
                        <canvas id="reportGrowthChart"></canvas>
                    </div>
                    <div class="space-y-2 overflow-y-auto max-h-[300px]">
                        <template x-for="(g, idx) in reportsData.growth_insights" :key="g.username">
                            <div class="glass-card rounded-xl p-3">
                                <div class="flex items-center gap-3">
                                    <div class="w-7 h-7 rounded-lg flex items-center justify-center text-[10px] font-bold flex-shrink-0"
                                         :class="idx < 3 ? 'gradient-fire text-white' : 'glass text-white/50'" x-text="'#' + (idx + 1)"></div>
                                    <div class="flex-1 min-w-0">
                                        <p class="text-xs font-semibold text-white/90" x-text="g.display_name"></p>
                                        <p class="text-[10px] text-white/40" x-text="'@' + g.username + ' • ' + g.followers_formatted + ' seg'"></p>
                                    </div>
                                    <div class="text-right">
                                        <p class="text-sm font-bold text-accent-orange" x-text="g.velocity_formatted + '/dia'"></p>
                                        <p class="text-[10px] text-white/40" x-text="g.video_count + ' videos • ' + g.total_views_formatted + ' views'"></p>
                                    </div>
                                    <span x-show="g.shop_count > 0" class="px-2 py-0.5 rounded-lg text-[10px] font-bold bg-green-500/20 text-green-400 flex-shrink-0" x-text="g.shop_count + ' shop'"></span>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
            </div>
        </div>

        <div x-show="!reportsLoading && !reportsData" class="text-center py-16">
            <i data-lucide="bar-chart-3" class="w-12 h-12 text-white/10 mx-auto mb-4"></i>
            <p class="text-white/40 text-sm">Clique em um periodo para gerar os relatorios</p>
        </div>
    </div>

    <!-- ═══════════ STORE TAB ═══════════ -->
    <div x-show="activeTab === 'store'" x-cloak>
        <div class="glass rounded-2xl p-4 mb-6 animate-fade-up">
            <div class="flex gap-3">
                <div class="flex-1 flex items-center glass-light rounded-xl px-4 py-2.5">
                    <i data-lucide="store" class="w-4 h-4 text-white/30 mr-3"></i>
                    <input type="text" x-model="storeUrl" @keyup.enter="analyzeStore()" placeholder="Cole a URL da loja TikTok (ex: https://www.tiktok.com/shop/store/...)" class="bg-transparent border-none outline-none text-sm text-white/80 placeholder:text-white/25 w-full">
                </div>
                <button @click="analyzeStore()" :disabled="loading" class="px-5 py-2.5 rounded-xl gradient-ocean text-white font-semibold text-sm hover:opacity-90 transition flex items-center gap-2 disabled:opacity-50">
                    <i data-lucide="scan-search" class="w-4 h-4"></i> Analisar
                </button>
            </div>
        </div>
        <div x-show="!loading">
            <div x-show="storeInfo.shop_name" class="glass-card rounded-2xl p-6 mb-6">
                <div class="flex items-start gap-4">
                    <div class="w-16 h-16 rounded-2xl overflow-hidden flex-shrink-0">
                        <img x-show="storeInfo.shop_logo" :src="storeInfo.shop_logo" class="w-full h-full object-cover">
                        <div x-show="!storeInfo.shop_logo" class="w-full h-full gradient-brand flex items-center justify-center text-2xl font-bold text-white" x-text="(storeInfo.shop_name || '?')[0]"></div>
                    </div>
                    <div class="flex-1">
                        <h3 class="text-xl font-bold text-white mb-1" x-text="storeInfo.shop_name"></h3>
                        <p class="text-sm text-white/40 mb-3" x-text="(storeInfo.region || '') + (storeInfo.creator_name ? ' • ' + storeInfo.creator_name : '')"></p>
                        <div class="grid grid-cols-2 sm:grid-cols-5 gap-4">
                            <div><p class="text-lg font-bold text-white" x-text="storeInfo.format_sold_count || formatNumber(storeInfo.sold_count)"></p><p class="text-xs text-white/40">Vendas</p></div>
                            <div><p class="text-lg font-bold text-brand-300" x-text="storeInfo.format_followers_count || formatNumber(storeInfo.followers_count)"></p><p class="text-xs text-white/40">Seguidores</p></div>
                            <div><p class="text-lg font-bold text-yellow-400" x-text="storeInfo.shop_rating || '--'"></p><p class="text-xs text-white/40">Rating</p></div>
                            <div><p class="text-lg font-bold text-accent-cyan" x-text="storeInfo.on_sell_product_count || '0'"></p><p class="text-xs text-white/40">Produtos</p></div>
                            <div><p class="text-lg font-bold text-accent-green" x-text="formatNumber(storeInfo.review_count)"></p><p class="text-xs text-white/40">Reviews</p></div>
                        </div>
                    </div>
                </div>
            </div>
            <div x-show="storeProducts.length > 0" class="grid-cards">
                <template x-for="product in storeProducts" :key="product.product_id">
                    <div class="glass-card rounded-2xl overflow-hidden">
                        <div class="relative aspect-square bg-dark-800">
                            <img :src="product.image" :alt="product.title" class="w-full h-full object-cover" onerror="this.style.display='none'">
                        </div>
                        <div class="p-4 space-y-2">
                            <h3 class="text-sm font-semibold text-white/90 line-clamp-2" x-text="product.title"></h3>
                            <div class="flex items-center justify-between">
                                <span class="text-base font-bold text-accent-green" x-text="product.price || 'N/A'"></span>
                                <span class="text-xs text-white/40" x-text="formatNumber(product.sold_count) + ' vendidos'"></span>
                            </div>
                            <button @click="monitorProduct(product)" class="w-full flex items-center justify-center gap-2 px-3 py-2 rounded-xl glass-light text-white/60 hover:text-accent-green text-xs transition">
                                <i data-lucide="activity" class="w-3.5 h-3.5"></i> Monitorar
                            </button>
                        </div>
                    </div>
                </template>
            </div>
        </div>
    </div>

    <!-- ═══════════ SAVED TAB ═══════════ -->
    <div x-show="activeTab === 'saved'" x-cloak>
        <div x-show="!loading">
            <div x-show="savedProducts.length > 0" class="flex items-center justify-between mb-4">
                <p class="text-sm text-white/40"><span class="text-white font-semibold" x-text="savedTotal"></span> produtos salvos</p>
                <div class="flex gap-2">
                    <button @click="loadSaved('sold_count')" class="text-xs font-medium text-white/40 hover:text-white/80 transition">Mais Vendidos</button>
                    <button @click="loadSaved('recent')" class="text-xs font-medium text-white/40 hover:text-white/80 transition">Recentes</button>
                    <button @click="loadSaved('rating')" class="text-xs font-medium text-white/40 hover:text-white/80 transition">Melhor Avaliados</button>
                </div>
            </div>
            <div class="grid-cards">
                <template x-for="product in savedProducts" :key="product.id">
                    <div class="glass-card rounded-2xl overflow-hidden">
                        <div class="relative aspect-square bg-dark-800">
                            <img :src="product.image" :alt="product.title" class="w-full h-full object-cover" onerror="this.style.display='none'">
                            <div class="absolute top-3 right-3">
                                <span class="px-2 py-1 rounded-lg text-[10px] font-bold gradient-fire text-white">
                                    <span x-text="product.sold_formatted"></span> vendidos
                                </span>
                            </div>
                            <div x-show="product.related_video_count > 0" class="absolute bottom-3 left-3">
                                <span class="px-2 py-1 rounded-lg text-[10px] font-bold gradient-ocean text-white">
                                    <span x-text="product.related_video_count"></span> videos
                                </span>
                            </div>
                        </div>
                        <div class="p-4 space-y-3">
                            <h3 class="text-sm font-semibold text-white/90 line-clamp-2" x-text="product.title"></h3>
                            <div class="flex items-center justify-between">
                                <span class="text-lg font-bold text-accent-green" x-text="product.price || 'N/A'"></span>
                                <span class="text-xs text-white/30" x-text="'Rating: ' + (product.rating || '--')"></span>
                            </div>
                            <div class="grid grid-cols-3 gap-2 pt-2 border-t border-white/5">
                                <div class="text-center">
                                    <p class="text-xs font-bold text-white/80" x-text="product.sold_formatted"></p>
                                    <p class="text-[10px] text-white/30">Vendidos</p>
                                </div>
                                <div class="text-center">
                                    <p class="text-xs font-bold text-white/80" x-text="formatNumber(product.review_count)"></p>
                                    <p class="text-[10px] text-white/30">Reviews</p>
                                </div>
                                <div class="text-center">
                                    <p class="text-xs font-bold text-white/80" x-text="formatNumber(product.stock)"></p>
                                    <p class="text-[10px] text-white/30">Estoque</p>
                                </div>
                            </div>
                            <div class="flex gap-2">
                                <button @click="viewProduct(product)" class="flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-xl gradient-brand text-white font-medium text-xs hover:opacity-90 transition">
                                    <i data-lucide="eye" class="w-3.5 h-3.5"></i> Detalhes
                                </button>
                                <button @click="monitorProduct(product)" class="flex items-center justify-center px-3 py-2 rounded-xl glass-light text-white/60 hover:text-accent-green text-xs transition" title="Monitorar">
                                    <i data-lucide="activity" class="w-3.5 h-3.5"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
            <div x-show="savedProducts.length === 0" class="text-center py-16">
                <i data-lucide="package" class="w-12 h-12 text-white/20 mx-auto mb-4"></i>
                <p class="text-white/40">Nenhum produto salvo. Busque e analise produtos para salvar.</p>
            </div>
        </div>
    </div>

    <!-- ═══════════ PRODUCT DETAIL MODAL ═══════════ -->
    <div x-show="selectedProduct" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
         @click.self="selectedProduct = null" @keydown.escape.window="selectedProduct = null" x-transition>
        <div class="glass rounded-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto" @click.stop>
            <div class="p-4 flex items-center justify-between border-b border-white/5">
                <h3 class="font-bold text-white/90 truncate pr-4">Detalhes do Produto</h3>
                <button @click="selectedProduct = 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-4 space-y-4">
                <div x-show="productDetails">
                    <h3 class="text-lg font-bold text-white mb-3" x-text="productDetails?.title"></h3>
                    <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-4">
                        <div class="glass-light rounded-xl p-3 text-center">
                            <p class="text-lg font-bold text-accent-green" x-text="productDetails?.price || 'N/A'"></p>
                            <p class="text-[10px] text-white/40">Preco</p>
                        </div>
                        <div class="glass-light rounded-xl p-3 text-center">
                            <p class="text-lg font-bold text-white" x-text="formatNumber(productDetails?.stock || 0)"></p>
                            <p class="text-[10px] text-white/40">Estoque</p>
                        </div>
                        <div class="glass-light rounded-xl p-3 text-center">
                            <p class="text-lg font-bold text-accent-orange" x-text="productDetails?.related_video_count || 0"></p>
                            <p class="text-[10px] text-white/40">Videos Promo</p>
                        </div>
                        <div class="glass-light rounded-xl p-3 text-center">
                            <p class="text-lg font-bold text-yellow-400" x-text="productDetails?.shop?.rating || '--'"></p>
                            <p class="text-[10px] text-white/40">Rating Loja</p>
                        </div>
                    </div>

                    <!-- Monitor button in modal -->
                    <div class="flex gap-3 mb-4">
                        <button @click="monitorFromDetails()" class="flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl gradient-success text-white font-semibold text-sm hover:opacity-90 transition">
                            <i data-lucide="activity" class="w-4 h-4"></i> Monitorar Vendas
                        </button>
                        <a x-show="productDetails?.url || selectedProduct?.url" :href="productDetails?.url || selectedProduct?.url" target="_blank" rel="noopener" class="flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl glass-card text-white/80 font-medium text-sm hover:text-white">
                            <i data-lucide="external-link" class="w-4 h-4"></i> Abrir
                        </a>
                    </div>

                    <!-- Related Videos -->
                    <div x-show="productDetails?.related_videos?.length > 0">
                        <h4 class="text-sm font-semibold text-white/70 mb-3 flex items-center gap-2">
                            <i data-lucide="video" class="w-4 h-4"></i> Videos Promovendo Este Produto
                        </h4>
                        <div class="space-y-2 max-h-60 overflow-y-auto">
                            <template x-for="(vid, i) in productDetails?.related_videos || []" :key="i">
                                <a :href="vid.url" target="_blank" rel="noopener" class="flex items-center gap-3 glass-light rounded-xl p-3 hover:bg-white/10 transition">
                                    <div class="w-10 h-10 rounded-lg gradient-brand flex items-center justify-center flex-shrink-0">
                                        <i data-lucide="play" class="w-5 h-5 text-white"></i>
                                    </div>
                                    <div class="flex-1 min-w-0">
                                        <p class="text-xs text-white/70 truncate" x-text="vid.description || 'Video promocional'"></p>
                                        <p class="text-[10px] text-white/40" x-text="'@' + (vid.author || 'criador') + ' • ' + formatNumber(vid.views) + ' views'"></p>
                                    </div>
                                    <i data-lucide="external-link" class="w-4 h-4 text-white/30 flex-shrink-0"></i>
                                </a>
                            </template>
                        </div>
                    </div>

                    <div x-show="productDetails?.description" class="mt-4">
                        <h4 class="text-sm font-semibold text-white/70 mb-2">Descricao</h4>
                        <p class="text-xs text-white/40 leading-relaxed whitespace-pre-line" x-text="(productDetails?.description || '').substring(0, 500)"></p>
                    </div>
                </div>
                <div x-show="loadingDetail" class="flex items-center justify-center py-8">
                    <div class="w-6 h-6 border-2 border-brand-400 border-t-transparent rounded-full animate-spin"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══════════ REVENUE MODAL ═══════════ -->
    <div x-show="revenueModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm"
         @click.self="revenueModal = false" @keydown.escape.window="revenueModal = false" x-transition>
        <div class="glass rounded-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto" @click.stop>
            <div class="p-4 flex items-center justify-between border-b border-white/5">
                <h3 class="font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="bar-chart-3" class="w-5 h-5 text-accent-green"></i> Revenue Tracking
                </h3>
                <button @click="revenueModal = 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-4 space-y-4">
                <div x-show="revenueData">
                    <!-- Revenue stats -->
                    <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-4">
                        <div class="glass-light rounded-xl p-3 text-center">
                            <p class="text-xl font-bold text-accent-green" x-text="revenueData?.estimated_revenue_formatted || 'R$ 0'"></p>
                            <p class="text-[10px] text-white/40">Revenue Estimado</p>
                        </div>
                        <div class="glass-light rounded-xl p-3 text-center">
                            <p class="text-xl font-bold text-white" x-text="formatNumber(revenueData?.total_sold || 0)"></p>
                            <p class="text-[10px] text-white/40">Vendas no Periodo</p>
                        </div>
                        <div class="glass-light rounded-xl p-3 text-center">
                            <p class="text-xl font-bold text-brand-300" x-text="(revenueData?.avg_daily_sales || 0).toFixed(1)"></p>
                            <p class="text-[10px] text-white/40">Vendas/Dia</p>
                        </div>
                        <div class="glass-light rounded-xl p-3 text-center">
                            <p class="text-xl font-bold" :class="revenueData?.trend === 'accelerating' ? 'text-accent-green' : revenueData?.trend === 'decelerating' ? 'text-accent-red' : 'text-white/60'" x-text="revenueData?.velocity || '--'"></p>
                            <p class="text-[10px] text-white/40">Tendencia</p>
                        </div>
                    </div>

                    <!-- Chart -->
                    <div class="glass-light rounded-xl p-4 mb-4">
                        <canvas id="revenueChart" height="200"></canvas>
                    </div>

                    <!-- Daily breakdown -->
                    <div x-show="revenueData?.daily_sales?.length > 0">
                        <h4 class="text-sm font-semibold text-white/70 mb-3">Detalhamento por Periodo</h4>
                        <div class="overflow-x-auto">
                            <table class="w-full text-xs">
                                <thead>
                                    <tr class="text-white/40 border-b border-white/5">
                                        <th class="text-left py-2 px-3">Data</th>
                                        <th class="text-right py-2 px-3">Vendas</th>
                                        <th class="text-right py-2 px-3">Vendas/Hora</th>
                                        <th class="text-right py-2 px-3">Estoque</th>
                                        <th class="text-right py-2 px-3">Preco</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <template x-for="(day, i) in revenueData?.daily_sales || []" :key="i">
                                        <tr class="border-b border-white/5 text-white/70">
                                            <td class="py-2 px-3" x-text="day.date"></td>
                                            <td class="text-right py-2 px-3 font-bold" :class="day.sold > 0 ? 'text-accent-green' : ''" x-text="'+' + day.sold"></td>
                                            <td class="text-right py-2 px-3" x-text="day.per_hour"></td>
                                            <td class="text-right py-2 px-3" x-text="formatNumber(day.stock)"></td>
                                            <td class="text-right py-2 px-3" x-text="day.price"></td>
                                        </tr>
                                    </template>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <div x-show="revenueData?.days_tracked === 0" class="text-center py-8">
                        <i data-lucide="clock" class="w-10 h-10 text-white/20 mx-auto mb-3"></i>
                        <p class="text-sm text-white/40 mb-2">Dados insuficientes para calcular revenue</p>
                        <p class="text-xs text-white/30">Precisa de pelo menos 2 snapshots. Clique em "Atualizar" para coletar mais dados.</p>
                    </div>
                </div>
                <div x-show="loadingRevenue" class="flex items-center justify-center py-8">
                    <div class="w-6 h-6 border-2 border-accent-green border-t-transparent rounded-full animate-spin"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══════════ ANALISE IA ═══════════ -->
    <div x-show="activeTab === 'analytics'" x-cloak class="space-y-4">
        <!-- Shop Alerts -->
        <template x-if="shopAlerts.length > 0">
            <div class="space-y-2">
                <h3 class="text-sm font-bold text-white/60 flex items-center gap-2"><i data-lucide="bell" class="w-4 h-4 text-yellow-400"></i> Alertas de Produtos</h3>
                <template x-for="alert in shopAlerts.slice(0,5)" :key="alert.title">
                    <div class="glass rounded-xl p-3 flex items-center gap-3 border-l-4"
                         :class="{
                            'border-red-500': alert.priority === 'urgent',
                            'border-orange-500': alert.priority === 'high',
                            'border-blue-500': alert.priority === 'medium',
                            'border-gray-500': alert.priority === 'low',
                         }">
                        <i :data-lucide="alert.icon || 'bell'" class="w-4 h-4 flex-shrink-0"
                           :class="alert.priority === 'urgent' ? 'text-red-400' : alert.priority === 'high' ? 'text-orange-400' : 'text-blue-400'"></i>
                        <div class="flex-1 min-w-0">
                            <p class="text-sm font-semibold text-white/90 truncate" x-text="alert.title"></p>
                            <p class="text-xs text-white/40 truncate" x-text="alert.detail"></p>
                        </div>
                        <span class="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase flex-shrink-0"
                              :class="alert.type === 'sales_spike' ? 'bg-emerald-500/20 text-emerald-400' : alert.type === 'price_change' ? 'bg-orange-500/20 text-orange-400' : alert.type === 'low_stock' ? 'bg-red-500/20 text-red-400' : 'bg-blue-500/20 text-blue-400'"
                              x-text="alert.type.replace('_',' ')"></span>
                    </div>
                </template>
            </div>
        </template>

        <!-- Viral Products -->
        <div class="glass rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="zap" class="w-5 h-5 text-orange-400"></i> Produtos Virais (Crescimento Explosivo)
                </h2>
                <p class="text-xs text-white/40 mt-1">Produtos com maior velocidade de vendas nos ultimos 7 dias</p>
            </div>
            <div class="p-5">
                <div class="space-y-2">
                    <template x-for="(p, idx) in viralProducts" :key="p.product_id">
                        <div class="flex items-center gap-3 p-3 rounded-xl glass-light">
                            <div class="w-12 h-12 rounded-lg bg-white/10 overflow-hidden flex-shrink-0">
                                <img x-show="p.image" :src="p.image.startsWith('/') ? p.image : '/api/echotik/image/product/' + p.product_id + '.jpg'" class="w-full h-full object-cover" loading="lazy">
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="text-sm font-semibold text-white/90 truncate" x-text="p.title"></p>
                                <div class="flex items-center gap-3 text-xs text-white/40">
                                    <span x-text="p.price"></span>
                                    <span class="text-emerald-400 font-bold" x-text="'+' + p.delta_sold + ' vendas'"></span>
                                    <span x-text="p.daily_velocity + '/dia'"></span>
                                </div>
                            </div>
                            <div class="text-right flex-shrink-0">
                                <span class="px-2 py-0.5 rounded-full text-[10px] font-bold"
                                      :class="p.growth_percent > 200 ? 'bg-red-500/20 text-red-400 animate-pulse' : p.growth_percent > 100 ? 'bg-orange-500/20 text-orange-400' : 'bg-emerald-500/20 text-emerald-400'"
                                      x-text="p.viral_label"></span>
                                <p class="text-[10px] text-white/40 mt-1" x-text="'+' + p.growth_percent + '%'"></p>
                            </div>
                        </div>
                    </template>
                    <template x-if="viralProducts.length === 0 && !analyticsLoading">
                        <div class="text-center py-8 text-white/30 text-sm">Nenhum produto viral detectado. Monitore produtos para coletar snapshots.</div>
                    </template>
                </div>
            </div>
        </div>

        <!-- Category Heatmap -->
        <div class="glass rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="flame" class="w-5 h-5 text-red-400"></i> Heatmap de Categorias
                </h2>
                <p class="text-xs text-white/40 mt-1">Quais categorias de produto estao mais quentes agora</p>
            </div>
            <div class="p-5">
                <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3">
                    <template x-for="[cat, data] in Object.entries(categoryHeatmap)" :key="cat">
                        <div class="rounded-xl p-4 border transition cursor-default"
                             :class="{
                                'bg-red-500/10 border-red-500/30': data.status === 'fire',
                                'bg-orange-500/10 border-orange-500/30': data.status === 'hot',
                                'bg-yellow-500/10 border-yellow-500/20': data.status === 'warm',
                                'bg-white/5 border-white/10': data.status === 'cold',
                             }">
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-xs font-bold text-white/90" x-text="data.name"></span>
                                <span class="text-[10px] font-bold uppercase"
                                      :class="{
                                         'text-red-400': data.status === 'fire',
                                         'text-orange-400': data.status === 'hot',
                                         'text-yellow-400': data.status === 'warm',
                                         'text-gray-400': data.status === 'cold',
                                      }" x-text="data.status"></span>
                            </div>
                            <div class="space-y-1 text-[10px]">
                                <div class="flex justify-between"><span class="text-white/40">Videos</span><span class="text-white/70 font-bold" x-text="data.video_count"></span></div>
                                <div class="flex justify-between"><span class="text-white/40">Score</span><span class="text-brand-300 font-bold" x-text="data.avg_score"></span></div>
                                <div class="flex justify-between"><span class="text-white/40">Com Shop</span><span class="text-emerald-400 font-bold" x-text="data.shop_rate + '%'"></span></div>
                                <div class="flex justify-between"><span class="text-white/40">Crescimento</span>
                                    <span class="font-bold" :class="data.growth_percent > 0 ? 'text-emerald-400' : 'text-red-400'"
                                          x-text="(data.growth_percent > 0 ? '+' : '') + data.growth_percent + '%'"></span>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
                <template x-if="Object.keys(categoryHeatmap).length === 0 && !analyticsLoading">
                    <div class="text-center py-8 text-white/30 text-sm">Carregando heatmap...</div>
                </template>
            </div>
        </div>
    </div>

    <!-- ═══════════ AFILIADOS ═══════════ -->
    <div x-show="activeTab === 'affiliates'" x-cloak class="space-y-4">
        <!-- Top Commission Products -->
        <div class="glass rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="dollar-sign" class="w-5 h-5 text-emerald-400"></i> Melhores Oportunidades de Comissao
                </h2>
                <p class="text-xs text-white/40 mt-1">Produtos com maior potencial de ganho como afiliado</p>
            </div>
            <div class="p-5 space-y-2">
                <template x-for="(p, idx) in topCommissions" :key="p.product_id">
                    <div class="flex items-center gap-3 p-3 rounded-xl glass-light">
                        <div class="w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold"
                             :class="idx < 3 ? 'gradient-fire text-white' : 'bg-white/10 text-white/60'"
                             x-text="idx + 1"></div>
                        <div class="flex-1 min-w-0">
                            <p class="text-sm font-semibold text-white/90 truncate" x-text="p.title"></p>
                            <div class="flex items-center gap-3 text-xs text-white/40">
                                <span x-text="p.price"></span>
                                <span x-text="p.daily_sales + ' vendas/dia'"></span>
                                <span class="text-brand-300" x-text="p.commission_percent + '% comissao'"></span>
                            </div>
                        </div>
                        <div class="text-right flex-shrink-0">
                            <p class="text-sm font-bold text-emerald-400" x-text="p.monthly_formatted"></p>
                            <p class="text-[10px] text-white/40">estimado/mes</p>
                        </div>
                    </div>
                </template>
                <template x-if="topCommissions.length === 0 && !affiliateLoading">
                    <div class="text-center py-8 text-white/30 text-sm">Monitore produtos para ver oportunidades de comissao</div>
                </template>
            </div>
        </div>

        <!-- Affiliate Network -->
        <div class="glass rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="network" class="w-5 h-5 text-purple-400"></i> Rede de Afiliados
                </h2>
                <p class="text-xs text-white/40 mt-1">Quais creators estao promovendo quais produtos</p>
            </div>
            <div class="p-5 space-y-2">
                <template x-for="(c, idx) in affiliateNetwork" :key="c.creator_id">
                    <div class="glass-light rounded-xl p-4">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 rounded-full bg-white/10 overflow-hidden flex-shrink-0">
                                <img x-show="c.avatar_url" :src="c.avatar_url" class="w-full h-full object-cover" loading="lazy">
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="text-sm font-bold text-white/90" x-text="'@' + c.username"></p>
                                <div class="flex gap-3 text-xs text-white/40">
                                    <span x-text="fmtNum(c.followers) + ' seguidores'"></span>
                                    <span class="text-emerald-400" x-text="c.total_shop_videos + ' videos c/ produto'"></span>
                                    <span x-text="c.products_promoted + ' produtos'"></span>
                                </div>
                            </div>
                            <div class="text-right flex-shrink-0">
                                <p class="text-sm font-bold text-brand-300" x-text="fmtNum(c.total_views)"></p>
                                <p class="text-[10px] text-white/40">views total</p>
                            </div>
                        </div>
                        <!-- Products promoted -->
                        <div x-show="c.top_products && c.top_products.length > 0" class="flex flex-wrap gap-1">
                            <template x-for="prod in c.top_products.slice(0,3)" :key="prod.url">
                                <span class="px-2 py-0.5 rounded-md bg-white/5 text-[10px] text-white/50 truncate max-w-[200px]"
                                      x-text="fmtNum(prod.total_views) + ' views (' + prod.videos + ' vids)'"></span>
                            </template>
                        </div>
                    </div>
                </template>
                <template x-if="affiliateNetwork.length === 0 && !affiliateLoading">
                    <div class="text-center py-8 text-white/30 text-sm">Nenhum dado de afiliados. Colete videos com shop_product_url.</div>
                </template>
            </div>
        </div>
    </div>

    <!-- ═══════════ CALCULADORA ═══════════ -->
    <div x-show="activeTab === 'calculator'" x-cloak>
        <div class="glass rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="calculator" class="w-5 h-5 text-yellow-400"></i> Calculadora de Comissao
                </h2>
                <p class="text-xs text-white/40 mt-1">Estime seus ganhos como afiliado TikTok Shop</p>
            </div>
            <div class="p-5">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Inputs -->
                    <div class="space-y-4">
                        <div>
                            <label class="text-xs text-white/60 mb-1 block">Preco do Produto (R$)</label>
                            <input type="number" x-model.number="calcPrice" placeholder="49.90"
                                   class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 outline-none focus:border-brand-500/50">
                        </div>
                        <div>
                            <label class="text-xs text-white/60 mb-1 block">Categoria</label>
                            <select x-model="calcCategory" class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 outline-none">
                                <option value="moda">Moda (5-15%)</option>
                                <option value="beleza">Beleza (8-20%)</option>
                                <option value="casa">Casa (5-15%)</option>
                                <option value="eletronicos">Eletronicos (3-10%)</option>
                                <option value="esportes">Esportes (5-15%)</option>
                                <option value="saude">Saude (10-25%)</option>
                                <option value="outros">Outros (3-15%)</option>
                            </select>
                        </div>
                        <div>
                            <label class="text-xs text-white/60 mb-1 block">Vendas por dia estimadas</label>
                            <input type="number" x-model.number="calcDailySales" placeholder="10"
                                   class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 outline-none focus:border-brand-500/50">
                        </div>
                        <div>
                            <label class="text-xs text-white/60 mb-1 block">Comissao % (ou 0 para media da categoria)</label>
                            <input type="number" x-model.number="calcCommission" placeholder="0" step="0.5"
                                   class="w-full bg-white/5 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 outline-none focus:border-brand-500/50">
                        </div>
                        <button @click="calculateCommission()" :disabled="calcPrice <= 0"
                                class="w-full px-4 py-3 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-50">
                            Calcular Ganhos
                        </button>
                    </div>

                    <!-- Results -->
                    <div x-show="calcResult" class="space-y-4">
                        <div class="text-center p-6 rounded-2xl" :class="calcResult?.tier === 'ouro' ? 'bg-yellow-500/10 border border-yellow-500/30' : calcResult?.tier === 'prata' ? 'bg-gray-300/10 border border-gray-300/30' : 'bg-amber-700/10 border border-amber-700/30'">
                            <p class="text-3xl font-black" :class="calcResult?.tier === 'ouro' ? 'text-yellow-400' : calcResult?.tier === 'prata' ? 'text-gray-300' : 'text-amber-600'" x-text="calcResult?.monthly_formatted"></p>
                            <p class="text-sm text-white/50 mt-1">estimativa mensal</p>
                            <span class="inline-block mt-2 px-3 py-1 rounded-full text-xs font-bold uppercase"
                                  :class="calcResult?.tier === 'ouro' ? 'bg-yellow-500/20 text-yellow-400' : calcResult?.tier === 'prata' ? 'bg-gray-300/20 text-gray-300' : 'bg-amber-600/20 text-amber-600'"
                                  x-text="'Tier ' + (calcResult?.tier || '')"></span>
                        </div>
                        <div class="grid grid-cols-2 gap-3">
                            <div class="bg-white/5 rounded-xl p-3 text-center">
                                <p class="text-lg font-bold text-emerald-400" x-text="'R$ ' + (calcResult?.per_sale || 0).toFixed(2)"></p>
                                <p class="text-[10px] text-white/40">por venda</p>
                            </div>
                            <div class="bg-white/5 rounded-xl p-3 text-center">
                                <p class="text-lg font-bold text-brand-300" x-text="'R$ ' + (calcResult?.daily_revenue || 0).toFixed(2)"></p>
                                <p class="text-[10px] text-white/40">por dia</p>
                            </div>
                        </div>
                        <div class="bg-white/5 rounded-xl p-3 text-xs text-white/40">
                            <p>Comissao: <span class="text-white/70 font-bold" x-text="calcResult?.commission_percent + '%'"></span>
                               (Range: <span x-text="calcResult?.commission_range"></span>)</p>
                            <p class="mt-1" x-text="calcResult?.daily_sales + ' vendas/dia x R$ ' + (calcResult?.per_sale || 0).toFixed(2) + ' = R$ ' + (calcResult?.daily_revenue || 0).toFixed(2) + '/dia'"></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══════════ RECEITA LOJAS ═══════════ -->
    <div x-show="activeTab === 'store_revenue'" x-cloak class="space-y-4">
        <div class="glass rounded-2xl">
            <div class="p-5 border-b border-white/5 flex items-center justify-between">
                <div>
                    <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                        <i data-lucide="building-2" class="w-5 h-5 text-emerald-400"></i> Estimativa de Receita por Loja
                    </h2>
                    <p class="text-xs text-white/40 mt-1">Faturamento mensal estimado baseado em velocidade de vendas</p>
                </div>
                <div class="flex items-center gap-2">
                    <input type="text" x-model="storeSearch" @keyup.enter="loadStoreRevenue()" placeholder="Buscar loja..."
                           class="bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-xs text-white/80 outline-none w-40">
                    <button @click="loadStoreRevenue()" class="px-3 py-2 rounded-xl gradient-brand text-white text-xs font-medium">Buscar</button>
                </div>
            </div>
            <div x-show="storeRevenueLoading" class="p-8 text-center">
                <div class="w-5 h-5 border-2 border-brand-400 border-t-transparent rounded-full animate-spin mx-auto"></div>
            </div>
            <div class="p-5 space-y-3" x-show="!storeRevenueLoading && storeRevenues.length > 0">
                <template x-for="store in storeRevenues" :key="store.shop_name">
                    <div class="bg-white/5 rounded-xl p-4 hover:bg-white/10 transition">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="font-bold text-white/90 text-sm" x-text="store.shop_name"></p>
                                <p class="text-xs text-white/40" x-text="store.product_count + ' produtos | Rating: ' + store.avg_rating + ' | ' + store.top_category"></p>
                            </div>
                            <div class="text-right">
                                <p class="text-lg font-black text-emerald-400" x-text="store.revenue_formatted"></p>
                                <span class="text-[10px] px-2 py-0.5 rounded-full"
                                      :class="store.tier === 'mega' ? 'bg-yellow-500/20 text-yellow-400' : store.tier === 'grande' ? 'bg-emerald-500/20 text-emerald-400' : store.tier === 'medio' ? 'bg-blue-500/20 text-blue-400' : 'bg-white/10 text-white/40'"
                                      x-text="store.tier.toUpperCase()"></span>
                            </div>
                        </div>
                        <div class="mt-2 flex flex-wrap gap-2">
                            <template x-for="p in store.top_products" :key="p.product_id">
                                <span class="text-[10px] bg-white/5 rounded-lg px-2 py-1 text-white/50" x-text="p.title + ' (R$' + p.monthly_revenue.toFixed(0) + '/mes)'"></span>
                            </template>
                        </div>
                    </div>
                </template>
            </div>
            <div x-show="!storeRevenueLoading && storeRevenues.length === 0" class="p-8 text-center text-white/30 text-sm">Nenhuma loja encontrada</div>
        </div>
    </div>

    <!-- ═══════════ MATCHER AFILIADOS ═══════════ -->
    <div x-show="activeTab === 'matcher'" x-cloak class="space-y-4">
        <div class="glass rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="link-2" class="w-5 h-5 text-purple-400"></i> Matcher: Video Viral x Produto
                </h2>
                <p class="text-xs text-white/40 mt-1">Videos virais SEM produto vinculado + produtos que combinam = oportunidade de afiliado</p>
            </div>
            <div x-show="matcherLoading" class="p-8 text-center">
                <div class="w-5 h-5 border-2 border-brand-400 border-t-transparent rounded-full animate-spin mx-auto"></div>
            </div>
            <div class="p-5 space-y-3" x-show="!matcherLoading && matcherResults.length > 0">
                <template x-for="m in matcherResults" :key="m.video.id">
                    <div class="bg-white/5 rounded-xl p-4 hover:bg-white/10 transition">
                        <div class="flex gap-4">
                            <div class="flex-1">
                                <p class="text-xs text-purple-400 font-bold mb-1">VIDEO VIRAL</p>
                                <p class="text-sm font-medium text-white/80" x-text="m.video.title"></p>
                                <p class="text-[10px] text-white/40 mt-1" x-text="fmtNum(m.video.views) + ' views | Score: ' + m.video.viral_score"></p>
                            </div>
                            <div class="text-center px-3">
                                <i data-lucide="arrow-right" class="w-5 h-5 text-yellow-400 mx-auto"></i>
                                <p class="text-[10px] text-yellow-400 mt-1" x-text="'Match: ' + m.match_score"></p>
                            </div>
                            <div class="flex-1 text-right">
                                <p class="text-xs text-emerald-400 font-bold mb-1">PRODUTO</p>
                                <p class="text-sm font-medium text-white/80" x-text="m.product.title?.substring(0, 40)"></p>
                                <p class="text-[10px] text-white/40 mt-1" x-text="m.product.price + ' | ' + fmtNum(m.product.sold_count) + ' vendidos'"></p>
                                <p class="text-xs text-emerald-400 mt-1" x-text="'Est. R$' + m.estimated_commission.toFixed(2) + '/venda'"></p>
                            </div>
                        </div>
                        <p class="text-xs text-white/30 mt-2 italic" x-text="m.suggestion"></p>
                    </div>
                </template>
            </div>
            <div x-show="!matcherLoading && matcherResults.length === 0" class="p-8 text-center text-white/30 text-sm">Nenhum match encontrado</div>
        </div>
    </div>

    <!-- ═══════════ OTIMIZADOR DE COMISSAO ═══════════ -->
    <div x-show="activeTab === 'optimizer'" x-cloak class="space-y-4">
        <div class="glass rounded-2xl">
            <div class="p-5 border-b border-white/5 flex items-center justify-between">
                <div>
                    <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                        <i data-lucide="target" class="w-5 h-5 text-orange-400"></i> Otimizador de Comissao
                    </h2>
                    <p class="text-xs text-white/40 mt-1">Maximize seus ganhos com o mix ideal de produtos</p>
                </div>
                <div class="flex items-center gap-2">
                    <label class="text-xs text-white/50">Horas/mes:</label>
                    <input type="number" x-model.number="optimizerBudget" min="5" max="100"
                           class="bg-white/5 border border-white/10 rounded-xl px-3 py-2 text-xs text-white/80 outline-none w-20">
                    <button @click="loadOptimizer()" class="px-3 py-2 rounded-xl gradient-brand text-white text-xs font-medium">Otimizar</button>
                </div>
            </div>
            <div x-show="optimizerLoading" class="p-8 text-center">
                <div class="w-5 h-5 border-2 border-brand-400 border-t-transparent rounded-full animate-spin mx-auto"></div>
            </div>
            <div x-show="!optimizerLoading && optimizerResult" class="p-5">
                <div class="grid grid-cols-3 gap-4 mb-4">
                    <div class="bg-emerald-500/10 rounded-xl p-4 text-center border border-emerald-500/20">
                        <p class="text-2xl font-black text-emerald-400" x-text="optimizerResult?.total_formatted"></p>
                        <p class="text-xs text-white/40">Receita mensal estimada</p>
                    </div>
                    <div class="bg-white/5 rounded-xl p-4 text-center">
                        <p class="text-2xl font-black text-brand-300" x-text="optimizerResult?.hours_used + '/' + optimizerResult?.budget_hours + 'h'"></p>
                        <p class="text-xs text-white/40">Horas utilizadas</p>
                    </div>
                    <div class="bg-white/5 rounded-xl p-4 text-center">
                        <p class="text-2xl font-black text-yellow-400" x-text="'R$' + (optimizerResult?.avg_roi_per_hour || 0).toFixed(0) + '/h'"></p>
                        <p class="text-xs text-white/40">ROI por hora</p>
                    </div>
                </div>
                <div class="space-y-2">
                    <p class="text-xs text-white/50 font-bold mb-2">PRODUTOS SELECIONADOS (melhor ROI)</p>
                    <template x-for="(p, i) in optimizerResult?.selected_products || []" :key="i">
                        <div class="bg-white/5 rounded-xl p-3 flex items-center justify-between">
                            <div class="flex items-center gap-3">
                                <span class="text-lg font-black text-white/20" x-text="i + 1"></span>
                                <div>
                                    <p class="text-sm text-white/80" x-text="p.title?.substring(0, 45)"></p>
                                    <p class="text-[10px] text-white/40" x-text="p.price + ' | ' + p.daily_sales + ' vendas/dia | ' + p.effort_hours + 'h esforco'"></p>
                                </div>
                            </div>
                            <div class="text-right">
                                <p class="text-sm font-bold text-emerald-400" x-text="p.monthly_formatted"></p>
                                <p class="text-[10px] text-yellow-400" x-text="p.roi_formatted + '/hora'"></p>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══════════ PRODUTOS SAZONAIS ═══════════ -->
    <div x-show="activeTab === 'seasonal'" x-cloak class="space-y-4">
        <div class="glass rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="calendar" class="w-5 h-5 text-pink-400"></i> Preditor de Produtos Sazonais
                </h2>
                <p class="text-xs text-white/40 mt-1">Antecipe a demanda com base em datas comemorativas e estacoes</p>
            </div>
            <div x-show="seasonalLoading" class="p-8 text-center">
                <div class="w-5 h-5 border-2 border-brand-400 border-t-transparent rounded-full animate-spin mx-auto"></div>
            </div>
            <div class="p-5 space-y-4" x-show="!seasonalLoading && seasonalData.length > 0">
                <template x-for="item in seasonalData" :key="item.event + item.month">
                    <div class="bg-white/5 rounded-xl p-4 hover:bg-white/10 transition"
                         :class="item.is_current ? 'border border-pink-500/30 bg-pink-500/5' : ''">
                        <div class="flex items-center justify-between mb-2">
                            <div class="flex items-center gap-2">
                                <span class="px-2 py-0.5 rounded-full text-[10px] font-bold"
                                      :class="item.is_current ? 'bg-pink-500/20 text-pink-400' : 'bg-white/10 text-white/50'"
                                      x-text="item.month_name"></span>
                                <p class="text-sm font-bold text-white/90" x-text="item.event"></p>
                            </div>
                            <span class="text-xs" :class="item.is_current ? 'text-pink-400 font-bold' : 'text-white/30'"
                                  x-text="item.is_current ? 'AGORA!' : 'em ' + item.offset_months + ' mes(es)'"></span>
                        </div>
                        <p class="text-xs text-white/40 mb-2" x-text="item.tip"></p>
                        <div class="flex flex-wrap gap-1">
                            <template x-for="kw in item.keywords" :key="kw">
                                <span class="text-[10px] bg-white/5 rounded px-2 py-0.5 text-white/40" x-text="kw"></span>
                            </template>
                        </div>
                        <div x-show="item.matching_products.length > 0" class="mt-2 flex flex-wrap gap-2">
                            <template x-for="p in item.matching_products.slice(0, 3)" :key="p.product_id">
                                <span class="text-[10px] bg-emerald-500/10 text-emerald-400 rounded-lg px-2 py-1" x-text="p.title?.substring(0, 35) + ' (' + p.price + ')'"></span>
                            </template>
                        </div>
                    </div>
                </template>
            </div>
        </div>
    </div>

    <!-- ═══════════ PREDITOR VIRAL ═══════════ -->
    <div x-show="activeTab === 'viral_predictor'" x-cloak class="space-y-4">
        <div class="glass rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="rocket" class="w-5 h-5 text-orange-400"></i> Preditor de Produtos Virais
                </h2>
                <p class="text-xs text-white/40 mt-1">IA identifica produtos prestes a viralizar com base em aceleracao de vendas e mencoes em videos</p>
            </div>
            <div x-show="viralPredictorLoading" class="p-8 text-center">
                <div class="w-5 h-5 border-2 border-orange-400 border-t-transparent rounded-full animate-spin mx-auto"></div>
                <p class="text-xs text-white/40 mt-2">Calculando predicoes com IA...</p>
            </div>
            <div class="p-5 space-y-4" x-show="!viralPredictorLoading && viralPredictions.length > 0">
                <!-- AI Commentary -->
                <div class="bg-orange-500/5 border border-orange-500/20 rounded-xl p-4" x-show="viralPredictorAI">
                    <p class="text-[10px] text-orange-400 font-bold mb-1">Analise IA</p>
                    <p class="text-xs text-white/60 whitespace-pre-line" x-text="viralPredictorAI"></p>
                </div>
                <!-- Product Cards -->
                <template x-for="(prod, idx) in viralPredictions" :key="prod.product_id">
                    <div class="bg-white/5 rounded-xl p-4 hover:bg-white/10 transition">
                        <div class="flex items-center justify-between mb-2">
                            <div class="flex items-center gap-2">
                                <span class="w-7 h-7 rounded-full bg-orange-500/20 flex items-center justify-center text-orange-400 text-xs font-bold" x-text="idx + 1"></span>
                                <p class="text-sm font-bold text-white/90" x-text="prod.title?.substring(0, 50)"></p>
                            </div>
                            <div class="flex items-center gap-2">
                                <span class="px-2 py-1 rounded-lg text-xs font-bold" :class="prod.viral_prediction_score >= 70 ? 'bg-red-500/20 text-red-400' : prod.viral_prediction_score >= 40 ? 'bg-orange-500/20 text-orange-400' : 'bg-white/10 text-white/40'" x-text="prod.viral_prediction_score + '/100'"></span>
                            </div>
                        </div>
                        <div class="grid grid-cols-4 gap-2 text-center mt-3">
                            <div>
                                <p class="text-sm font-bold text-cyan-400" x-text="prod.acceleration + '%'"></p>
                                <p class="text-[9px] text-white/40">Aceleracao</p>
                            </div>
                            <div>
                                <p class="text-sm font-bold text-purple-400" x-text="prod.video_mentions"></p>
                                <p class="text-[9px] text-white/40">Mencoes</p>
                            </div>
                            <div>
                                <p class="text-sm font-bold text-emerald-400" x-text="prod.price_formatted || prod.price"></p>
                                <p class="text-[9px] text-white/40">Preco</p>
                            </div>
                            <div>
                                <p class="text-sm font-bold text-yellow-400" x-text="prod.sold_count?.toLocaleString() || 0"></p>
                                <p class="text-[9px] text-white/40">Vendidos</p>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
            <div class="p-5 text-center text-white/30 text-sm" x-show="!viralPredictorLoading && viralPredictions.length === 0">
                Sem predicoes disponiveis. Tente sincronizar dados primeiro.
            </div>
        </div>
    </div>

    <!-- ═══════════ SCRIPTS PRODUTO ═══════════ -->
    <div x-show="activeTab === 'scripts'" x-cloak class="space-y-4">
        <div class="glass rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="file-text" class="w-5 h-5 text-violet-400"></i> Scripts de Produto (IA)
                </h2>
                <p class="text-xs text-white/40 mt-1">Gere roteiros de video e scripts de vendas com IA</p>
            </div>
            <div class="p-5">
                <!-- Form -->
                <div class="grid grid-cols-1 md:grid-cols-4 gap-3 mb-4">
                    <div>
                        <label class="text-[10px] text-white/40 mb-1 block">Product ID</label>
                        <input type="number" x-model="scriptProductId" placeholder="ID do produto" class="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:border-brand-500 outline-none">
                    </div>
                    <div>
                        <label class="text-[10px] text-white/40 mb-1 block">Tipo de Script</label>
                        <select x-model="scriptType" class="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:border-brand-500 outline-none">
                            <option value="video_review">Video Review</option>
                            <option value="video_unboxing">Video Unboxing</option>
                            <option value="video_comparacao">Video Comparacao</option>
                            <option value="video_tutorial">Video Tutorial</option>
                            <option value="video_storytelling">Video Storytelling</option>
                            <option value="sales">Script de Vendas</option>
                        </select>
                    </div>
                    <div>
                        <label class="text-[10px] text-white/40 mb-1 block">Publico</label>
                        <select x-model="scriptAudience" class="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:border-brand-500 outline-none">
                            <option value="geral">Geral</option>
                            <option value="jovens 18-25">Jovens 18-25</option>
                            <option value="mulheres 25-40">Mulheres 25-40</option>
                            <option value="homens 25-40">Homens 25-40</option>
                            <option value="maes">Maes</option>
                        </select>
                    </div>
                    <div class="flex items-end">
                        <button @click="generateScript()" :disabled="scriptLoading || !scriptProductId" class="w-full py-2.5 rounded-lg bg-violet-600 hover:bg-violet-500 disabled:opacity-50 text-white text-sm font-bold transition flex items-center justify-center gap-2">
                            <template x-if="!scriptLoading"><span class="flex items-center gap-1"><i data-lucide="sparkles" class="w-4 h-4"></i> Gerar</span></template>
                            <template x-if="scriptLoading"><span class="flex items-center gap-1"><div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div> Gerando...</span></template>
                        </button>
                    </div>
                </div>

                <!-- Script Result -->
                <div x-show="scriptResult" class="bg-white/5 rounded-xl p-5 space-y-3">
                    <div class="flex items-center justify-between mb-3">
                        <h3 class="text-sm font-bold text-violet-400" x-text="scriptResult?.product?.title?.substring(0, 40)"></h3>
                        <button @click="navigator.clipboard.writeText(JSON.stringify(scriptResult, null, 2)); showToast('Script copiado!', 'success')" class="px-3 py-1 rounded-lg bg-white/10 hover:bg-white/20 text-xs text-white/60 transition">
                            <i data-lucide="copy" class="w-3 h-3 inline"></i> Copiar
                        </button>
                    </div>
                    <!-- Video Template fields -->
                    <template x-if="scriptResult?.hook">
                        <div class="space-y-2 text-xs">
                            <div class="bg-violet-500/10 rounded-lg p-3">
                                <span class="text-violet-300 font-bold">Hook:</span>
                                <p class="text-white/70 mt-1" x-text="scriptResult.hook"></p>
                            </div>
                            <div x-show="scriptResult.intro"><span class="text-white/40">Intro:</span> <span class="text-white/70" x-text="scriptResult.intro"></span></div>
                            <div x-show="scriptResult.demo"><span class="text-white/40">Demo:</span> <span class="text-white/70" x-text="scriptResult.demo"></span></div>
                            <div x-show="scriptResult.prova_social"><span class="text-white/40">Prova Social:</span> <span class="text-white/70" x-text="scriptResult.prova_social"></span></div>
                            <div x-show="scriptResult.solution"><span class="text-white/40">Solucao:</span> <span class="text-white/70" x-text="scriptResult.solution"></span></div>
                            <div class="bg-emerald-500/10 rounded-lg p-3">
                                <span class="text-emerald-300 font-bold">CTA:</span>
                                <p class="text-white/70 mt-1" x-text="scriptResult.cta"></p>
                            </div>
                            <!-- Benefits -->
                            <template x-if="scriptResult.benefits?.length">
                                <div><span class="text-white/40">Beneficios:</span>
                                    <template x-for="b in scriptResult.benefits" :key="b"><span class="inline-block px-2 py-0.5 rounded bg-emerald-500/10 text-emerald-300 text-[10px] mr-1 mt-1" x-text="b"></span></template>
                                </div>
                            </template>
                            <!-- Objection Handling -->
                            <template x-if="scriptResult.objection_handling?.length">
                                <div class="mt-2">
                                    <p class="text-white/40 font-bold mb-1">Objecoes:</p>
                                    <template x-for="obj in scriptResult.objection_handling" :key="obj.objection">
                                        <div class="bg-white/5 rounded-lg p-2 mb-1">
                                            <p class="text-red-300 text-[10px]" x-text="'Q: ' + obj.objection"></p>
                                            <p class="text-emerald-300 text-[10px]" x-text="'R: ' + obj.response"></p>
                                        </div>
                                    </template>
                                </div>
                            </template>
                            <!-- Urgency & Price Anchoring -->
                            <div x-show="scriptResult.urgency" class="bg-red-500/10 rounded-lg p-2"><span class="text-red-300 text-[10px] font-bold">Urgencia:</span> <span class="text-white/60 text-[10px]" x-text="scriptResult.urgency"></span></div>
                            <div x-show="scriptResult.price_anchoring" class="bg-yellow-500/10 rounded-lg p-2"><span class="text-yellow-300 text-[10px] font-bold">Ancoragem:</span> <span class="text-white/60 text-[10px]" x-text="scriptResult.price_anchoring"></span></div>
                            <!-- Hashtags -->
                            <div x-show="scriptResult.hashtags?.length" class="flex flex-wrap gap-1 mt-2">
                                <template x-for="h in (scriptResult.hashtags || [])" :key="h"><span class="text-[10px] bg-brand-500/10 text-brand-300 rounded px-2 py-0.5" x-text="h"></span></template>
                            </div>
                        </div>
                    </template>
                    <!-- Raw fallback -->
                    <template x-if="scriptResult?.raw_script || scriptResult?.raw_analysis">
                        <p class="text-xs text-white/60 whitespace-pre-line" x-text="scriptResult.raw_script || scriptResult.raw_analysis"></p>
                    </template>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══════════ LIVE PLANNER ═══════════ -->
    <div x-show="activeTab === 'live_planner'" x-cloak class="space-y-4">
        <div class="glass rounded-2xl">
            <div class="p-5 border-b border-white/5">
                <h2 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="radio" class="w-5 h-5 text-red-400"></i> Live Commerce Planner (IA)
                </h2>
                <p class="text-xs text-white/40 mt-1">Planeje lives de vendas com cronograma, scripts e gatilhos de engajamento</p>
            </div>
            <div class="p-5">
                <!-- Form -->
                <div class="grid grid-cols-1 md:grid-cols-3 gap-3 mb-4">
                    <div>
                        <label class="text-[10px] text-white/40 mb-1 block">IDs dos Produtos (separados por virgula)</label>
                        <input type="text" x-model="livePlannerIds" placeholder="1,2,3 ou vazio para auto" class="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:border-brand-500 outline-none">
                    </div>
                    <div>
                        <label class="text-[10px] text-white/40 mb-1 block">Duracao (minutos)</label>
                        <select x-model="livePlannerDuration" class="w-full bg-white/5 border border-white/10 rounded-lg px-3 py-2 text-sm text-white focus:border-brand-500 outline-none">
                            <option value="30">30 min</option>
                            <option value="60" selected>60 min</option>
                            <option value="90">90 min</option>
                            <option value="120">120 min</option>
                        </select>
                    </div>
                    <div class="flex items-end">
                        <button @click="generateLivePlan()" :disabled="livePlannerLoading" class="w-full py-2.5 rounded-lg bg-red-600 hover:bg-red-500 disabled:opacity-50 text-white text-sm font-bold transition flex items-center justify-center gap-2">
                            <template x-if="!livePlannerLoading"><span class="flex items-center gap-1"><i data-lucide="radio" class="w-4 h-4"></i> Planejar Live</span></template>
                            <template x-if="livePlannerLoading"><span class="flex items-center gap-1"><div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div> Planejando...</span></template>
                        </button>
                    </div>
                </div>

                <!-- Live Plan Result -->
                <div x-show="livePlanResult" class="space-y-4">
                    <!-- Title & Products -->
                    <div class="bg-red-500/5 border border-red-500/20 rounded-xl p-4">
                        <h3 class="text-sm font-bold text-red-400" x-text="livePlanResult?.title || 'Plano da Live'"></h3>
                        <p class="text-[10px] text-white/40 mt-1" x-text="livePlanResult?.duration_minutes + ' minutos | ' + (livePlanResult?.products?.length || 0) + ' produtos'"></p>
                        <p class="text-xs text-emerald-400 font-bold mt-1" x-show="livePlanResult?.estimated_revenue" x-text="'Receita estimada: ' + livePlanResult.estimated_revenue"></p>
                    </div>

                    <!-- Setup Checklist -->
                    <div class="bg-white/5 rounded-xl p-4" x-show="livePlanResult?.setup_checklist?.length">
                        <h4 class="text-xs font-bold text-yellow-400 mb-2">Setup Checklist</h4>
                        <template x-for="item in (livePlanResult?.setup_checklist || [])" :key="item">
                            <p class="text-[11px] text-white/60 flex items-center gap-2"><i data-lucide="check-square" class="w-3 h-3 text-yellow-400"></i> <span x-text="item"></span></p>
                        </template>
                    </div>

                    <!-- Schedule Timeline -->
                    <div class="bg-white/5 rounded-xl p-4" x-show="livePlanResult?.schedule?.length">
                        <h4 class="text-xs font-bold text-cyan-400 mb-3">Cronograma</h4>
                        <div class="space-y-2">
                            <template x-for="block in (livePlanResult?.schedule || [])" :key="block.minute">
                                <div class="flex gap-3 items-start bg-white/5 rounded-lg p-3">
                                    <span class="text-[10px] font-bold text-cyan-400 whitespace-nowrap min-w-[40px]" x-text="block.minute + 'min'"></span>
                                    <div class="flex-1">
                                        <p class="text-xs font-bold text-white/80" x-text="block.activity"></p>
                                        <p class="text-[10px] text-white/50 mt-0.5" x-text="block.script"></p>
                                        <span class="text-[9px] text-brand-300" x-show="block.product" x-text="'Produto: ' + block.product"></span>
                                    </div>
                                    <span class="text-[9px] text-white/30" x-text="block.duration + 'min'"></span>
                                </div>
                            </template>
                        </div>
                    </div>

                    <!-- Engagement Triggers -->
                    <div class="bg-white/5 rounded-xl p-4" x-show="livePlanResult?.engagement_triggers?.length">
                        <h4 class="text-xs font-bold text-pink-400 mb-2">Gatilhos de Engajamento</h4>
                        <template x-for="trigger in (livePlanResult?.engagement_triggers || [])" :key="trigger.minute">
                            <div class="flex items-center gap-2 mb-1">
                                <span class="text-[10px] text-pink-400 font-bold" x-text="trigger.minute + 'min'"></span>
                                <span class="text-[11px] text-white/60" x-text="trigger.action"></span>
                            </div>
                        </template>
                    </div>

                    <!-- Tips -->
                    <div class="bg-white/5 rounded-xl p-4" x-show="livePlanResult?.tips?.length">
                        <h4 class="text-xs font-bold text-emerald-400 mb-2">Dicas</h4>
                        <template x-for="tip in (livePlanResult?.tips || [])" :key="tip">
                            <p class="text-[11px] text-white/50 mb-1"><span class="text-emerald-400">*</span> <span x-text="tip"></span></p>
                        </template>
                    </div>

                    <!-- Raw fallback -->
                    <div x-show="livePlanResult?.raw_plan" class="bg-white/5 rounded-xl p-4">
                        <p class="text-xs text-white/60 whitespace-pre-line" x-text="livePlanResult.raw_plan"></p>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>
{% endblock %}

{% block scripts %}
<script>
function shopApp() {
    return {
        activeTab: 'ranking',
        loading: false,
        loadingMsg: '',
        playingVideoId: null,
        cacheStatus: null,
        syncing: false,

        // Missing legacy vars (used in pre-existing tabs)
        selectedProduct: null,
        revenueModal: false,
        productDetails: null,
        revenueData: null,
        loadingRevenue: false,
        monitoredTotal: 0,
        crossKeywords: '',
        crossResults: null,
        autoDetected: null,
        monitoredProducts: [],
        storeUrl: '',
        storeInfo: null,
        storeProducts: [],
        savedProducts: [],
        savedTotal: 0,

        // Product Ranking
        rankProducts: [],
        rankField: 1,
        rankLoading: false,

        //Top Sellers
        topSellers: [],
        sellerRankField: 1,
        sellerLoading: false,

        //Top Creators
        topCreators: [],
        creatorRankField: 1,
        creatorDays: 30,
        creatorLoading: false,

        //Top Videos
        topVideos: [],
        videoRankField: 1,
        videoDays: 30,
        videoRankLoading: false,

        // Daily Trends Chart
        trendsDays: 30,
        trendsData: [],
        trendsChart: null,
        trendsLoading: false,

        //Spy Store
        spySellerSearch: '',
        spySellerDetail: null,
        spySellerProducts: [],
        spySearchResults: [],
        spyLoading: false,

        //Product Detail
        detailSearch: '',
        echoProduct: null,
        echoTrend: [],
        echoProductVideos: [],
        detailSearchResults: [],
        detailLoading: false,
        echoTrendChart: null,

        // Search (legacy)
        searchQuery: '',
        searchDone: false,
        sortBy: 'sold',
        products: [],

        // Viral videos with products
        viralVideos: [],
        viralVideosTotal: 0,
        viralVideosOffset: 0,
        viralFilters: {
            region_filter: 'all',
            min_views: 10000,
            min_viral_score: 0,
            min_duration: 0,
            max_duration: 0,
            description_contains: '',
            category: '',
            style: '',
            sort_by: 'views',
        },
        shopCategories: [
            { id: 'ai_construcao', name: 'IA Construcao', icon: '🤖🏗️' },
            { id: 'construcao', name: 'Construcao', icon: '🏗️' },
            { id: 'arquitetura', name: 'Arquitetura', icon: '🏛️' },
            { id: 'decoracao', name: 'Decoracao', icon: '🎨' },
            { id: 'diy_reforma', name: 'DIY/Reforma', icon: '🔨' },
            { id: 'lifestyle', name: 'Lifestyle', icon: '✨' },
            { id: 'tech', name: 'Tech', icon: '📱' },
            { id: 'moda', name: 'Moda', icon: '👗' },
            { id: 'beleza', name: 'Beleza', icon: '💄' },
            { id: 'fitness', name: 'Fitness', icon: '💪' },
        ],
        shopStyles: [
            { id: 'ai_generated', name: 'Gerado por IA', icon: '🤖' },
            { id: 'timelapse', name: 'Timelapse', icon: '⏩' },
            { id: 'tutorial', name: 'Tutorial', icon: '📋' },
            { id: 'before_after', name: 'Antes/Depois', icon: '🔄' },
            { id: 'review', name: 'Review', icon: '⭐' },
            { id: 'unboxing', name: 'Unboxing', icon: '📦' },
            { id: 'satisfying', name: 'Satisfying', icon: '🤤' },
        ],

        // Reports
        reportsDays: 30,
        reportsData: null,
        reportsLoading: false,
        reportsCharts: {},

        // Analytics
        viralProducts: [],
        shopAlerts: [],
        categoryHeatmap: {},
        analyticsLoading: false,

        // Affiliates
        topCommissions: [],
        affiliateNetwork: [],
        affiliateLoading: false,

        // Commission Calculator
        calcPrice: 49.90,
        calcCategory: 'moda',
        calcDailySales: 10,
        calcCommission: 0,
        calcResult: null,

        // Store Revenue
        storeRevenues: [],
        storeSearch: '',
        storeRevenueLoading: false,

        // Matcher
        matcherResults: [],
        matcherLoading: false,

        // Optimizer
        optimizerResult: null,
        optimizerBudget: 20,
        optimizerLoading: false,

        // Seasonal
        seasonalData: [],
        seasonalLoading: false,

        // Viral Predictor
        viralPredictions: [],
        viralPredictorAI: '',
        viralPredictorLoading: false,

        // Scripts
        scriptProductId: '',
        scriptType: 'video_review',
        scriptAudience: 'geral',
        scriptLoading: false,
        scriptResult: null,

        // Live Planner
        livePlannerIds: '',
        livePlannerDuration: 60,
        livePlannerLoading: false,
        livePlanResult: null,

        quickTags: ['skincare', 'gadgets', 'moda feminina', 'fone bluetooth', 'organizador', 'fitness', 'beleza', 'decoracao', 'acessorios celular', 'legging'],

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

        async checkCacheStatus() {
            try {
                const r = await fetch('/api/echotik/cache/stats');
                if (r.ok) this.cacheStatus = await r.json();
            } catch(e) {}
            this._icons();
        },

        async syncEchotik() {
            this.syncing = true;
            try {
                const r = await fetch('/api/echotik/sync', { method: 'POST' });
                const d = await r.json();
                if (d.synced > 0) {
                    showToast(`${d.synced} keywords sincronizados via Apify!`, 'success');
                    this.checkCacheStatus();
                    this.loadRanking();
                } else {
                    showToast('Nenhum dado retornado. Verifique o APIFY_API_TOKEN.', 'warning');
                }
            } catch(e) { showToast('Erro ao sincronizar', 'error'); }
            this.syncing = false;
            this._icons();
        },

        async searchProducts() {
            if (!this.searchQuery.trim()) return;
            this.loading = true;
            this.loadingMsg = 'Buscando produtos...';
            this.searchDone = false;
            try {
                const r = await fetch(`/api/echotik/product/search?keyword=${encodeURIComponent(this.searchQuery)}&page_size=10`);
                if (!r.ok) { const e = await r.json(); showToast(e.detail || 'Erro', 'error'); this.loading = false; return; }
                const d = await r.json();
                this.products = (d.products || []).map(p => ({
                    ...p,
                    sold_count: p.sales_total || 0,
                    review_count: p.review_count || 0,
                    price: p.price_formatted || p.price,
                    seller_name: p.seller_name || '',
                }));
                this.searchDone = true;
                showToast(`${this.products.length} produtos encontrados`, 'success');
            } catch(e) { showToast('Erro ao buscar produtos', 'error'); }
            this.loading = false;
            this._icons();
        },

        sortProducts(by) {
            this.sortBy = by;
            if (by === 'sold') this.products.sort((a, b) => (b.sold_count || 0) - (a.sold_count || 0));
            else if (by === 'rating') this.products.sort((a, b) => (b.rating || 0) - (a.rating || 0));
        },

        async viewProduct(product) {
            const pid = product.product_id || '';
            if (pid) {
                this.openProductDetail(pid);
            }
        },

        async monitorProduct(product) {
            // First save the product details
            const url = product.url || '';
            if (url) {
                try { await fetch(`/api/shop/product?url=${encodeURIComponent(url)}&get_related_videos=true`); } catch(e) {}
            }
            // Then start monitoring
            const pid = product.product_id || '';
            if (!pid) { showToast('Produto sem ID', 'error'); return; }
            try {
                const r = await fetch(`/api/shop/monitor/${pid}`, { method: 'POST' });
                if (r.ok) {
                    showToast('Produto monitorado! Snapshots de vendas serao coletados.', 'success');
                    this.monitoredTotal++;
                } else {
                    const d = await r.json();
                    showToast(d.detail || 'Erro ao monitorar', 'error');
                }
            } catch(e) { showToast('Erro ao monitorar produto', 'error'); }
        },

        async monitorFromDetails() {
            const pid = this.productDetails?.product_id || this.selectedProduct?.product_id || '';
            if (!pid) return;
            await this.monitorProduct({ product_id: pid, url: this.productDetails?.url || this.selectedProduct?.url || '' });
        },

        async loadCategories() {
            try {
                const r = await fetch('/api/shop/categories');
                const d = await r.json();
                this.categories = d.categories || {};
            } catch(e) {}
            this._icons();
        },

        async loadCategoryProducts(category) {
            this.selectedCategory = category;
            this.loading = true;
            this.loadingMsg = `Buscando produtos de ${this.categories[category]?.name || category}...`;
            try {
                const r = await fetch(`/api/shop/category/${category}?amount=30`);
                const d = await r.json();
                this.categoryProducts = d.products || [];
                showToast(`${this.categoryProducts.length} produtos encontrados em ${d.category_name}`, 'success');
            } catch(e) { showToast('Erro ao buscar categoria', 'error'); }
            this.loading = false;
            this._icons();
        },

        async runCrossPlatform() {
            if (!this.crossKeywords.trim()) return;
            this.loading = true;
            this.loadingMsg = 'Detectando videos com produtos TikTok Shop...';
            try {
                const r = await fetch(`/api/shop/cross-platform?keywords=${encodeURIComponent(this.crossKeywords)}&count=20`);
                this.crossResults = await r.json();
                showToast(`${this.crossResults.videos_with_products} videos com produtos detectados de ${this.crossResults.total_videos} analisados`, 'success');
            } catch(e) { showToast('Erro na deteccao', 'error'); }
            this.loading = false;
            this._icons();
        },

        async autoDetect() {
            this.loading = true;
            this.loadingMsg = 'Auto-detectando produtos virais nas categorias BR... (pode demorar)';
            try {
                const r = await fetch('/api/shop/auto-detect?category=all', { method: 'POST' });
                const d = await r.json();
                this.autoDetected = d.products || [];
                showToast(`${d.detected} produtos virais detectados automaticamente!`, 'success');
            } catch(e) { showToast('Erro na auto-deteccao', 'error'); }
            this.loading = false;
            this._icons();
        },

        async loadMonitored() {
            this.loading = true;
            this.loadingMsg = 'Carregando produtos monitorados...';
            try {
                const r = await fetch('/api/shop/monitored');
                const d = await r.json();
                this.monitoredProducts = d.products || [];
                this.monitoredTotal = d.total || 0;
            } catch(e) { showToast('Erro ao carregar monitorados', 'error'); }
            this.loading = false;
            this._icons();
        },

        async loadViralVideos() {
            this.loading = true;
            this.loadingMsg = 'Carregando videos virais com produtos...';
            this.viralVideosOffset = 0;
            try {
                const vp = new URLSearchParams({
                    limit: 100, offset: 0,
                    region_filter: this.viralFilters.region_filter,
                    min_views: this.viralFilters.min_views,
                    sort_by: this.viralFilters.sort_by,
                });
                if (this.viralFilters.min_viral_score) vp.set('min_viral_score', this.viralFilters.min_viral_score);
                if (this.viralFilters.min_duration) vp.set('min_duration', this.viralFilters.min_duration);
                if (this.viralFilters.max_duration) vp.set('max_duration', this.viralFilters.max_duration);
                if (this.viralFilters.description_contains) vp.set('description_contains', this.viralFilters.description_contains);
                if (this.viralFilters.category) vp.set('category', this.viralFilters.category);
                if (this.viralFilters.style) vp.set('style', this.viralFilters.style);
                const r = await fetch(`/api/shop/viral-videos?${vp}`);
                const d = await r.json();
                this.viralVideos = d.videos || [];
                this.viralVideosTotal = d.total || 0;
            } catch(e) { showToast('Erro ao carregar videos', 'error'); }
            this.loading = false;
            this._icons();
        },

        async loadMoreViralVideos() {
            this.viralVideosOffset += 100;
            try {
                const vp2 = new URLSearchParams({
                    limit: 100, offset: this.viralVideosOffset,
                    region_filter: this.viralFilters.region_filter,
                    min_views: this.viralFilters.min_views,
                    sort_by: this.viralFilters.sort_by,
                });
                if (this.viralFilters.min_viral_score) vp2.set('min_viral_score', this.viralFilters.min_viral_score);
                if (this.viralFilters.min_duration) vp2.set('min_duration', this.viralFilters.min_duration);
                if (this.viralFilters.max_duration) vp2.set('max_duration', this.viralFilters.max_duration);
                if (this.viralFilters.description_contains) vp2.set('description_contains', this.viralFilters.description_contains);
                if (this.viralFilters.category) vp2.set('category', this.viralFilters.category);
                if (this.viralFilters.style) vp2.set('style', this.viralFilters.style);
                const r = await fetch(`/api/shop/viral-videos?${vp2}`);
                const d = await r.json();
                this.viralVideos = [...this.viralVideos, ...(d.videos || [])];
            } catch(e) { showToast('Erro', 'error'); }
            this._icons();
        },

        async autoLinkProducts() {
            this.loading = true;
            this.loadingMsg = 'Importando produtos dos videos para a Shop...';
            try {
                const r = await fetch('/api/shop/auto-link', { method: 'POST' });
                const d = await r.json();
                if (d.new_products_saved > 0) {
                    showToast(`${d.new_products_saved} novos produtos importados!`, 'success');
                } else {
                    showToast(`Nenhum produto novo encontrado. ${d.videos_with_products} videos ja processados.`, 'info');
                }
                if (d.errors && d.errors.length > 0) {
                    showToast(`${d.errors.length} erros encontrados`, 'warning');
                }
            } catch(e) { showToast('Erro ao importar produtos', 'error'); }
            this.loading = false;
        },

        async takeSnapshot(productId) {
            try {
                const r = await fetch(`/api/shop/snapshot/${productId}`, { method: 'POST' });
                if (r.ok) {
                    showToast('Snapshot coletado!', 'success');
                    this.loadMonitored();
                } else {
                    showToast('Erro ao coletar snapshot', 'error');
                }
            } catch(e) { showToast('Erro', 'error'); }
        },

        async snapshotAll() {
            this.loading = true;
            this.loadingMsg = 'Atualizando dados de todos os produtos...';
            try {
                const r = await fetch('/api/shop/snapshot-all', { method: 'POST' });
                const d = await r.json();
                showToast(`${d.snapshots_taken} snapshots coletados!`, 'success');
                this.loadMonitored();
            } catch(e) { showToast('Erro', 'error'); }
            this.loading = false;
        },

        async viewRevenue(productId) {
            this.revenueModal = true;
            this.revenueData = null;
            this.loadingRevenue = true;
            this._icons();
            try {
                const r = await fetch(`/api/shop/revenue/${productId}?days=30`);
                this.revenueData = await r.json();
                this.$nextTick(() => this.drawRevenueChart());
            } catch(e) { showToast('Erro ao carregar revenue', 'error'); }
            this.loadingRevenue = false;
            this._icons();
        },

        drawRevenueChart() {
            if (!this.revenueData?.daily_sales?.length) return;
            const ctx = document.getElementById('revenueChart');
            if (!ctx) return;
            if (this.revenueChart) this.revenueChart.destroy();

            const sales = this.revenueData.daily_sales;
            this.revenueChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: sales.map(s => s.date),
                    datasets: [
                        {
                            label: 'Vendas',
                            data: sales.map(s => s.sold),
                            backgroundColor: 'rgba(16, 185, 129, 0.6)',
                            borderColor: 'rgba(16, 185, 129, 1)',
                            borderWidth: 1,
                            borderRadius: 4,
                            yAxisID: 'y',
                        },
                        {
                            label: 'Estoque',
                            data: sales.map(s => s.stock),
                            type: 'line',
                            borderColor: 'rgba(139, 92, 246, 0.8)',
                            backgroundColor: 'rgba(139, 92, 246, 0.1)',
                            fill: true,
                            tension: 0.4,
                            pointRadius: 3,
                            yAxisID: 'y1',
                        }
                    ]
                },
                options: {
                    responsive: true,
                    interaction: { intersect: false, mode: 'index' },
                    plugins: {
                        legend: { labels: { color: 'rgba(255,255,255,0.6)', font: { size: 11 } } }
                    },
                    scales: {
                        x: { ticks: { color: 'rgba(255,255,255,0.4)', font: { size: 10 } }, grid: { color: 'rgba(255,255,255,0.05)' } },
                        y: { position: 'left', title: { display: true, text: 'Vendas', color: 'rgba(16,185,129,0.8)' }, ticks: { color: 'rgba(255,255,255,0.4)' }, grid: { color: 'rgba(255,255,255,0.05)' } },
                        y1: { position: 'right', title: { display: true, text: 'Estoque', color: 'rgba(139,92,246,0.8)' }, ticks: { color: 'rgba(255,255,255,0.4)' }, grid: { display: false } },
                    }
                }
            });
        },

        async loadSaved(sortBy = 'sold_count') {
            this.loading = true;
            try {
                const r = await fetch(`/api/shop/products?limit=100&sort_by=${sortBy}`);
                const d = await r.json();
                this.savedProducts = d.products || [];
                this.savedTotal = d.total || 0;
            } catch(e) { showToast('Erro ao carregar produtos salvos', 'error'); }
            this.loading = false;
            this._icons();
        },

        async analyzeStore() {
            if (!this.storeUrl.trim()) return;
            this.loading = true;
            this.loadingMsg = 'Analisando loja...';
            this.storeInfo = {};
            this.storeProducts = [];
            try {
                const r = await fetch(`/api/shop/store?url=${encodeURIComponent(this.storeUrl)}`);
                const d = await r.json();
                this.storeInfo = d.shop_info || {};
                this.storeProducts = d.products || [];
                showToast(`${this.storeProducts.length} produtos da loja carregados`, 'success');
            } catch(e) { showToast('Erro ao analisar loja', 'error'); }
            this.loading = false;
            this._icons();
        },

        // ── EchoTik: Product Ranking ──
        async loadRanking() {
            this.rankLoading = true;
            try {
                const r = await fetch(`/api/echotik/product/ranking?rank_field=${this.rankField}&page_size=10`);
                if (!r.ok) { const e = await r.json(); showToast(e.detail || 'Erro', 'error'); this.rankLoading = false; return; }
                const d = await r.json();
                this.rankProducts = d.products || [];
            } catch(e) { showToast('Erro ao carregar ranking', 'error'); }
            this.rankLoading = false;
            this._icons();
        },

        // ── EchoTik: Top Sellers ──
        async loadTopSellers() {
            this.sellerLoading = true;
            try {
                const r = await fetch(`/api/echotik/seller/ranking?rank_field=${this.sellerRankField}&page_size=10`);
                if (!r.ok) { const e = await r.json(); showToast(e.detail || 'Erro', 'error'); this.sellerLoading = false; return; }
                const d = await r.json();
                this.topSellers = d.sellers || [];
            } catch(e) { showToast('Erro ao carregar lojas', 'error'); }
            this.sellerLoading = false;
            this._icons();
        },

        // ── Top Creators BR (dados locais) ──
        async loadTopCreators() {
            this.creatorLoading = true;
            try {
                const r = await fetch(`/api/echotik/influencer/ranking?rank_field=${this.creatorRankField}&page_size=20&days=${this.creatorDays}`);
                if (!r.ok) { const e = await r.json(); showToast(e.detail || 'Erro', 'error'); this.creatorLoading = false; return; }
                const d = await r.json();
                this.topCreators = d.influencers || [];
            } catch(e) { showToast('Erro ao carregar creators', 'error'); }
            this.creatorLoading = false;
            this._icons();
        },

        // ── Top Videos BR (dados locais) ──
        async loadTopVideos() {
            this.videoRankLoading = true;
            try {
                const r = await fetch(`/api/echotik/video/ranking?rank_field=${this.videoRankField}&page_size=20&days=${this.videoDays}`);
                if (!r.ok) { const e = await r.json(); showToast(e.detail || 'Erro', 'error'); this.videoRankLoading = false; return; }
                const d = await r.json();
                this.topVideos = d.videos || [];
            } catch(e) { showToast('Erro ao carregar videos', 'error'); }
            this.videoRankLoading = false;
            this._icons();
        },

        // ── Reports ──
        async loadReports() {
            this.reportsLoading = true;
            try {
                const r = await fetch(`/api/shop/reports?days=${this.reportsDays}`);
                if (!r.ok) { showToast('Erro ao carregar relatorios', 'error'); this.reportsLoading = false; return; }
                this.reportsData = await r.json();
                this.$nextTick(() => this.drawReportCharts());
            } catch(e) { showToast('Erro ao carregar relatorios', 'error'); }
            this.reportsLoading = false;
            this._icons();
        },

        drawReportCharts() {
            if (!this.reportsData) return;
            const nichos = this.reportsData.nicho_performance || [];
            const growth = this.reportsData.growth_insights || [];

            // Nicho chart
            const nichoCtx = document.getElementById('reportNichoChart');
            if (nichoCtx && nichos.length > 0) {
                if (this.reportsCharts.nicho) this.reportsCharts.nicho.destroy();
                this.reportsCharts.nicho = new Chart(nichoCtx.getContext('2d'), {
                    type: 'bar',
                    data: {
                        labels: nichos.map(n => n.category_name),
                        datasets: [
                            { label: 'Total Videos', data: nichos.map(n => n.video_count), backgroundColor: 'rgba(124, 58, 237, 0.7)', borderRadius: 6 },
                            { label: 'Com Produto', data: nichos.map(n => n.shop_count), backgroundColor: 'rgba(16, 185, 129, 0.7)', borderRadius: 6 },
                        ]
                    },
                    options: {
                        indexAxis: 'y',
                        responsive: true, maintainAspectRatio: false,
                        plugins: { legend: { labels: { color: 'rgba(255,255,255,0.6)', font: { size: 10 } } } },
                        scales: {
                            x: { grid: { color: 'rgba(255,255,255,0.05)' }, ticks: { color: 'rgba(255,255,255,0.4)', font: { size: 10 } } },
                            y: { grid: { display: false }, ticks: { color: 'rgba(255,255,255,0.6)', font: { size: 11 } } },
                        }
                    }
                });
            }

            // Growth chart
            const growthCtx = document.getElementById('reportGrowthChart');
            if (growthCtx && growth.length > 0) {
                if (this.reportsCharts.growth) this.reportsCharts.growth.destroy();
                const top10 = growth.slice(0, 10);
                this.reportsCharts.growth = new Chart(growthCtx.getContext('2d'), {
                    type: 'bar',
                    data: {
                        labels: top10.map(g => '@' + g.username),
                        datasets: [{
                            label: 'Views/dia',
                            data: top10.map(g => g.velocity),
                            backgroundColor: top10.map((g, i) => i < 3 ? 'rgba(251, 146, 60, 0.8)' : 'rgba(124, 58, 237, 0.6)'),
                            borderRadius: 6,
                        }]
                    },
                    options: {
                        indexAxis: 'y',
                        responsive: true, maintainAspectRatio: false,
                        plugins: { legend: { display: false } },
                        scales: {
                            x: { grid: { color: 'rgba(255,255,255,0.05)' }, ticks: { color: 'rgba(255,255,255,0.4)', font: { size: 10 }, callback: v => v >= 1000000 ? (v/1000000).toFixed(1)+'M' : v >= 1000 ? (v/1000).toFixed(0)+'K' : v } },
                            y: { grid: { display: false }, ticks: { color: 'rgba(255,255,255,0.6)', font: { size: 10 } } },
                        }
                    }
                });
            }
        },

        // ── EchoTik: Spy Store ──
        async searchSeller() {
            if (!this.spySellerSearch.trim()) return;
            this.spyLoading = true;
            this.spySellerDetail = null;
            this.spySellerProducts = [];
            this.spySearchResults = [];
            try {
                const r = await fetch(`/api/echotik/seller/search?keyword=${encodeURIComponent(this.spySellerSearch)}&page_size=10`);
                if (!r.ok) { const e = await r.json(); showToast(e.detail || 'Erro', 'error'); this.spyLoading = false; return; }
                const d = await r.json();
                this.spySearchResults = d.sellers || [];
                if (this.spySearchResults.length === 1) {
                    this.openSellerDetail(this.spySearchResults[0].seller_id);
                } else if (this.spySearchResults.length === 0) {
                    showToast('Nenhuma loja encontrada', 'warning');
                }
            } catch(e) { showToast('Erro ao buscar loja', 'error'); }
            this.spyLoading = false;
            this._icons();
        },

        async openSellerDetail(sellerId) {
            this.activeTab = 'spy_store';
            this.spyLoading = true;
            this.spySellerDetail = null;
            this.spySellerProducts = [];
            try {
                const [detR, prodR] = await Promise.all([
                    fetch(`/api/echotik/seller/detail?seller_id=${sellerId}`),
                    fetch(`/api/echotik/seller/products?seller_id=${sellerId}&page_size=10`),
                ]);
                if (detR.ok) this.spySellerDetail = await detR.json();
                if (prodR.ok) { const d = await prodR.json(); this.spySellerProducts = d.products || []; }
                showToast(`Loja "${this.spySellerDetail?.name}" carregada`, 'success');
            } catch(e) { showToast('Erro ao carregar loja', 'error'); }
            this.spyLoading = false;
            this._icons();
        },

        // ── EchoTik: Product Detail ──
        async searchProductDetail() {
            if (!this.detailSearch.trim()) return;
            this.detailLoading = true;
            this.echoProduct = null;
            this.echoTrend = [];
            this.echoProductVideos = [];
            this.detailSearchResults = [];
            // Check if it's a product ID (numeric)
            if (/^\d{10,}$/.test(this.detailSearch.trim())) {
                await this.openProductDetail(this.detailSearch.trim());
                return;
            }
            try {
                const r = await fetch(`/api/echotik/product/search?keyword=${encodeURIComponent(this.detailSearch)}&page_size=10`);
                if (!r.ok) { const e = await r.json(); showToast(e.detail || 'Erro', 'error'); this.detailLoading = false; return; }
                const d = await r.json();
                this.detailSearchResults = d.products || [];
                if (this.detailSearchResults.length === 1) {
                    await this.openProductDetail(this.detailSearchResults[0].product_id);
                } else if (this.detailSearchResults.length === 0) {
                    showToast('Nenhum produto encontrado', 'warning');
                }
            } catch(e) { showToast('Erro ao buscar produto', 'error'); }
            this.detailLoading = false;
            this._icons();
        },

        async openProductDetail(productId) {
            this.activeTab = 'product_detail';
            this.detailLoading = true;
            this.echoProduct = null;
            this.echoTrend = [];
            this.echoProductVideos = [];
            try {
                // Load detail, trend, and videos in parallel
                const [detR, trendR, vidR] = await Promise.all([
                    fetch(`/api/echotik/product/detail?product_id=${productId}`),
                    fetch(`/api/echotik/product/trend?product_id=${productId}&days=30`),
                    fetch(`/api/echotik/product/videos?product_id=${productId}&page_size=10`),
                ]);
                if (detR.ok) this.echoProduct = await detR.json();
                if (trendR.ok) { const d = await trendR.json(); this.echoTrend = d.trend || []; }
                if (vidR.ok) { const d = await vidR.json(); this.echoProductVideos = d.videos || []; }

                // Auto-take snapshot for trend tracking (non-blocking)
                fetch(`/api/echotik/product/snapshot?product_id=${productId}`, { method: 'POST' }).catch(() => {});

                if (this.echoTrend.length > 0) {
                    this.$nextTick(() => this.drawEchoTrendChart());
                }
            } catch(e) { showToast('Erro ao carregar produto', 'error'); }
            this.detailLoading = false;
            this._icons();
        },

        // ── Tendencias BR (graficos) ──
        async loadTrendsChart() {
            this.trendsLoading = true;
            try {
                const r = await fetch(`/api/echotik/trends/daily?days=${this.trendsDays}`);
                if (!r.ok) { showToast('Erro ao carregar tendencias', 'error'); this.trendsLoading = false; return; }
                const d = await r.json();
                this.trendsData = d.trends || [];
                if (this.trendsData.length > 0) {
                    this.$nextTick(() => this.drawTrendsCharts());
                }
            } catch(e) { showToast('Erro ao carregar tendencias', 'error'); }
            this.trendsLoading = false;
            this._icons();
        },

        drawTrendsCharts() {
            if (!this.trendsData.length) return;
            const t = this.trendsData;
            const labels = t.map(d => d.date.slice(5)); // MM-DD

            // Main chart: Videos + Views
            const ctx1 = document.getElementById('trendsMainChart');
            if (ctx1) {
                if (this.trendsChart) this.trendsChart.destroy();
                this.trendsChart = new Chart(ctx1, {
                    type: 'bar',
                    data: {
                        labels,
                        datasets: [
                            {
                                label: 'Videos/dia',
                                data: t.map(d => d.video_count),
                                backgroundColor: 'rgba(139, 92, 246, 0.6)',
                                borderColor: 'rgba(139, 92, 246, 1)',
                                borderWidth: 1, borderRadius: 4, yAxisID: 'y',
                            },
                            {
                                label: 'Views/dia',
                                data: t.map(d => d.total_views),
                                type: 'line',
                                borderColor: 'rgba(6, 182, 212, 0.8)',
                                backgroundColor: 'rgba(6, 182, 212, 0.1)',
                                fill: true, tension: 0.4, pointRadius: 2, yAxisID: 'y1',
                            },
                            {
                                label: 'Com Produto',
                                data: t.map(d => d.shop_video_count),
                                backgroundColor: 'rgba(16, 185, 129, 0.5)',
                                borderColor: 'rgba(16, 185, 129, 1)',
                                borderWidth: 1, borderRadius: 4, yAxisID: 'y',
                            },
                        ]
                    },
                    options: {
                        responsive: true,
                        interaction: { intersect: false, mode: 'index' },
                        plugins: { legend: { labels: { color: 'rgba(255,255,255,0.6)', font: { size: 11 } } } },
                        scales: {
                            x: { ticks: { color: 'rgba(255,255,255,0.4)', font: { size: 10 }, maxRotation: 45 }, grid: { color: 'rgba(255,255,255,0.05)' } },
                            y: { position: 'left', title: { display: true, text: 'Videos', color: 'rgba(139,92,246,0.8)' }, ticks: { color: 'rgba(255,255,255,0.4)' }, grid: { color: 'rgba(255,255,255,0.05)' } },
                            y1: { position: 'right', title: { display: true, text: 'Views', color: 'rgba(6,182,212,0.8)' }, ticks: { color: 'rgba(255,255,255,0.4)', callback: v => v >= 1e6 ? (v/1e6).toFixed(1)+'M' : v >= 1e3 ? (v/1e3).toFixed(0)+'K' : v }, grid: { display: false } },
                        }
                    }
                });
            }

            // Viral chart
            const ctx2 = document.getElementById('trendsViralChart');
            if (ctx2) {
                if (this._viralChart) this._viralChart.destroy();
                this._viralChart = new Chart(ctx2, {
                    type: 'line',
                    data: {
                        labels,
                        datasets: [
                            {
                                label: 'Viral Score Medio',
                                data: t.map(d => d.avg_viral_score),
                                borderColor: 'rgba(249, 115, 22, 0.9)',
                                backgroundColor: 'rgba(249, 115, 22, 0.1)',
                                fill: true, tension: 0.4, pointRadius: 3, yAxisID: 'y',
                            },
                            {
                                label: 'Engajamento Medio %',
                                data: t.map(d => d.avg_engagement),
                                borderColor: 'rgba(236, 72, 153, 0.9)',
                                backgroundColor: 'rgba(236, 72, 153, 0.1)',
                                fill: true, tension: 0.4, pointRadius: 3, yAxisID: 'y1',
                            },
                        ]
                    },
                    options: {
                        responsive: true,
                        interaction: { intersect: false, mode: 'index' },
                        plugins: { legend: { labels: { color: 'rgba(255,255,255,0.6)', font: { size: 11 } } } },
                        scales: {
                            x: { ticks: { color: 'rgba(255,255,255,0.4)', font: { size: 10 }, maxRotation: 45 }, grid: { color: 'rgba(255,255,255,0.05)' } },
                            y: { position: 'left', title: { display: true, text: 'Viral Score', color: 'rgba(249,115,22,0.8)' }, ticks: { color: 'rgba(255,255,255,0.4)' }, grid: { color: 'rgba(255,255,255,0.05)' } },
                            y1: { position: 'right', title: { display: true, text: 'Engajamento %', color: 'rgba(236,72,153,0.8)' }, ticks: { color: 'rgba(255,255,255,0.4)' }, grid: { display: false } },
                        }
                    }
                });
            }
        },

        drawEchoTrendChart() {
            if (!this.echoTrend.length) return;
            const ctx = document.getElementById('echoTrendChart');
            if (!ctx) return;
            if (this.echoTrendChart) this.echoTrendChart.destroy();
            const trend = this.echoTrend;

            // Calculate daily deltas from cumulative data (snapshots)
            const dailySales = trend.map((t, i) => {
                if (t.sales_daily > 0) return t.sales_daily; // Already has daily data
                if (i === 0) return 0;
                return Math.max(0, (t.sales_total || 0) - (trend[i-1].sales_total || 0));
            });
            const dailyGmv = trend.map((t, i) => {
                if (t.gmv_daily > 0) return t.gmv_daily;
                if (i === 0) return 0;
                return Math.max(0, (t.gmv_total || 0) - (trend[i-1].gmv_total || 0));
            });

            // If all daily values are 0, show cumulative totals instead
            const hasDailyData = dailySales.some(v => v > 0);

            this.echoTrendChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: trend.map(t => t.date),
                    datasets: [
                        {
                            label: hasDailyData ? 'Vendas Diarias' : 'Vendas Acumuladas',
                            data: hasDailyData ? dailySales : trend.map(t => t.sales_total),
                            backgroundColor: 'rgba(16, 185, 129, 0.6)',
                            borderColor: 'rgba(16, 185, 129, 1)',
                            borderWidth: 1, borderRadius: 4, yAxisID: 'y',
                        },
                        {
                            label: 'Estoque',
                            data: trend.map(t => t.stock || 0),
                            type: 'line',
                            borderColor: 'rgba(139, 92, 246, 0.8)',
                            backgroundColor: 'rgba(139, 92, 246, 0.1)',
                            fill: true, tension: 0.4, pointRadius: 3, yAxisID: 'y1',
                        }
                    ]
                },
                options: {
                    responsive: true,
                    interaction: { intersect: false, mode: 'index' },
                    plugins: { legend: { labels: { color: 'rgba(255,255,255,0.6)', font: { size: 11 } } } },
                    scales: {
                        x: { ticks: { color: 'rgba(255,255,255,0.4)', font: { size: 10 } }, grid: { color: 'rgba(255,255,255,0.05)' } },
                        y: { position: 'left', title: { display: true, text: hasDailyData ? 'Vendas/dia' : 'Vendas total', color: 'rgba(16,185,129,0.8)' }, ticks: { color: 'rgba(255,255,255,0.4)' }, grid: { color: 'rgba(255,255,255,0.05)' } },
                        y1: { position: 'right', title: { display: true, text: 'Estoque', color: 'rgba(139,92,246,0.8)' }, ticks: { color: 'rgba(255,255,255,0.4)' }, grid: { display: false } },
                    }
                }
            });
        },

        // ── Analytics IA ──
        async loadAnalytics() {
            this.analyticsLoading = true;
            const [viralRes, alertsRes, heatmapRes] = await Promise.allSettled([
                fetch('/api/shop-analytics/viral-products?days=7&limit=20').then(r => r.json()),
                fetch('/api/shop-analytics/alerts?hours=48').then(r => r.json()),
                fetch('/api/shop-analytics/category-heatmap?days=7').then(r => r.json()),
            ]);
            if (viralRes.status === 'fulfilled') this.viralProducts = viralRes.value.products || [];
            if (alertsRes.status === 'fulfilled') this.shopAlerts = alertsRes.value.alerts || [];
            if (heatmapRes.status === 'fulfilled') this.categoryHeatmap = heatmapRes.value || {};
            this.analyticsLoading = false;
            this._icons();
        },

        // ── Affiliates ──
        async loadAffiliates() {
            this.affiliateLoading = true;
            const [commRes, netRes] = await Promise.allSettled([
                fetch('/api/shop-analytics/top-commissions?days=7&limit=20').then(r => r.json()),
                fetch('/api/shop-analytics/affiliate-network?days=30&limit=30').then(r => r.json()),
            ]);
            if (commRes.status === 'fulfilled') this.topCommissions = commRes.value.products || [];
            if (netRes.status === 'fulfilled') this.affiliateNetwork = netRes.value.creators || [];
            this.affiliateLoading = false;
            this._icons();
        },

        // ── Commission Calculator ──
        async calculateCommission() {
            if (this.calcPrice <= 0) return;
            try {
                const params = new URLSearchParams({
                    price: this.calcPrice,
                    category: this.calcCategory,
                    daily_sales: this.calcDailySales,
                    commission_pct: this.calcCommission || 0,
                });
                const r = await fetch('/api/shop-analytics/commission?' + params, { method: 'POST' });
                this.calcResult = await r.json();
            } catch(e) { showToast('Erro ao calcular', 'error'); }
        },

        // ── Store Revenue ──
        async loadStoreRevenue() {
            this.storeRevenueLoading = true;
            try {
                const params = this.storeSearch ? `?shop_name=${encodeURIComponent(this.storeSearch)}` : '';
                const r = await fetch('/api/shop-analytics/store-revenue' + params);
                const d = await r.json();
                this.storeRevenues = d.stores || [];
            } catch(e) { showToast('Erro ao carregar receitas', 'error'); }
            this.storeRevenueLoading = false;
            this._icons();
        },

        // ── Matcher ──
        async loadMatcher() {
            this.matcherLoading = true;
            try {
                const r = await fetch('/api/shop-analytics/match-affiliates?days=14&limit=30');
                const d = await r.json();
                this.matcherResults = d.matches || [];
            } catch(e) { showToast('Erro ao carregar matches', 'error'); }
            this.matcherLoading = false;
            this._icons();
        },

        // ── Optimizer ──
        async loadOptimizer() {
            this.optimizerLoading = true;
            try {
                const r = await fetch(`/api/shop-analytics/optimize-commission?budget_hours=${this.optimizerBudget}`);
                this.optimizerResult = await r.json();
            } catch(e) { showToast('Erro ao otimizar', 'error'); }
            this.optimizerLoading = false;
            this._icons();
        },

        // ── Seasonal ──
        async loadSeasonal() {
            this.seasonalLoading = true;
            try {
                const r = await fetch('/api/shop-analytics/seasonal?months_ahead=3');
                const d = await r.json();
                this.seasonalData = d.predictions || [];
            } catch(e) { showToast('Erro ao carregar sazonais', 'error'); }
            this.seasonalLoading = false;
            this._icons();
        },

        // ── Viral Predictor ──
        async loadViralPredictor() {
            this.viralPredictorLoading = true;
            try {
                const r = await fetch('/api/shop-analytics/predict-viral?days=14&limit=10');
                const d = await r.json();
                this.viralPredictions = d.predictions || [];
                this.viralPredictorAI = d.ai_commentary || '';
            } catch(e) { showToast('Erro ao carregar predicoes', 'error'); }
            this.viralPredictorLoading = false;
            this._icons();
        },

        // ── Scripts ──
        async generateScript() {
            this.scriptLoading = true;
            this.scriptResult = null;
            try {
                let url, body;
                if (this.scriptType === 'sales') {
                    body = new URLSearchParams({ product_id: this.scriptProductId, audience: this.scriptAudience, tone: 'conversacional' });
                    const r = await fetch('/api/shop-analytics/sales-script', { method: 'POST', body });
                    this.scriptResult = await r.json();
                } else {
                    const style = this.scriptType.replace('video_', '');
                    body = new URLSearchParams({ product_id: this.scriptProductId, style });
                    const r = await fetch('/api/shop-analytics/video-template', { method: 'POST', body });
                    this.scriptResult = await r.json();
                }
                if (this.scriptResult?.success) showToast('Script gerado com sucesso!', 'success');
                else showToast('Erro: ' + (this.scriptResult?.error || 'Falha'), 'error');
            } catch(e) { showToast('Erro ao gerar script', 'error'); }
            this.scriptLoading = false;
            this._icons();
        },

        // ── Live Planner ──
        async generateLivePlan() {
            this.livePlannerLoading = true;
            this.livePlanResult = null;
            try {
                const body = new URLSearchParams({ product_ids: this.livePlannerIds, duration_minutes: this.livePlannerDuration });
                const r = await fetch('/api/shop-analytics/live-planner', { method: 'POST', body });
                this.livePlanResult = await r.json();
                if (this.livePlanResult?.success) showToast('Plano da live gerado!', 'success');
                else showToast('Erro: ' + (this.livePlanResult?.error || 'Falha'), 'error');
            } catch(e) { showToast('Erro ao planejar live', 'error'); }
            this.livePlannerLoading = false;
            this._icons();
        },

        fmtNum(n) {
            if (!n) return '0';
            if (n >= 1000000) return (n/1000000).toFixed(1) + 'M';
            if (n >= 1000) return (n/1000).toFixed(1) + 'K';
            return n.toString();
        },

        _icons() {
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },
    }
}
</script>
{% endblock %}
