{% extends "base.html" %}
{% block title %}Shop Dashboard PRO - Viral Social Pro{% endblock %}
{% block nav_shop_dashboard %}active{% endblock %}
{% block page_title %}TikTok Shop Dashboard PRO{% endblock %}
{% block page_subtitle %}Analytics profissional para suas contas TikTok Shop{% endblock %}

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

    <!-- ADD ACCOUNT -->
    <div class="animate-fade-up mb-6">
        <div class="glass-card rounded-2xl p-5">
            <div class="flex flex-col gap-4">
                <div class="flex flex-col md:flex-row md:items-end gap-4">
                    <div class="flex-1">
                        <h3 class="text-lg font-bold text-white/90 mb-1 flex items-center gap-2">
                            <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center flex-shrink-0">
                                <i data-lucide="store" class="w-5 h-5"></i>
                            </div>
                            Adicionar Conta
                        </h3>
                        <p class="text-xs text-white/40 ml-12">Cole o @ ou link de uma conta TikTok Shop</p>
                    </div>
                    <form @submit.prevent="addAccount()" class="flex flex-col sm:flex-row gap-3 w-full md:w-auto">
                        <div class="relative flex-1 min-w-[250px]">
                            <i data-lucide="at-sign" class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/30"></i>
                            <input type="text" x-model="newUsername" placeholder="@usuario ou link TikTok" required
                                   class="w-full bg-dark-700 border border-white/10 rounded-xl pl-9 pr-4 py-2.5 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none transition"
                                   @keydown.enter.prevent="addAccount()">
                        </div>
                        <button type="submit" :disabled="adding || !newUsername.trim()"
                                class="flex items-center justify-center gap-2 px-6 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-40 disabled:cursor-not-allowed whitespace-nowrap">
                            <template x-if="adding">
                                <svg class="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                            </template>
                            <template x-if="!adding">
                                <i data-lucide="plus" class="w-4 h-4"></i>
                            </template>
                            <span x-text="adding ? 'Adicionando...' : 'Adicionar'"></span>
                        </button>
                    </form>
                </div>
                <!-- Bulk Add -->
                <div>
                    <button @click="showBulk = !showBulk" class="text-xs text-brand-300 hover:text-brand-200 transition flex items-center gap-1">
                        <i data-lucide="list-plus" class="w-3.5 h-3.5"></i>
                        <span x-text="showBulk ? 'Fechar importacao em massa' : 'Importar em massa'"></span>
                    </button>
                    <div x-show="showBulk" x-transition class="mt-3">
                        <textarea x-model="bulkText" rows="3" placeholder="Cole varios @ separados por virgula ou quebra de linha...&#10;@conta1, @conta2, @conta3"
                                  class="w-full bg-dark-700 border border-white/10 rounded-xl px-4 py-3 text-sm text-white/80 placeholder:text-white/25 focus:border-brand-400 focus:outline-none transition resize-y"></textarea>
                        <button @click="addBulk()" :disabled="addingBulk || !bulkText.trim()"
                                class="mt-2 flex items-center justify-center gap-2 px-5 py-2 rounded-xl bg-brand-600 text-white font-semibold text-sm hover:bg-brand-500 transition disabled:opacity-40">
                            <template x-if="addingBulk">
                                <svg class="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                            </template>
                            <span x-text="addingBulk ? 'Importando...' : 'Importar Todos'"></span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- SUMMARY CARDS: 8 cards in 2 rows -->
    <div x-show="accounts.length > 0" x-transition class="animate-fade-up-delay mb-6">
        <div class="grid grid-cols-2 md:grid-cols-4 gap-3 mb-3">
            <div class="glass-card rounded-xl p-4 text-center">
                <div class="flex items-center justify-center gap-2 mb-1"><i data-lucide="store" class="w-4 h-4 text-brand-300"></i></div>
                <p class="stat-number text-brand-300" x-text="summary.total_accounts || 0"></p>
                <p class="text-xs text-white/40 mt-1">Contas</p>
            </div>
            <div class="glass-card rounded-xl p-4 text-center">
                <div class="flex items-center justify-center gap-2 mb-1"><i data-lucide="shopping-cart" class="w-4 h-4 text-green-400"></i></div>
                <p class="stat-number text-green-400" x-text="fmtNum(summary.total_sold || 0)"></p>
                <p class="text-xs text-white/40 mt-1">Total Vendas</p>
            </div>
            <div class="glass-card rounded-xl p-4 text-center">
                <div class="flex items-center justify-center gap-2 mb-1"><i data-lucide="dollar-sign" class="w-4 h-4 text-yellow-400"></i></div>
                <p class="stat-number text-yellow-400" x-text="'$' + fmtNum(summary.total_revenue || 0)"></p>
                <p class="text-xs text-white/40 mt-1">Receita Estimada</p>
            </div>
            <div class="glass-card rounded-xl p-4 text-center">
                <div class="flex items-center justify-center gap-2 mb-1"><i data-lucide="eye" class="w-4 h-4 text-blue-400"></i></div>
                <p class="stat-number text-blue-400" x-text="fmtNum(summary.total_views || 0)"></p>
                <p class="text-xs text-white/40 mt-1">Total Views</p>
            </div>
        </div>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
            <div class="glass-card rounded-xl p-4 text-center">
                <div class="flex items-center justify-center gap-2 mb-1"><i data-lucide="flame" class="w-4 h-4 text-orange-400"></i></div>
                <p class="stat-number text-orange-400" x-text="(summary.avg_engagement || 0).toFixed(1) + '%'"></p>
                <p class="text-xs text-white/40 mt-1">Avg Engagement</p>
            </div>
            <div class="glass-card rounded-xl p-4 text-center">
                <div class="flex items-center justify-center gap-2 mb-1"><i data-lucide="package" class="w-4 h-4 text-pink-400"></i></div>
                <p class="stat-number text-pink-400" x-text="fmtNum(summary.total_products || 0)"></p>
                <p class="text-xs text-white/40 mt-1">Total Produtos</p>
            </div>
            <div class="glass-card rounded-xl p-4 text-center">
                <div class="flex items-center justify-center gap-2 mb-1"><i data-lucide="wallet" class="w-4 h-4 text-emerald-400"></i></div>
                <p class="stat-number text-emerald-400" x-text="'$' + fmtNum(summary.avg_revenue_per_account || 0)"></p>
                <p class="text-xs text-white/40 mt-1">Receita/Conta</p>
            </div>
            <div class="glass-card rounded-xl p-4 text-center">
                <div class="flex items-center justify-center gap-2 mb-1"><i data-lucide="shopping-bag" class="w-4 h-4 text-cyan-400"></i></div>
                <p class="stat-number text-cyan-400" x-text="(summary.avg_commerce_ratio || 0).toFixed(1) + '%'"></p>
                <p class="text-xs text-white/40 mt-1">Commerce Ratio</p>
            </div>
        </div>
    </div>

    <!-- ACTION BAR -->
    <div x-show="accounts.length > 0" class="flex flex-wrap items-center gap-3 mb-4">
        <button @click="refreshAll()" :disabled="refreshingAll"
                class="flex items-center gap-2 px-4 py-2 rounded-xl bg-dark-700 border border-white/10 text-sm text-white/70 hover:text-white hover:border-brand-400 transition disabled:opacity-40">
            <svg x-show="refreshingAll" class="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
            <i x-show="!refreshingAll" data-lucide="refresh-cw" class="w-4 h-4"></i>
            <span x-text="refreshingAll ? 'Atualizando...' : 'Atualizar Todas'"></span>
        </button>
        <button x-show="selectedIds.length >= 2" @click="compareSelected()"
                class="flex items-center gap-2 px-4 py-2 rounded-xl gradient-brand text-sm text-white font-semibold hover:opacity-90 transition">
            <i data-lucide="git-compare" class="w-4 h-4"></i>
            Comparar (<span x-text="selectedIds.length"></span>)
        </button>
    </div>

    <!-- ACCOUNT GRID (enriched cards) -->
    <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 mb-6">
        <template x-for="acc in accounts" :key="acc.id">
            <div class="glass-card rounded-2xl p-5 hover:border-brand-400/30 transition-all duration-300 relative">
                <!-- Checkbox -->
                <label class="absolute top-3 right-3 cursor-pointer">
                    <input type="checkbox" :value="acc.id" x-model.number="selectedIds" class="w-4 h-4 rounded accent-purple-500">
                </label>

                <!-- Header -->
                <div class="flex items-center gap-3 mb-4">
                    <img x-show="acc.avatar" :src="acc.avatar" class="w-12 h-12 rounded-full object-cover border-2 border-brand-400/30" :alt="acc.username">
                    <div x-show="!acc.avatar" class="w-12 h-12 rounded-full bg-brand-600/30 flex items-center justify-center text-white font-bold text-lg" x-text="(acc.username || '?')[0].toUpperCase()"></div>
                    <div class="flex-1 min-w-0">
                        <h4 class="font-bold text-white/90 truncate" x-text="acc.display_name || acc.username"></h4>
                        <p class="text-xs text-white/40" x-text="'@' + acc.username"></p>
                    </div>
                    <div class="flex flex-col gap-1 items-end">
                        <span x-show="acc.has_shop" class="px-2 py-0.5 text-[10px] rounded-full bg-green-500/20 text-green-400 font-bold">Shop</span>
                        <span x-show="!acc.has_shop" class="px-2 py-0.5 text-[10px] rounded-full bg-white/10 text-white/40 font-bold">Sem Loja</span>
                        <!-- Engagement badge -->
                        <span class="px-2 py-0.5 text-[10px] rounded-full font-bold"
                              :class="acc.avg_engagement_rate >= 5 ? 'bg-green-500/20 text-green-400' : acc.avg_engagement_rate >= 2 ? 'bg-yellow-500/20 text-yellow-400' : 'bg-red-500/20 text-red-400'"
                              x-text="(acc.avg_engagement_rate || 0).toFixed(1) + '% eng'"
                              x-show="acc.avg_engagement_rate > 0"></span>
                    </div>
                </div>

                <!-- Primary Metrics -->
                <div class="grid grid-cols-2 gap-3 mb-3">
                    <div class="bg-dark-800/50 rounded-xl p-3 text-center">
                        <p class="text-lg font-bold text-green-400" x-text="fmtNum(acc.total_sold)"></p>
                        <p class="text-[10px] text-white/40">Vendas</p>
                    </div>
                    <div class="bg-dark-800/50 rounded-xl p-3 text-center">
                        <p class="text-lg font-bold text-yellow-400" x-text="'$' + fmtNum(acc.estimated_revenue)"></p>
                        <p class="text-[10px] text-white/40">Revenue</p>
                    </div>
                    <div class="bg-dark-800/50 rounded-xl p-3 text-center">
                        <p class="text-lg font-bold text-blue-400" x-text="fmtNum(acc.total_views)"></p>
                        <p class="text-[10px] text-white/40">Views</p>
                    </div>
                    <div class="bg-dark-800/50 rounded-xl p-3 text-center">
                        <p class="text-lg font-bold text-purple-400" x-text="fmtNum(acc.avg_views)"></p>
                        <p class="text-[10px] text-white/40">Avg Views</p>
                    </div>
                </div>

                <!-- Secondary Metrics (enriched) -->
                <div class="flex flex-wrap gap-2 text-xs text-white/50 mb-3">
                    <span class="flex items-center gap-1"><i data-lucide="users" class="w-3 h-3"></i> <span x-text="fmtNum(acc.followers)"></span></span>
                    <span class="flex items-center gap-1"><i data-lucide="package" class="w-3 h-3"></i> <span x-text="acc.total_products"></span></span>
                    <span x-show="acc.shop_rating > 0" class="flex items-center gap-1"><i data-lucide="star" class="w-3 h-3 text-yellow-400"></i> <span x-text="acc.shop_rating.toFixed(1)"></span></span>
                    <span x-show="acc.posts_per_week > 0" class="flex items-center gap-1 px-1.5 py-0.5 rounded bg-brand-500/20 text-brand-300"><i data-lucide="calendar" class="w-3 h-3"></i> <span x-text="acc.posts_per_week.toFixed(1)"></span>/sem</span>
                    <span x-show="acc.avg_hook_strength > 0" class="flex items-center gap-1 px-1.5 py-0.5 rounded bg-orange-500/20 text-orange-300"><i data-lucide="zap" class="w-3 h-3"></i> Hook <span x-text="acc.avg_hook_strength.toFixed(0)"></span></span>
                </div>

                <!-- Commerce ratio bar -->
                <div x-show="acc.commerce_ratio > 0" class="mb-3">
                    <div class="flex justify-between text-[10px] text-white/40 mb-1">
                        <span>Commerce Ratio</span>
                        <span x-text="acc.commerce_ratio.toFixed(1) + '%'"></span>
                    </div>
                    <div class="w-full bg-dark-800/50 rounded-full h-1.5">
                        <div class="bg-gradient-to-r from-cyan-500 to-blue-500 h-1.5 rounded-full transition-all" :style="'width:' + Math.min(acc.commerce_ratio, 100) + '%'"></div>
                    </div>
                </div>

                <!-- Last checked -->
                <p x-show="acc.last_checked" class="text-[10px] text-white/25 mb-3">
                    Atualizado: <span x-text="timeAgo(acc.last_checked)"></span>
                </p>

                <!-- Actions -->
                <div class="flex gap-2">
                    <button @click="refreshOne(acc.id)" :disabled="refreshingId === acc.id"
                            class="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-xl bg-dark-700 border border-white/10 text-xs text-white/60 hover:text-white hover:border-brand-400 transition disabled:opacity-40">
                        <svg x-show="refreshingId === acc.id" class="animate-spin w-3 h-3" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                        <i x-show="refreshingId !== acc.id" data-lucide="refresh-cw" class="w-3 h-3"></i>
                        Refresh
                    </button>
                    <button @click="openDetail(acc.id)"
                            class="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-xl bg-dark-700 border border-white/10 text-xs text-white/60 hover:text-white hover:border-brand-400 transition">
                        <i data-lucide="bar-chart-3" class="w-3 h-3"></i>
                        Detalhes
                    </button>
                    <button @click="removeAccount(acc.id)"
                            class="flex items-center justify-center px-3 py-2 rounded-xl bg-dark-700 border border-white/10 text-xs text-red-400/60 hover:text-red-400 hover:border-red-400/30 transition">
                        <i data-lucide="trash-2" class="w-3 h-3"></i>
                    </button>
                </div>
            </div>
        </template>
    </div>

    <!-- EMPTY STATE -->
    <div x-show="accounts.length === 0 && !loading" class="glass-card rounded-2xl p-12 text-center">
        <i data-lucide="store" class="w-16 h-16 text-white/10 mx-auto mb-4"></i>
        <h3 class="text-lg font-bold text-white/60 mb-2">Nenhuma conta monitorada</h3>
        <p class="text-sm text-white/30">Adicione contas TikTok Shop acima para comecar a monitorar</p>
    </div>

    <!-- ═══════════════ DETAIL MODAL - 6 TABS ═══════════════ -->
    <div x-show="detailAccount" x-transition.opacity class="fixed inset-0 z-50 flex items-center justify-center p-4" style="background: rgba(0,0,0,0.7); backdrop-filter: blur(8px);">
        <div @click.outside="detailAccount = null" class="glass-card rounded-2xl w-full max-w-5xl max-h-[92vh] flex flex-col">
            <!-- Modal Header -->
            <div class="flex items-center justify-between p-5 border-b border-white/10 flex-shrink-0">
                <div class="flex items-center gap-3">
                    <img x-show="detailAccount?.avatar" :src="detailAccount?.avatar" class="w-10 h-10 rounded-full">
                    <div>
                        <h3 class="text-lg font-bold text-white/90" x-text="detailAccount?.display_name || detailAccount?.username"></h3>
                        <p class="text-xs text-white/40" x-text="'@' + (detailAccount?.username || '')"></p>
                    </div>
                </div>
                <button @click="detailAccount = null" class="text-white/40 hover:text-white transition">
                    <i data-lucide="x" class="w-5 h-5"></i>
                </button>
            </div>

            <!-- Tab Navigation -->
            <div class="flex border-b border-white/10 px-5 overflow-x-auto flex-shrink-0">
                <template x-for="tab in ['Overview','Growth','Videos','Products','Content Strategy','AI Intelligence']" :key="tab">
                    <button @click="activeTab = tab; watchTab()"
                            class="px-4 py-3 text-xs font-medium border-b-2 transition whitespace-nowrap"
                            :class="activeTab === tab ? 'border-brand-400 text-brand-300' : 'border-transparent text-white/40 hover:text-white/60'">
                        <span x-text="tab"></span>
                    </button>
                </template>
            </div>

            <!-- Tab Content (scrollable) -->
            <div class="flex-1 overflow-y-auto p-5">

                <!-- ═══ TAB 1: OVERVIEW ═══ -->
                <div x-show="activeTab === 'Overview'">
                    <!-- Bio -->
                    <p x-show="detailAccount?.bio" class="text-xs text-white/50 mb-4 p-3 bg-dark-800/50 rounded-xl" x-text="detailAccount?.bio"></p>

                    <!-- 2x4 metrics grid -->
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3 mb-6">
                        <div class="bg-dark-800/50 rounded-xl p-4 text-center">
                            <p class="text-xl font-bold text-green-400" x-text="fmtNum(detailAccount?.total_sold || 0)"></p>
                            <p class="text-[10px] text-white/40 mt-1">Vendas</p>
                            <p class="text-[10px] mt-1" :class="(detailGrowth.growth?.sold || 0) >= 0 ? 'text-green-400' : 'text-red-400'" x-text="(detailGrowth.growth?.sold >= 0 ? '+' : '') + fmtNum(detailGrowth.growth?.sold || 0)"></p>
                        </div>
                        <div class="bg-dark-800/50 rounded-xl p-4 text-center">
                            <p class="text-xl font-bold text-yellow-400" x-text="'$' + fmtNum(detailAccount?.estimated_revenue || 0)"></p>
                            <p class="text-[10px] text-white/40 mt-1">Revenue</p>
                            <p class="text-[10px] mt-1" :class="(detailGrowth.growth?.revenue || 0) >= 0 ? 'text-green-400' : 'text-red-400'" x-text="'$' + fmtNum(detailGrowth.growth?.revenue || 0)"></p>
                        </div>
                        <div class="bg-dark-800/50 rounded-xl p-4 text-center">
                            <p class="text-xl font-bold text-blue-400" x-text="fmtNum(detailAccount?.total_views || 0)"></p>
                            <p class="text-[10px] text-white/40 mt-1">Views</p>
                            <p class="text-[10px] mt-1" :class="(detailGrowth.growth?.views || 0) >= 0 ? 'text-green-400' : 'text-red-400'" x-text="fmtNum(detailGrowth.growth?.views || 0)"></p>
                        </div>
                        <div class="bg-dark-800/50 rounded-xl p-4 text-center">
                            <p class="text-xl font-bold text-purple-400" x-text="fmtNum(detailAccount?.followers || 0)"></p>
                            <p class="text-[10px] text-white/40 mt-1">Followers</p>
                            <p class="text-[10px] mt-1" :class="(detailGrowth.growth?.followers || 0) >= 0 ? 'text-green-400' : 'text-red-400'" x-text="fmtNum(detailGrowth.growth?.followers || 0)"></p>
                        </div>
                        <div class="bg-dark-800/50 rounded-xl p-4 text-center">
                            <p class="text-xl font-bold text-orange-400" x-text="(detailAccount?.avg_engagement_rate || 0).toFixed(1) + '%'"></p>
                            <p class="text-[10px] text-white/40 mt-1">Engagement</p>
                        </div>
                        <div class="bg-dark-800/50 rounded-xl p-4 text-center">
                            <p class="text-xl font-bold text-amber-400" x-text="(detailAccount?.avg_hook_strength || 0).toFixed(0)"></p>
                            <p class="text-[10px] text-white/40 mt-1">Hook Strength</p>
                        </div>
                        <div class="bg-dark-800/50 rounded-xl p-4 text-center">
                            <p class="text-xl font-bold text-cyan-400" x-text="(detailAccount?.commerce_ratio || 0).toFixed(1) + '%'"></p>
                            <p class="text-[10px] text-white/40 mt-1">Commerce Ratio</p>
                        </div>
                        <div class="bg-dark-800/50 rounded-xl p-4 text-center">
                            <p class="text-xl font-bold text-pink-400" x-text="(detailAccount?.posts_per_week || 0).toFixed(1)"></p>
                            <p class="text-[10px] text-white/40 mt-1">Posts/Semana</p>
                        </div>
                    </div>

                    <!-- Quick stats row -->
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                        <div class="bg-dark-800/30 rounded-lg p-3 text-center">
                            <p class="text-sm font-bold text-white/70" x-text="(detailAccount?.avg_shareability || 0).toFixed(0)"></p>
                            <p class="text-[10px] text-white/30">Shareability</p>
                        </div>
                        <div class="bg-dark-800/30 rounded-lg p-3 text-center">
                            <p class="text-sm font-bold text-white/70" x-text="'$' + (detailAccount?.revenue_per_video || 0).toFixed(2)"></p>
                            <p class="text-[10px] text-white/30">Revenue/Video</p>
                        </div>
                        <div class="bg-dark-800/30 rounded-lg p-3 text-center">
                            <p class="text-sm font-bold text-white/70" x-text="(detailAccount?.follower_to_sale_ratio || 0).toFixed(0) + ':1'"></p>
                            <p class="text-[10px] text-white/30">Follower:Sale</p>
                        </div>
                        <div class="bg-dark-800/30 rounded-lg p-3 text-center">
                            <p class="text-sm font-bold text-white/70" x-text="(detailAccount?.avg_duration || 0).toFixed(0) + 's'"></p>
                            <p class="text-[10px] text-white/30">Avg Duration</p>
                        </div>
                    </div>
                </div>

                <!-- ═══ TAB 2: GROWTH ═══ -->
                <div x-show="activeTab === 'Growth'">
                    <!-- Period selector -->
                    <div class="flex gap-2 mb-4">
                        <template x-for="d in [7, 14, 30, 60, 90]" :key="d">
                            <button @click="loadGrowth(d)"
                                    class="px-3 py-1.5 text-xs rounded-lg transition"
                                    :class="growthDays === d ? 'bg-brand-500 text-white' : 'bg-dark-700 text-white/40 hover:text-white/70'">
                                <span x-text="d + 'd'"></span>
                            </button>
                        </template>
                    </div>

                    <!-- Growth chart -->
                    <div class="bg-dark-800/50 rounded-xl p-4 mb-4">
                        <canvas id="growthChart" height="250"></canvas>
                    </div>

                    <!-- Growth deltas -->
                    <div x-show="detailGrowth.growth" class="grid grid-cols-2 md:grid-cols-4 gap-3">
                        <div class="bg-dark-800/50 rounded-lg p-3 text-center">
                            <p class="text-sm font-bold" :class="(detailGrowth.growth?.sold || 0) >= 0 ? 'text-green-400' : 'text-red-400'" x-text="(detailGrowth.growth?.sold >= 0 ? '+' : '') + fmtNum(detailGrowth.growth?.sold || 0)"></p>
                            <p class="text-[10px] text-white/40">Vendas</p>
                            <p class="text-[9px] text-white/25" x-text="(detailGrowth.growth?.sold_per_day || 0).toFixed(1) + '/dia'"></p>
                        </div>
                        <div class="bg-dark-800/50 rounded-lg p-3 text-center">
                            <p class="text-sm font-bold" :class="(detailGrowth.growth?.revenue || 0) >= 0 ? 'text-yellow-400' : 'text-red-400'" x-text="'$' + fmtNum(detailGrowth.growth?.revenue || 0)"></p>
                            <p class="text-[10px] text-white/40">Revenue</p>
                            <p class="text-[9px] text-white/25" x-text="'$' + (detailGrowth.growth?.revenue_per_day || 0).toFixed(2) + '/dia'"></p>
                        </div>
                        <div class="bg-dark-800/50 rounded-lg p-3 text-center">
                            <p class="text-sm font-bold" :class="(detailGrowth.growth?.views || 0) >= 0 ? 'text-blue-400' : 'text-red-400'" x-text="fmtNum(detailGrowth.growth?.views || 0)"></p>
                            <p class="text-[10px] text-white/40">Views</p>
                            <p class="text-[9px] text-white/25" x-text="fmtNum(detailGrowth.growth?.views_per_day || 0) + '/dia'"></p>
                        </div>
                        <div class="bg-dark-800/50 rounded-lg p-3 text-center">
                            <p class="text-sm font-bold" :class="(detailGrowth.growth?.followers || 0) >= 0 ? 'text-purple-400' : 'text-red-400'" x-text="fmtNum(detailGrowth.growth?.followers || 0)"></p>
                            <p class="text-[10px] text-white/40">Followers</p>
                            <p class="text-[9px] text-white/25" x-text="(detailGrowth.growth?.followers_percent || 0).toFixed(1) + '%'"></p>
                        </div>
                    </div>
                </div>

                <!-- ═══ TAB 3: VIDEOS ═══ -->
                <div x-show="activeTab === 'Videos'">
                    <!-- Controls -->
                    <div class="flex flex-wrap gap-3 mb-4">
                        <select x-model="videoSort" @change="sortVideos()" class="bg-dark-700 border border-white/10 rounded-lg px-3 py-1.5 text-xs text-white/70">
                            <option value="viral_score">Viral Score</option>
                            <option value="views">Views</option>
                            <option value="engagement_rate">Engagement</option>
                            <option value="hook_score">Hook Score</option>
                            <option value="shareability_score">Shareability</option>
                            <option value="likes">Likes</option>
                            <option value="shares">Shares</option>
                            <option value="comments">Comments</option>
                            <option value="monetization_score">Monetization</option>
                        </select>
                        <select x-model="videoFilter" @change="filterVideos()" class="bg-dark-700 border border-white/10 rounded-lg px-3 py-1.5 text-xs text-white/70">
                            <option value="all">Todos</option>
                            <option value="commerce">Commerce</option>
                            <option value="organic">Organico</option>
                            <option value="high_eng">Eng > 5%</option>
                            <option value="viral">Viral (>100K views)</option>
                            <option value="short">Curtos (<=15s)</option>
                            <option value="medium">Medios (16-60s)</option>
                            <option value="long">Longos (>60s)</option>
                            <option value="with_transcript">Com Transcricao</option>
                        </select>
                        <span class="text-xs text-white/30 flex items-center" x-text="filteredVideos.length + ' videos'"></span>
                        <!-- Transcribe button -->
                        <button @click="loadTranscripts()" :disabled="loadingTranscripts"
                                class="ml-auto flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-brand-600/30 text-brand-300 hover:bg-brand-600/50 transition disabled:opacity-40">
                            <svg x-show="loadingTranscripts" class="animate-spin w-3 h-3" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                            <i x-show="!loadingTranscripts" data-lucide="mic" class="w-3 h-3"></i>
                            <span x-text="loadingTranscripts ? 'Transcrevendo...' : 'Transcrever Top Videos'"></span>
                        </button>
                    </div>

                    <!-- Video table -->
                    <div class="overflow-x-auto">
                        <table class="w-full text-xs">
                            <thead>
                                <tr class="text-white/40 border-b border-white/10">
                                    <th class="text-left py-2 px-2">#</th>
                                    <th class="text-left py-2 px-2">Video</th>
                                    <th class="text-right py-2 px-2">Views</th>
                                    <th class="text-right py-2 px-2">Likes</th>
                                    <th class="text-right py-2 px-2">Shares</th>
                                    <th class="text-right py-2 px-2">Eng%</th>
                                    <th class="text-right py-2 px-2">Hook</th>
                                    <th class="text-right py-2 px-2">Share</th>
                                    <th class="text-right py-2 px-2">Monet</th>
                                    <th class="text-center py-2 px-2">Flags</th>
                                    <th class="text-right py-2 px-2">Viral</th>
                                </tr>
                            </thead>
                            <tbody>
                                <template x-for="(v, i) in filteredVideos" :key="v.id || i">
                                    <tr class="border-b border-white/5 hover:bg-white/5 cursor-pointer" @click="expandedVideo = expandedVideo === i ? -1 : i">
                                        <td class="py-2 px-2 text-white/30" x-text="i + 1"></td>
                                        <td class="py-2 px-2 max-w-[200px]">
                                            <div class="flex items-center gap-2">
                                                <img x-show="v.thumbnail" :src="v.thumbnail" class="w-10 h-7 rounded object-cover flex-shrink-0">
                                                <div class="min-w-0">
                                                    <span class="text-white/70 truncate block" x-text="v.title || 'Video'"></span>
                                                    <span class="text-[9px] text-white/25" x-text="(v.duration || 0) + 's'"></span>
                                                </div>
                                            </div>
                                        </td>
                                        <td class="py-2 px-2 text-right text-blue-400 font-medium" x-text="fmtNum(v.views)"></td>
                                        <td class="py-2 px-2 text-right text-pink-400" x-text="fmtNum(v.likes)"></td>
                                        <td class="py-2 px-2 text-right text-cyan-400" x-text="fmtNum(v.shares)"></td>
                                        <td class="py-2 px-2 text-right font-medium"
                                            :class="v.engagement_rate >= 5 ? 'text-green-400' : v.engagement_rate >= 2 ? 'text-yellow-400' : 'text-red-400'"
                                            x-text="(v.engagement_rate || 0).toFixed(1) + '%'"></td>
                                        <td class="py-2 px-2 text-right">
                                            <span class="inline-block w-7 h-7 rounded-full text-[10px] font-bold flex items-center justify-center"
                                                  :class="v.hook_score >= 60 ? 'bg-green-500/20 text-green-400' : v.hook_score >= 30 ? 'bg-yellow-500/20 text-yellow-400' : 'bg-red-500/20 text-red-400'"
                                                  x-text="v.hook_score || 0"></span>
                                        </td>
                                        <td class="py-2 px-2 text-right text-white/60" x-text="v.shareability_score || 0"></td>
                                        <td class="py-2 px-2 text-right text-white/60" x-text="v.monetization_score || 0"></td>
                                        <td class="py-2 px-2 text-center flex gap-0.5 justify-center">
                                            <span x-show="v.has_commerce" class="px-1 py-0.5 text-[8px] rounded bg-cyan-500/20 text-cyan-400 font-bold">Shop</span>
                                            <span x-show="v.transcript" class="px-1 py-0.5 text-[8px] rounded bg-purple-500/20 text-purple-400 font-bold">TXT</span>
                                            <span x-show="v.is_ad" class="px-1 py-0.5 text-[8px] rounded bg-yellow-500/20 text-yellow-400 font-bold">Ad</span>
                                        </td>
                                        <td class="py-2 px-2 text-right font-bold text-brand-300" x-text="(v.viral_score || 0).toFixed(0)"></td>
                                    </tr>
                                    <!-- Expanded row with transcript -->
                                    <tr x-show="expandedVideo === i" class="bg-dark-800/30">
                                        <td colspan="11" class="p-4">
                                            <div class="space-y-3">
                                                <div class="flex flex-wrap gap-4 text-xs text-white/50">
                                                    <div><span class="text-white/30">Duracao:</span> <span x-text="(v.duration || 0) + 's'"></span></div>
                                                    <div><span class="text-white/30">Hashtags:</span> <span x-text="(v.hashtags || []).map(h => '#' + h).join(' ')"></span></div>
                                                    <div x-show="v.music"><span class="text-white/30">Musica:</span> <span x-text="(v.music?.title || '') + ' - ' + (v.music?.author || '')"></span></div>
                                                    <div x-show="v.region"><span class="text-white/30">Regiao:</span> <span x-text="v.region"></span></div>
                                                    <div x-show="v.audio_language"><span class="text-white/30">Idioma:</span> <span x-text="v.audio_language"></span></div>
                                                    <div x-show="v.is_ad" class="text-yellow-400">Anuncio</div>
                                                    <div x-show="v.is_paid_partnership" class="text-yellow-400">Parceria Paga</div>
                                                    <div x-show="v.created_by_ai" class="text-purple-400">Criado por IA</div>
                                                    <div x-show="v.is_eligible_for_commission" class="text-green-400">Elegivel Comissao</div>
                                                    <a x-show="v.url" :href="v.url" target="_blank" class="text-brand-300 hover:text-brand-200 flex items-center gap-1">
                                                        <i data-lucide="external-link" class="w-3 h-3"></i> Abrir
                                                    </a>
                                                </div>
                                                <!-- Transcript -->
                                                <div x-show="v.transcript" class="bg-dark-700/50 rounded-lg p-3">
                                                    <div class="flex items-center gap-2 mb-2">
                                                        <i data-lucide="file-text" class="w-3 h-3 text-purple-400"></i>
                                                        <span class="text-[10px] text-purple-400 font-bold">TRANSCRICAO</span>
                                                    </div>
                                                    <p class="text-xs text-white/70 leading-relaxed whitespace-pre-wrap" x-text="v.transcript"></p>
                                                </div>
                                                <p x-show="!v.transcript" class="text-[10px] text-white/20 italic">Sem transcricao. Use o botao "Transcrever Top Videos" acima.</p>
                                            </div>
                                        </td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                    </div>
                    <p x-show="filteredVideos.length === 0" class="text-center text-white/30 text-sm py-8">Nenhum video carregado. Faca um refresh da conta para buscar videos.</p>
                </div>

                <!-- ═══ TAB 4: PRODUCTS ═══ -->
                <div x-show="activeTab === 'Products'">
                    <!-- Product sorting -->
                    <div class="flex gap-2 mb-4">
                        <select x-model="productSort" @change="loadProducts()" class="bg-dark-700 border border-white/10 rounded-lg px-3 py-1.5 text-xs text-white/70">
                            <option value="sold_count">Mais Vendidos</option>
                            <option value="rating">Melhor Rating</option>
                            <option value="price">Maior Preco</option>
                            <option value="review_count">Mais Reviews</option>
                        </select>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <template x-for="(p, i) in detailProducts" :key="p.id || i">
                            <div class="bg-dark-800/50 rounded-xl p-4 flex gap-3">
                                <img x-show="p.image" :src="p.image" class="w-16 h-16 rounded-lg object-cover flex-shrink-0">
                                <div class="flex-1 min-w-0">
                                    <p class="text-xs text-white/80 font-medium truncate" x-text="p.title"></p>
                                    <div class="flex gap-3 mt-2 text-[10px] text-white/50">
                                        <span class="text-green-400 font-bold" x-text="fmtNum(p.sold_count) + ' vendidos'"></span>
                                        <span x-text="p.price"></span>
                                        <span x-show="p.rating > 0" class="flex items-center gap-0.5"><i data-lucide="star" class="w-2.5 h-2.5 text-yellow-400"></i> <span x-text="p.rating.toFixed(1)"></span></span>
                                        <span x-show="p.review_count > 0" x-text="fmtNum(p.review_count) + ' reviews'"></span>
                                    </div>
                                    <!-- Sparkline placeholder for trends -->
                                    <div x-show="p.sold_growth !== undefined" class="mt-2">
                                        <span class="text-[9px]" :class="(p.sold_growth || 0) >= 0 ? 'text-green-400' : 'text-red-400'" x-text="(p.sold_growth >= 0 ? '+' : '') + fmtNum(p.sold_growth || 0) + ' vendas no periodo'"></span>
                                    </div>
                                </div>
                                <span x-show="i === 0" class="px-2 py-0.5 text-[9px] rounded-full bg-yellow-500/20 text-yellow-400 font-bold h-fit">TOP</span>
                            </div>
                        </template>
                    </div>
                    <p x-show="detailProducts.length === 0" class="text-center text-white/30 text-sm py-8">Nenhum produto encontrado.</p>

                    <!-- Product-Video Mapping -->
                    <div class="mt-6">
                        <div class="flex items-center justify-between mb-3">
                            <h5 class="text-sm font-bold text-white/70 flex items-center gap-2">
                                <i data-lucide="link" class="w-4 h-4 text-cyan-400"></i> Mapeamento Produto-Video
                            </h5>
                            <div class="flex items-center gap-2 text-xs text-white/30">
                                <template x-if="loadingProductMap">
                                    <span class="flex items-center gap-1">
                                        <svg class="animate-spin w-3 h-3" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                                        Mapeando...
                                    </span>
                                </template>
                                <template x-if="productVideoMap?.summary">
                                    <span x-text="productVideoMap.summary.products_with_videos + '/' + productVideoMap.summary.total_products + ' produtos com videos'"></span>
                                </template>
                            </div>
                        </div>

                        <template x-if="productVideoMap && productVideoMap.product_videos">
                            <div class="space-y-3">
                                <template x-for="(pv, pvIdx) in productVideoMap.product_videos" :key="pvIdx">
                                    <div class="bg-dark-800/50 rounded-xl p-4">
                                        <div class="flex items-start gap-3 mb-2">
                                            <img x-show="pv.product?.image" :src="pv.product?.image" class="w-12 h-12 rounded-lg object-cover flex-shrink-0">
                                            <div class="flex-1 min-w-0">
                                                <p class="text-xs text-white/80 font-medium truncate" x-text="pv.product?.title || 'Produto'"></p>
                                                <div class="flex gap-2 mt-1 text-[10px] text-white/40">
                                                    <span x-text="pv.product?.price || ''"></span>
                                                    <span class="text-green-400" x-text="fmtNum(pv.product?.sold_count || 0) + ' vendidos'"></span>
                                                    <span class="text-cyan-400" x-text="(pv.videos || []).length + ' videos'"></span>
                                                </div>
                                            </div>
                                        </div>
                                        <!-- Videos associated with this product -->
                                        <div x-show="pv.videos && pv.videos.length > 0" class="pl-4 border-l-2 border-cyan-500/20 space-y-1.5">
                                            <template x-for="vid in (pv.videos || []).slice(0, 5)" :key="vid.id || vid.url">
                                                <div class="flex items-center gap-2 text-[10px] p-1.5 rounded hover:bg-white/5">
                                                    <img x-show="vid.thumbnail" :src="vid.thumbnail" class="w-8 h-5 rounded object-cover flex-shrink-0">
                                                    <span class="text-white/60 truncate flex-1" x-text="vid.title || 'Video'"></span>
                                                    <span class="text-blue-400" x-text="fmtNum(vid.views || 0) + ' views'"></span>
                                                    <span class="text-pink-400" x-text="fmtNum(vid.likes || 0) + ' likes'"></span>
                                                    <a x-show="vid.url" :href="vid.url" target="_blank" class="text-brand-300 hover:text-brand-200" @click.stop>
                                                        <i data-lucide="external-link" class="w-3 h-3"></i>
                                                    </a>
                                                </div>
                                            </template>
                                        </div>
                                        <p x-show="!pv.videos || pv.videos.length === 0" class="text-[10px] text-white/20 italic pl-4">Nenhum video detectado para este produto</p>
                                    </div>
                                </template>

                                <!-- Products without videos -->
                                <div x-show="productVideoMap.products_without_videos && productVideoMap.products_without_videos.length > 0" class="mt-4">
                                    <h6 class="text-[10px] text-white/30 mb-2 font-bold uppercase">Produtos sem videos detectados</h6>
                                    <div class="flex flex-wrap gap-2">
                                        <template x-for="np in productVideoMap.products_without_videos" :key="np.title">
                                            <span class="px-2 py-1 text-[10px] rounded-lg bg-red-500/10 text-red-400/60" x-text="np.title"></span>
                                        </template>
                                    </div>
                                </div>
                            </div>
                        </template>
                        <p x-show="!productVideoMap && !loadingProductMap" class="text-center text-white/20 text-xs py-4">O mapeamento sera carregado automaticamente.</p>
                    </div>
                </div>

                <!-- ═══ TAB 5: CONTENT STRATEGY ═══ -->
                <div x-show="activeTab === 'Content Strategy'">
                    <div x-show="loadingContent" class="flex items-center justify-center py-12">
                        <svg class="animate-spin w-8 h-8 text-brand-400" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                    </div>

                    <div x-show="!loadingContent">
                        <!-- Best times -->
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                            <div class="bg-dark-800/50 rounded-xl p-4">
                                <h5 class="text-xs font-bold text-white/50 mb-2 flex items-center gap-1"><i data-lucide="calendar" class="w-3 h-3"></i> Posts/Semana</h5>
                                <p class="text-2xl font-bold text-brand-300" x-text="(contentData.cadence?.posts_per_week || 0).toFixed(1)"></p>
                            </div>
                            <div class="bg-dark-800/50 rounded-xl p-4">
                                <h5 class="text-xs font-bold text-white/50 mb-2 flex items-center gap-1"><i data-lucide="clock" class="w-3 h-3"></i> Melhores Dias</h5>
                                <p class="text-sm font-bold text-green-400" x-text="(contentData.cadence?.best_days || []).join(', ') || '-'"></p>
                            </div>
                            <div class="bg-dark-800/50 rounded-xl p-4">
                                <h5 class="text-xs font-bold text-white/50 mb-2 flex items-center gap-1"><i data-lucide="timer" class="w-3 h-3"></i> Melhores Horas</h5>
                                <p class="text-sm font-bold text-blue-400" x-text="(contentData.cadence?.best_hours || []).map(h => h + 'h').join(', ') || '-'"></p>
                            </div>
                        </div>

                        <!-- Cadence Heatmap -->
                        <div class="bg-dark-800/50 rounded-xl p-4 mb-6">
                            <h5 class="text-xs font-bold text-white/50 mb-3 flex items-center gap-1"><i data-lucide="grid-3x3" class="w-3 h-3"></i> Heatmap de Cadencia</h5>
                            <div class="overflow-x-auto">
                                <canvas id="heatmapChart" height="200"></canvas>
                            </div>
                        </div>

                        <!-- Format distribution & Hashtags side by side -->
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                            <!-- Donut chart - Formats -->
                            <div class="bg-dark-800/50 rounded-xl p-4">
                                <h5 class="text-xs font-bold text-white/50 mb-3 flex items-center gap-1"><i data-lucide="pie-chart" class="w-3 h-3"></i> Mix de Formatos</h5>
                                <canvas id="formatChart" height="200"></canvas>
                                <div class="flex justify-center gap-4 mt-3 text-[10px] text-white/50">
                                    <span>Avg: <span class="text-white/80" x-text="(contentData.formats?.avg_duration || 0).toFixed(0) + 's'"></span></span>
                                </div>
                            </div>

                            <!-- Hashtag cloud -->
                            <div class="bg-dark-800/50 rounded-xl p-4">
                                <h5 class="text-xs font-bold text-white/50 mb-3 flex items-center gap-1"><i data-lucide="hash" class="w-3 h-3"></i> Top Hashtags</h5>
                                <div class="flex flex-wrap gap-2 max-h-[250px] overflow-y-auto">
                                    <template x-for="tag in (contentData.hashtags?.top_hashtags || []).slice(0, 30)" :key="tag.tag">
                                        <span class="px-2 py-1 rounded-lg text-xs font-medium transition"
                                              :style="'font-size:' + Math.max(10, Math.min(18, 10 + tag.count * 2)) + 'px'"
                                              :class="tag.avg_views > 50000 ? 'bg-green-500/20 text-green-400' : tag.avg_views > 10000 ? 'bg-blue-500/20 text-blue-400' : 'bg-white/10 text-white/50'"
                                              x-text="'#' + tag.tag + ' (' + tag.count + ')'"></span>
                                    </template>
                                </div>
                                <p class="text-[10px] text-white/30 mt-2" x-text="'Avg ' + (contentData.hashtags?.avg_tags_per_post || 0).toFixed(1) + ' tags/post | ' + (contentData.hashtags?.total_unique_tags || 0) + ' unicas'"></p>
                            </div>
                        </div>

                        <!-- Top Content -->
                        <div class="bg-dark-800/50 rounded-xl p-4">
                            <h5 class="text-xs font-bold text-white/50 mb-3 flex items-center gap-1"><i data-lucide="trophy" class="w-3 h-3"></i> Top 10 Content</h5>
                            <div class="space-y-2">
                                <template x-for="(tc, i) in (contentData.top_content || [])" :key="i">
                                    <div class="flex items-center gap-3 p-2 rounded-lg hover:bg-white/5">
                                        <span class="text-[10px] font-bold w-5 text-white/30" x-text="i + 1"></span>
                                        <img x-show="tc.thumbnail" :src="tc.thumbnail" class="w-12 h-8 rounded object-cover">
                                        <div class="flex-1 min-w-0">
                                            <p class="text-xs text-white/70 truncate" x-text="tc.title || 'Video'"></p>
                                            <div class="flex gap-3 text-[10px] text-white/40 mt-0.5">
                                                <span x-text="fmtNum(tc.views) + ' views'"></span>
                                                <span x-text="tc.engagement_rate + '% eng'"></span>
                                                <span x-text="(tc.duration || 0) + 's'"></span>
                                            </div>
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- ═══ TAB 6: AI INTELLIGENCE ═══ -->
                <div x-show="activeTab === 'AI Intelligence'">
                    <div x-show="loadingAI" class="flex items-center justify-center py-12">
                        <div class="text-center">
                            <svg class="animate-spin w-8 h-8 text-brand-400 mx-auto mb-3" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                            <p class="text-xs text-white/40">Gerando analise com IA...</p>
                        </div>
                    </div>

                    <div x-show="!loadingAI">
                        <!-- AI Report -->
                        <div class="bg-dark-800/50 rounded-xl p-5 mb-6">
                            <div class="flex items-center justify-between mb-3">
                                <h5 class="text-sm font-bold text-white/70 flex items-center gap-2"><i data-lucide="brain" class="w-4 h-4 text-brand-300"></i> Relatorio IA Estrategico</h5>
                                <button @click="loadAIReport(true)" class="text-xs text-brand-300 hover:text-brand-200 transition flex items-center gap-1">
                                    <i data-lucide="refresh-cw" class="w-3 h-3"></i> Regenerar
                                </button>
                            </div>
                            <div class="prose prose-invert prose-sm max-w-none text-xs text-white/70 leading-relaxed whitespace-pre-wrap" x-text="aiData.report || 'Clique em Regenerar para gerar o relatorio.'"></div>
                        </div>

                        <!-- Revenue Breakdown -->
                        <div class="bg-dark-800/50 rounded-xl p-5 mb-6">
                            <h5 class="text-sm font-bold text-white/70 mb-4 flex items-center gap-2"><i data-lucide="dollar-sign" class="w-4 h-4 text-yellow-400"></i> Revenue Breakdown</h5>
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                                <div class="bg-dark-700/50 rounded-lg p-4 text-center">
                                    <p class="text-[10px] text-white/40 mb-1">Shop Revenue</p>
                                    <p class="text-xl font-bold text-green-400" x-text="'$' + fmtNum(revenueData.shop_revenue || 0)"></p>
                                    <p class="text-[9px] text-white/25 mt-1" x-text="'$' + (revenueData.revenue_per_video || 0).toFixed(2) + '/video'"></p>
                                </div>
                                <div class="bg-dark-700/50 rounded-lg p-4 text-center">
                                    <p class="text-[10px] text-white/40 mb-1">Ad Revenue (mensal)</p>
                                    <div class="flex items-end justify-center gap-1">
                                        <span class="text-xs text-white/30">$<span x-text="(revenueData.ad_revenue?.low || 0).toFixed(0)"></span></span>
                                        <span class="text-xl font-bold text-yellow-400" x-text="'$' + fmtNum(revenueData.ad_revenue?.mid || 0)"></span>
                                        <span class="text-xs text-white/30">$<span x-text="(revenueData.ad_revenue?.high || 0).toFixed(0)"></span></span>
                                    </div>
                                    <p class="text-[9px] text-white/25 mt-1" x-text="fmtNum(revenueData.monthly_views || 0) + ' views/mes'"></p>
                                </div>
                                <div class="bg-dark-700/50 rounded-lg p-4 text-center">
                                    <p class="text-[10px] text-white/40 mb-1">Total Combinado (est.)</p>
                                    <div class="flex items-end justify-center gap-1">
                                        <span class="text-xs text-white/30">$<span x-text="(revenueData.combined_monthly?.low || 0).toFixed(0)"></span></span>
                                        <span class="text-xl font-bold text-brand-300" x-text="'$' + fmtNum(revenueData.combined_monthly?.mid || 0)"></span>
                                        <span class="text-xs text-white/30">$<span x-text="(revenueData.combined_monthly?.high || 0).toFixed(0)"></span></span>
                                    </div>
                                    <p class="text-[9px] text-white/25 mt-1" x-text="'Tier: ' + (revenueData.tier || 'N/A')"></p>
                                </div>
                            </div>
                        </div>

                        <!-- Insights (AI-generated actionable insights) -->
                        <div class="bg-dark-800/50 rounded-xl p-5 mb-6">
                            <div class="flex items-center justify-between mb-3">
                                <h5 class="text-sm font-bold text-white/70 flex items-center gap-2"><i data-lucide="lightbulb" class="w-4 h-4 text-amber-400"></i> Insights Acionaveis</h5>
                                <button @click="loadInsights(true)" :disabled="loadingInsights" class="text-xs text-amber-300 hover:text-amber-200 transition flex items-center gap-1">
                                    <svg x-show="loadingInsights" class="animate-spin w-3 h-3" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                                    <i x-show="!loadingInsights" data-lucide="refresh-cw" class="w-3 h-3"></i> Regenerar
                                </button>
                            </div>
                            <div x-show="insightsData?.insights" class="prose prose-invert prose-sm max-w-none text-xs text-white/70 leading-relaxed whitespace-pre-wrap" x-text="insightsData?.insights || ''"></div>
                            <p x-show="insightsData?.generated_at" class="text-[9px] text-white/20 mt-2" x-text="'Gerado: ' + (insightsData?.generated_at ? new Date(insightsData.generated_at).toLocaleString('pt-BR') : '')"></p>
                            <p x-show="!insightsData?.insights && !loadingInsights" class="text-xs text-white/30 italic">Clique em Regenerar para gerar insights acionaveis com IA.</p>
                        </div>

                        <!-- Video Ideas (AI-generated content ideas) -->
                        <div class="bg-dark-800/50 rounded-xl p-5 mb-6">
                            <div class="flex items-center justify-between mb-3">
                                <h5 class="text-sm font-bold text-white/70 flex items-center gap-2"><i data-lucide="video" class="w-4 h-4 text-green-400"></i> Ideias de Videos</h5>
                                <button @click="loadVideoIdeas(true)" :disabled="loadingIdeas" class="text-xs text-green-300 hover:text-green-200 transition flex items-center gap-1">
                                    <svg x-show="loadingIdeas" class="animate-spin w-3 h-3" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>
                                    <i x-show="!loadingIdeas" data-lucide="refresh-cw" class="w-3 h-3"></i> Regenerar
                                </button>
                            </div>
                            <div x-show="videoIdeasData?.ideas" class="prose prose-invert prose-sm max-w-none text-xs text-white/70 leading-relaxed whitespace-pre-wrap" x-text="videoIdeasData?.ideas || ''"></div>
                            <p x-show="videoIdeasData?.generated_at" class="text-[9px] text-white/20 mt-2" x-text="'Gerado: ' + (videoIdeasData?.generated_at ? new Date(videoIdeasData.generated_at).toLocaleString('pt-BR') : '')"></p>
                            <p x-show="!videoIdeasData?.ideas && !loadingIdeas" class="text-xs text-white/30 italic">Clique em Regenerar para gerar ideias de videos com IA.</p>
                        </div>

                        <!-- Commerce Analysis -->
                        <div class="bg-dark-800/50 rounded-xl p-5">
                            <h5 class="text-sm font-bold text-white/70 mb-4 flex items-center gap-2"><i data-lucide="shopping-bag" class="w-4 h-4 text-cyan-400"></i> Commerce vs Organico</h5>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                                <div class="bg-dark-700/50 rounded-lg p-4">
                                    <div class="flex items-center justify-between mb-2">
                                        <span class="text-xs text-cyan-400 font-bold">Commerce</span>
                                        <span class="text-[10px] text-white/30" x-text="(commerceData.commerce?.count || 0) + ' videos'"></span>
                                    </div>
                                    <div class="grid grid-cols-2 gap-2 text-xs">
                                        <div><span class="text-white/30">Avg Views:</span> <span class="text-white/70" x-text="fmtNum(commerceData.commerce?.avg_views || 0)"></span></div>
                                        <div><span class="text-white/30">Avg Likes:</span> <span class="text-white/70" x-text="fmtNum(commerceData.commerce?.avg_likes || 0)"></span></div>
                                        <div><span class="text-white/30">Avg Shares:</span> <span class="text-white/70" x-text="fmtNum(commerceData.commerce?.avg_shares || 0)"></span></div>
                                        <div><span class="text-white/30">Engagement:</span> <span class="text-white/70" x-text="(commerceData.commerce?.avg_engagement || 0).toFixed(1) + '%'"></span></div>
                                    </div>
                                </div>
                                <div class="bg-dark-700/50 rounded-lg p-4">
                                    <div class="flex items-center justify-between mb-2">
                                        <span class="text-xs text-green-400 font-bold">Organico</span>
                                        <span class="text-[10px] text-white/30" x-text="(commerceData.organic?.count || 0) + ' videos'"></span>
                                    </div>
                                    <div class="grid grid-cols-2 gap-2 text-xs">
                                        <div><span class="text-white/30">Avg Views:</span> <span class="text-white/70" x-text="fmtNum(commerceData.organic?.avg_views || 0)"></span></div>
                                        <div><span class="text-white/30">Avg Likes:</span> <span class="text-white/70" x-text="fmtNum(commerceData.organic?.avg_likes || 0)"></span></div>
                                        <div><span class="text-white/30">Avg Shares:</span> <span class="text-white/70" x-text="fmtNum(commerceData.organic?.avg_shares || 0)"></span></div>
                                        <div><span class="text-white/30">Engagement:</span> <span class="text-white/70" x-text="(commerceData.organic?.avg_engagement || 0).toFixed(1) + '%'"></span></div>
                                    </div>
                                </div>
                            </div>
                            <div x-show="commerceData.comparison?.views_diff_pct !== undefined" class="bg-dark-700/50 rounded-lg p-3 text-center text-xs">
                                <span x-text="commerceData.comparison?.commerce_performs_better ? 'Commerce performa ' + Math.abs(commerceData.comparison?.views_diff_pct || 0).toFixed(0) + '% melhor em views' : 'Organico performa ' + Math.abs(commerceData.comparison?.views_diff_pct || 0).toFixed(0) + '% melhor em views'"
                                      :class="commerceData.comparison?.commerce_performs_better ? 'text-cyan-400' : 'text-green-400'"></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- ═══════════════ COMPARE MODAL (enriched) ═══════════════ -->
    <div x-show="showCompare" x-transition.opacity class="fixed inset-0 z-50 flex items-center justify-center p-4" style="background: rgba(0,0,0,0.7); backdrop-filter: blur(8px);">
        <div @click.outside="showCompare = false" class="glass-card rounded-2xl p-6 w-full max-w-6xl max-h-[90vh] overflow-y-auto">
            <div class="flex items-center justify-between mb-6">
                <h3 class="text-lg font-bold text-white/90 flex items-center gap-2">
                    <i data-lucide="git-compare" class="w-5 h-5 text-brand-300"></i> Comparacao de Contas
                </h3>
                <button @click="showCompare = false" class="text-white/40 hover:text-white transition">
                    <i data-lucide="x" class="w-5 h-5"></i>
                </button>
            </div>

            <!-- Compare Charts: 3x2 grid -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div class="bg-dark-800/50 rounded-xl p-4">
                    <h5 class="text-xs font-bold text-white/50 mb-2">Vendas</h5>
                    <canvas id="compareSoldChart" height="150"></canvas>
                </div>
                <div class="bg-dark-800/50 rounded-xl p-4">
                    <h5 class="text-xs font-bold text-white/50 mb-2">Revenue</h5>
                    <canvas id="compareRevenueChart" height="150"></canvas>
                </div>
                <div class="bg-dark-800/50 rounded-xl p-4">
                    <h5 class="text-xs font-bold text-white/50 mb-2">Views</h5>
                    <canvas id="compareViewsChart" height="150"></canvas>
                </div>
                <div class="bg-dark-800/50 rounded-xl p-4">
                    <h5 class="text-xs font-bold text-white/50 mb-2">Followers</h5>
                    <canvas id="compareFollowersChart" height="150"></canvas>
                </div>
                <div class="bg-dark-800/50 rounded-xl p-4">
                    <h5 class="text-xs font-bold text-white/50 mb-2">Engagement Rate</h5>
                    <canvas id="compareEngagementChart" height="150"></canvas>
                </div>
                <div class="bg-dark-800/50 rounded-xl p-4">
                    <h5 class="text-xs font-bold text-white/50 mb-2">Hook Strength</h5>
                    <canvas id="compareHookChart" height="150"></canvas>
                </div>
            </div>

            <!-- Compare Table (enriched with ranking) -->
            <div class="overflow-x-auto">
                <table class="w-full text-xs">
                    <thead>
                        <tr class="text-white/40 border-b border-white/10">
                            <th class="text-left py-2 px-3">#</th>
                            <th class="text-left py-2 px-3">Conta</th>
                            <th class="text-right py-2 px-3">Vendas</th>
                            <th class="text-right py-2 px-3">Revenue</th>
                            <th class="text-right py-2 px-3">Views</th>
                            <th class="text-right py-2 px-3">Followers</th>
                            <th class="text-right py-2 px-3">Engagement</th>
                            <th class="text-right py-2 px-3">Hook</th>
                            <th class="text-right py-2 px-3">Commerce</th>
                            <th class="text-right py-2 px-3">Produtos</th>
                            <th class="text-right py-2 px-3">Rating</th>
                        </tr>
                    </thead>
                    <tbody>
                        <template x-for="(acc, idx) in (compareData.accounts || []).sort((a,b) => b.total_sold - a.total_sold)" :key="acc.id">
                            <tr class="border-b border-white/5 hover:bg-white/5">
                                <td class="py-2 px-3">
                                    <span class="inline-flex items-center justify-center w-5 h-5 rounded-full text-[10px] font-bold"
                                          :class="idx === 0 ? 'bg-yellow-500/30 text-yellow-400' : idx === 1 ? 'bg-gray-400/20 text-gray-300' : idx === 2 ? 'bg-orange-500/20 text-orange-400' : 'bg-white/5 text-white/30'"
                                          x-text="'#' + (idx + 1)"></span>
                                </td>
                                <td class="py-2 px-3 text-white/80 font-medium" x-text="'@' + acc.username"></td>
                                <td class="py-2 px-3 text-right text-green-400" x-text="fmtNum(acc.total_sold)"></td>
                                <td class="py-2 px-3 text-right text-yellow-400" x-text="'$' + fmtNum(acc.estimated_revenue)"></td>
                                <td class="py-2 px-3 text-right text-blue-400" x-text="fmtNum(acc.total_views)"></td>
                                <td class="py-2 px-3 text-right text-purple-400" x-text="fmtNum(acc.followers)"></td>
                                <td class="py-2 px-3 text-right"
                                    :class="acc.avg_engagement_rate >= 5 ? 'text-green-400' : acc.avg_engagement_rate >= 2 ? 'text-yellow-400' : 'text-red-400'"
                                    x-text="(acc.avg_engagement_rate || 0).toFixed(1) + '%'"></td>
                                <td class="py-2 px-3 text-right text-orange-400" x-text="(acc.avg_hook_strength || 0).toFixed(0)"></td>
                                <td class="py-2 px-3 text-right text-cyan-400" x-text="(acc.commerce_ratio || 0).toFixed(1) + '%'"></td>
                                <td class="py-2 px-3 text-right text-white/60" x-text="acc.total_products"></td>
                                <td class="py-2 px-3 text-right text-white/60" x-text="acc.shop_rating ? acc.shop_rating.toFixed(1) : '-'"></td>
                            </tr>
                        </template>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- TOAST -->
    <div x-show="toast" x-transition.opacity class="fixed bottom-6 right-6 z-50 px-5 py-3 rounded-xl text-sm font-medium shadow-2xl"
         :class="toastType === 'error' ? 'bg-red-600 text-white' : 'bg-green-600 text-white'"
         x-text="toast" @click="toast = ''"></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>
<script>
function shopDashboard() {
    return {
        accounts: [],
        summary: {},
        loading: true,
        newUsername: '',
        adding: false,
        showBulk: false,
        bulkText: '',
        addingBulk: false,
        refreshingAll: false,
        refreshingId: null,
        selectedIds: [],
        // Detail modal
        detailAccount: null,
        detailGrowth: {},
        detailProducts: [],
        activeTab: 'Overview',
        growthDays: 30,
        // Videos tab
        viralVideos: [],
        filteredVideos: [],
        videoSort: 'viral_score',
        videoFilter: 'all',
        expandedVideo: -1,
        // Content Strategy tab
        contentData: {},
        loadingContent: false,
        // AI tab
        aiData: {},
        revenueData: {},
        commerceData: {},
        loadingAI: false,
        // Product sort
        productSort: 'sold_count',
        // Phase 2: transcripts, product-video map, insights, ideas
        loadingTranscripts: false,
        productVideoMap: null,
        loadingProductMap: false,
        insightsData: null,
        loadingInsights: false,
        videoIdeasData: null,
        loadingIdeas: false,
        // Compare modal
        showCompare: false,
        compareData: {},
        // Toast
        toast: '',
        toastType: 'success',
        // Charts
        growthChart: null,
        compareCharts: {},
        formatChart: null,
        pollTimer: null,

        async init() {
            await this.loadData();
            this.loading = false;
            this.pollTimer = setInterval(() => this.loadData(true), 15000);
            this.$watch('detailAccount', () => { if (this.detailAccount) this.$nextTick(() => lucide.createIcons()); });
        },

        async loadData(silent = false) {
            try {
                const res = await fetch('/api/shop-accounts/dashboard');
                const data = await res.json();
                this.summary = data;
                this.accounts = data.accounts || [];
                if (!silent) this.$nextTick(() => lucide.createIcons());
            } catch (e) { if (!silent) console.error(e); }
        },

        async addAccount() {
            if (!this.newUsername.trim() || this.adding) return;
            this.adding = true;
            try {
                const res = await fetch('/api/shop-accounts', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({username: this.newUsername}) });
                const data = await res.json();
                if (data.status === 'exists') this.showToast('Conta ja monitorada', 'error');
                else if (data.status === 'added') { this.showToast('Conta adicionada!'); this.newUsername = ''; await this.loadData(); }
                else this.showToast(data.message || 'Erro ao adicionar', 'error');
            } catch (e) { this.showToast('Erro de conexao', 'error'); }
            this.adding = false;
        },

        async addBulk() {
            if (!this.bulkText.trim() || this.addingBulk) return;
            this.addingBulk = true;
            try {
                const res = await fetch('/api/shop-accounts/bulk', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({usernames: this.bulkText}) });
                const data = await res.json();
                this.showToast(`${data.added?.length || 0} adicionadas, ${data.skipped?.length || 0} ja existiam`);
                this.bulkText = ''; this.showBulk = false; await this.loadData();
            } catch (e) { this.showToast('Erro na importacao', 'error'); }
            this.addingBulk = false;
        },

        async refreshOne(id) {
            this.refreshingId = id;
            try { await fetch(`/api/shop-accounts/${id}/refresh`, {method: 'POST'}); await this.loadData(); this.showToast('Conta atualizada!'); }
            catch (e) { this.showToast('Erro ao atualizar', 'error'); }
            this.refreshingId = null;
        },

        async refreshAll() {
            this.refreshingAll = true;
            try { await fetch('/api/shop-accounts/refresh-all', {method: 'POST'}); await this.loadData(); this.showToast('Todas as contas atualizadas!'); }
            catch (e) { this.showToast('Erro ao atualizar', 'error'); }
            this.refreshingAll = false;
        },

        async removeAccount(id) {
            if (!confirm('Remover esta conta?')) return;
            try { await fetch(`/api/shop-accounts/${id}`, {method: 'DELETE'}); this.selectedIds = this.selectedIds.filter(i => i !== id); await this.loadData(); this.showToast('Conta removida'); }
            catch (e) { this.showToast('Erro ao remover', 'error'); }
        },

        async openDetail(id) {
            this.activeTab = 'Overview';
            this.viralVideos = [];
            this.filteredVideos = [];
            this.contentData = {};
            this.aiData = {};
            this.revenueData = {};
            this.commerceData = {};
            this.expandedVideo = -1;
            this.productVideoMap = null;
            this.insightsData = null;
            this.videoIdeasData = null;

            try {
                const [accRes, growthRes, prodRes] = await Promise.all([
                    fetch(`/api/shop-accounts/${id}`),
                    fetch(`/api/shop-accounts/${id}/growth?days=30`),
                    fetch(`/api/shop-accounts/${id}/products?limit=20`)
                ]);
                this.detailAccount = await accRes.json();
                this.detailGrowth = await growthRes.json();
                const prodData = await prodRes.json();
                this.detailProducts = prodData.products || [];
                this.growthDays = 30;

                this.$nextTick(() => { lucide.createIcons(); });
            } catch (e) { this.showToast('Erro ao carregar detalhes', 'error'); }
        },

        async loadGrowth(days) {
            if (!this.detailAccount) return;
            this.growthDays = days;
            try {
                const res = await fetch(`/api/shop-accounts/${this.detailAccount.id}/growth?days=${days}`);
                this.detailGrowth = await res.json();
                this.$nextTick(() => this.renderGrowthChart());
            } catch (e) { console.error(e); }
        },

        async loadViralVideos() {
            if (!this.detailAccount || this.viralVideos.length > 0) return;
            try {
                const res = await fetch(`/api/shop-accounts/${this.detailAccount.id}/viral-videos`);
                const data = await res.json();
                this.viralVideos = data.videos || [];
                this.filterVideos();
            } catch (e) { console.error(e); }
        },

        async loadContentAnalysis() {
            if (!this.detailAccount || this.contentData.cadence) return;
            this.loadingContent = true;
            try {
                const res = await fetch(`/api/shop-accounts/${this.detailAccount.id}/content-analysis`);
                this.contentData = await res.json();
                this.$nextTick(() => {
                    this.renderFormatChart();
                    this.renderHeatmapChart();
                });
            } catch (e) { console.error(e); }
            this.loadingContent = false;
        },

        async loadAIReport(force = false) {
            if (!this.detailAccount) return;
            this.loadingAI = true;
            try {
                const [aiRes, revRes, comRes] = await Promise.all([
                    fetch(`/api/shop-accounts/${this.detailAccount.id}/ai-report?force=${force}`),
                    fetch(`/api/shop-accounts/${this.detailAccount.id}/revenue-detail`),
                    fetch(`/api/shop-accounts/${this.detailAccount.id}/commerce-analysis`)
                ]);
                this.aiData = await aiRes.json();
                this.revenueData = await revRes.json();
                this.commerceData = await comRes.json();
            } catch (e) { console.error(e); }
            this.loadingAI = false;
        },

        async loadProducts() {
            if (!this.detailAccount) return;
            try {
                const res = await fetch(`/api/shop-accounts/${this.detailAccount.id}/product-trends?days=30`);
                const data = await res.json();
                this.detailProducts = data.products || [];
            } catch (e) { console.error(e); }
        },

        async loadTranscripts() {
            if (!this.detailAccount || this.loadingTranscripts) return;
            this.loadingTranscripts = true;
            try {
                const res = await fetch(`/api/shop-accounts/${this.detailAccount.id}/transcripts?max_videos=10`);
                const data = await res.json();
                // Update viral videos with transcripts
                if (data.videos) {
                    data.videos.forEach(tv => {
                        const match = this.viralVideos.find(v => v.id === tv.id || v.url === tv.url);
                        if (match && tv.transcript) match.transcript = tv.transcript;
                    });
                    this.filterVideos();
                }
                this.showToast(`${data.transcribed || 0} videos transcritos!`);
            } catch (e) { this.showToast('Erro ao transcrever', 'error'); }
            this.loadingTranscripts = false;
        },

        async loadProductVideoMap() {
            if (!this.detailAccount || this.productVideoMap || this.loadingProductMap) return;
            this.loadingProductMap = true;
            try {
                const res = await fetch(`/api/shop-accounts/${this.detailAccount.id}/product-video-map`);
                this.productVideoMap = await res.json();
            } catch (e) { console.error(e); }
            this.loadingProductMap = false;
        },

        async loadInsights(force = false) {
            if (!this.detailAccount) return;
            if (this.insightsData && !force) return;
            this.loadingInsights = true;
            try {
                const res = await fetch(`/api/shop-accounts/${this.detailAccount.id}/insights?force=${force}`);
                this.insightsData = await res.json();
            } catch (e) { this.showToast('Erro ao gerar insights', 'error'); }
            this.loadingInsights = false;
        },

        async loadVideoIdeas(force = false) {
            if (!this.detailAccount) return;
            if (this.videoIdeasData && !force) return;
            this.loadingIdeas = true;
            try {
                const res = await fetch(`/api/shop-accounts/${this.detailAccount.id}/video-ideas?force=${force}`);
                this.videoIdeasData = await res.json();
            } catch (e) { this.showToast('Erro ao gerar ideias', 'error'); }
            this.loadingIdeas = false;
        },

        sortVideos() {
            const key = this.videoSort;
            this.filteredVideos.sort((a, b) => (b[key] || 0) - (a[key] || 0));
        },

        filterVideos() {
            let vids = [...this.viralVideos];
            const f = this.videoFilter;
            if (f === 'commerce') vids = vids.filter(v => v.has_commerce);
            else if (f === 'organic') vids = vids.filter(v => !v.has_commerce);
            else if (f === 'high_eng') vids = vids.filter(v => (v.engagement_rate || 0) >= 5);
            else if (f === 'viral') vids = vids.filter(v => (v.views || 0) >= 100000);
            else if (f === 'short') vids = vids.filter(v => (v.duration || 0) <= 15);
            else if (f === 'medium') vids = vids.filter(v => (v.duration || 0) > 15 && (v.duration || 0) <= 60);
            else if (f === 'long') vids = vids.filter(v => (v.duration || 0) > 60);
            else if (f === 'with_transcript') vids = vids.filter(v => v.transcript);
            this.filteredVideos = vids;
            this.sortVideos();
        },

        // Watch tab changes to lazy-load data
        watchTab() {
            if (this.activeTab === 'Growth') this.$nextTick(() => this.renderGrowthChart());
            if (this.activeTab === 'Videos') this.loadViralVideos();
            if (this.activeTab === 'Products') this.loadProductVideoMap();
            if (this.activeTab === 'Content Strategy') this.loadContentAnalysis();
            if (this.activeTab === 'AI Intelligence') { this.loadAIReport(); this.loadInsights(); this.loadVideoIdeas(); }
        },

        renderGrowthChart() {
            const ctx = document.getElementById('growthChart');
            if (!ctx) return;
            if (this.growthChart) this.growthChart.destroy();

            const snaps = this.detailGrowth.snapshots || [];
            if (snaps.length < 2) return;

            const labels = snaps.map(s => {
                const d = new Date(s.captured_at);
                return d.toLocaleDateString('pt-BR', {day: '2-digit', month: '2-digit'});
            });

            this.growthChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels,
                    datasets: [
                        { label: 'Vendas', data: snaps.map(s => s.total_sold), borderColor: '#4ade80', backgroundColor: 'rgba(74,222,128,0.1)', tension: 0.3, fill: true },
                        { label: 'Revenue ($)', data: snaps.map(s => s.estimated_revenue), borderColor: '#facc15', backgroundColor: 'rgba(250,204,21,0.1)', tension: 0.3, fill: true, yAxisID: 'y1' },
                        { label: 'Views', data: snaps.map(s => s.total_views), borderColor: '#60a5fa', backgroundColor: 'rgba(96,165,250,0.1)', tension: 0.3, fill: true, hidden: true },
                        { label: 'Followers', data: snaps.map(s => s.followers), borderColor: '#c084fc', backgroundColor: 'rgba(192,132,252,0.1)', tension: 0.3, fill: true, hidden: true },
                        { label: 'Engagement %', data: snaps.map(s => s.avg_engagement_rate || 0), borderColor: '#fb923c', backgroundColor: 'rgba(251,146,60,0.1)', tension: 0.3, fill: true, hidden: true },
                        { label: 'Hook Strength', data: snaps.map(s => s.avg_hook_strength || 0), borderColor: '#f472b6', backgroundColor: 'rgba(244,114,182,0.1)', tension: 0.3, fill: true, hidden: true },
                        { label: 'Commerce Videos', data: snaps.map(s => s.commerce_video_count || 0), borderColor: '#22d3ee', backgroundColor: 'rgba(34,211,238,0.1)', tension: 0.3, fill: true, hidden: true },
                    ]
                },
                options: {
                    responsive: true,
                    interaction: { mode: 'index', intersect: false },
                    plugins: { legend: { labels: { color: 'rgba(255,255,255,0.6)', font: { size: 10 } } } },
                    scales: {
                        x: { ticks: { color: 'rgba(255,255,255,0.3)', font: { size: 9 } }, grid: { color: 'rgba(255,255,255,0.05)' } },
                        y: { ticks: { color: 'rgba(255,255,255,0.3)', font: { size: 9 } }, grid: { color: 'rgba(255,255,255,0.05)' } },
                        y1: { position: 'right', ticks: { color: 'rgba(250,204,21,0.5)', font: { size: 9 } }, grid: { display: false } }
                    }
                }
            });
        },

        renderFormatChart() {
            const ctx = document.getElementById('formatChart');
            if (!ctx) return;
            if (this.formatChart) this.formatChart.destroy();

            const fmt = this.contentData.formats?.formats || {};
            this.formatChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['Curto (<=15s)', 'Medio (16-60s)', 'Longo (>60s)'],
                    datasets: [{
                        data: [fmt.short || 0, fmt.medium || 0, fmt.long || 0],
                        backgroundColor: ['#4ade80', '#60a5fa', '#c084fc'],
                        borderWidth: 0,
                    }]
                },
                options: {
                    responsive: true,
                    cutout: '60%',
                    plugins: { legend: { labels: { color: 'rgba(255,255,255,0.6)', font: { size: 10 } } } },
                }
            });
        },

        renderHeatmapChart() {
            const ctx = document.getElementById('heatmapChart');
            if (!ctx) return;

            const heatmap = this.contentData.cadence?.cadence_heatmap || {};
            const days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
            const hours = Array.from({length: 24}, (_, i) => i);
            const data = [];
            let maxVal = 0;

            days.forEach((day, y) => {
                hours.forEach(hour => {
                    const val = (heatmap[day] && heatmap[day][hour]) || 0;
                    if (val > maxVal) maxVal = val;
                    data.push({x: hour, y, v: val});
                });
            });

            // Use a simple bar chart as heatmap proxy
            const dayLabels = ['Seg','Ter','Qua','Qui','Sex','Sab','Dom'];
            const datasets = dayLabels.map((label, dayIdx) => {
                const hourData = hours.map(h => {
                    const day = days[dayIdx];
                    return (heatmap[day] && heatmap[day][h]) || 0;
                });
                const colors = ['#4ade80','#60a5fa','#c084fc','#facc15','#f87171','#2dd4bf','#fb923c'];
                return {
                    label,
                    data: hourData,
                    backgroundColor: colors[dayIdx] + '60',
                    borderColor: colors[dayIdx],
                    borderWidth: 1,
                };
            });

            new Chart(ctx, {
                type: 'bar',
                data: { labels: hours.map(h => h + 'h'), datasets },
                options: {
                    responsive: true,
                    scales: {
                        x: { stacked: true, ticks: { color: 'rgba(255,255,255,0.3)', font: { size: 8 } }, grid: { display: false } },
                        y: { stacked: true, ticks: { color: 'rgba(255,255,255,0.3)', font: { size: 8 } }, grid: { color: 'rgba(255,255,255,0.05)' } }
                    },
                    plugins: { legend: { labels: { color: 'rgba(255,255,255,0.5)', font: { size: 9 } } } }
                }
            });
        },

        async compareSelected() {
            if (this.selectedIds.length < 2) return;
            try {
                const res = await fetch('/api/shop-accounts/compare', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({account_ids: this.selectedIds}) });
                this.compareData = await res.json();
                this.showCompare = true;
                this.$nextTick(() => { this.renderCompareCharts(); lucide.createIcons(); });
            } catch (e) { this.showToast('Erro ao comparar', 'error'); }
        },

        renderCompareCharts() {
            const cd = this.compareData.chart_data || {};
            const colors = ['#4ade80', '#60a5fa', '#c084fc', '#facc15', '#f87171', '#2dd4bf', '#fb923c'];
            const usernames = Object.keys(cd);

            const metrics = [
                {id: 'compareSoldChart', key: 'sold'},
                {id: 'compareRevenueChart', key: 'revenue'},
                {id: 'compareViewsChart', key: 'views'},
                {id: 'compareFollowersChart', key: 'followers'},
                {id: 'compareEngagementChart', key: 'engagement'},
                {id: 'compareHookChart', key: 'hook_strength'},
            ];

            metrics.forEach(m => {
                const ctx = document.getElementById(m.id);
                if (!ctx) return;
                if (this.compareCharts[m.id]) this.compareCharts[m.id].destroy();

                const datasets = usernames.map((u, i) => ({
                    label: '@' + u,
                    data: cd[u][m.key] || [],
                    borderColor: colors[i % colors.length],
                    backgroundColor: 'transparent',
                    tension: 0.3,
                    borderWidth: 2,
                }));

                const maxLabels = Math.max(...usernames.map(u => (cd[u].labels || []).length));
                const labels = usernames.find(u => (cd[u].labels || []).length === maxLabels) ? cd[usernames.find(u => (cd[u].labels || []).length === maxLabels)].labels : [];

                this.compareCharts[m.id] = new Chart(ctx, {
                    type: 'line',
                    data: { labels, datasets },
                    options: {
                        responsive: true,
                        plugins: { legend: { labels: { color: 'rgba(255,255,255,0.6)', font: { size: 9 } } } },
                        scales: {
                            x: { ticks: { color: 'rgba(255,255,255,0.3)', font: { size: 8 } }, grid: { color: 'rgba(255,255,255,0.05)' } },
                            y: { ticks: { color: 'rgba(255,255,255,0.3)', font: { size: 8 } }, grid: { color: 'rgba(255,255,255,0.05)' } }
                        }
                    }
                });
            });
        },

        fmtNum(n) {
            if (n === undefined || n === null) return '0';
            n = Number(n);
            if (n >= 1e9) return (n / 1e9).toFixed(1) + 'B';
            if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M';
            if (n >= 1e3) return (n / 1e3).toFixed(1) + 'K';
            return Math.round(n).toLocaleString();
        },

        timeAgo(iso) {
            if (!iso) return '';
            const diff = (Date.now() - new Date(iso).getTime()) / 1000;
            if (diff < 60) return 'agora';
            if (diff < 3600) return Math.floor(diff / 60) + 'min atras';
            if (diff < 86400) return Math.floor(diff / 3600) + 'h atras';
            return Math.floor(diff / 86400) + 'd atras';
        },

        showToast(msg, type = 'success') {
            this.toast = msg;
            this.toastType = type;
            setTimeout(() => this.toast = '', 3000);
        },

        destroy() {
            if (this.pollTimer) clearInterval(this.pollTimer);
            if (this.growthChart) this.growthChart.destroy();
            if (this.formatChart) this.formatChart.destroy();
            Object.values(this.compareCharts).forEach(c => c.destroy());
        }
    };
}
</script>
{% endblock %}
