{% extends "base.html" %}
{% block title %}Sons e Audios - Viral Social Pro{% endblock %}
{% block nav_sounds %}active{% endblock %}
{% block page_title %}Sons & Audios{% endblock %}
{% block page_subtitle %}Descubra sons virais e oportunidades de audio{% endblock %}

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

    <!-- Header Stats -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 mb-6 animate-fade-up">
        <div class="glass-card rounded-2xl p-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl gradient-brand flex items-center justify-center flex-shrink-0">
                    <i data-lucide="music" class="w-5 h-5 text-white"></i>
                </div>
                <div>
                    <p class="stat-number text-white" x-text="trendingSounds.length"></p>
                    <p class="text-xs text-white/40 mt-0.5">Em Alta</p>
                </div>
            </div>
        </div>
        <div class="glass-card rounded-2xl p-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl gradient-success flex items-center justify-center flex-shrink-0">
                    <i data-lucide="sparkles" class="w-5 h-5 text-white"></i>
                </div>
                <div>
                    <p class="stat-number text-white" x-text="emergingSounds.length"></p>
                    <p class="text-xs text-white/40 mt-0.5">Emergentes</p>
                </div>
            </div>
        </div>
        <div class="glass-card rounded-2xl p-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl gradient-ocean flex items-center justify-center flex-shrink-0">
                    <i data-lucide="trending-up" class="w-5 h-5 text-white"></i>
                </div>
                <div>
                    <p class="stat-number text-white" x-text="topGrowth"></p>
                    <p class="text-xs text-white/40 mt-0.5">Maior Crescimento</p>
                </div>
            </div>
        </div>
        <div class="glass-card rounded-2xl p-4">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl gradient-fire flex items-center justify-center flex-shrink-0">
                    <i data-lucide="search" class="w-5 h-5 text-white"></i>
                </div>
                <div>
                    <p class="stat-number text-white" x-text="searchResults.length"></p>
                    <p class="text-xs text-white/40 mt-0.5">Resultados</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabs -->
    <div class="flex items-center gap-2 mb-6 overflow-x-auto pb-1 animate-fade-up-delay">
        <button class="tab-btn" :class="activeTab === 'trending' && 'active'" @click="activeTab = 'trending'">
            <span class="flex items-center gap-2"><i data-lucide="flame" class="w-4 h-4"></i> Sons em Alta</span>
        </button>
        <button class="tab-btn" :class="activeTab === 'emerging' && 'active'" @click="activeTab = 'emerging'">
            <span class="flex items-center gap-2"><i data-lucide="sparkles" class="w-4 h-4"></i> Sons Emergentes</span>
        </button>
        <button class="tab-btn" :class="activeTab === 'search' && 'active'" @click="activeTab = 'search'">
            <span class="flex items-center gap-2"><i data-lucide="search" class="w-4 h-4"></i> Buscar Sons</span>
        </button>
    </div>

    <!-- ============================================ -->
    <!-- TAB: Sons em Alta                            -->
    <!-- ============================================ -->
    <div x-show="activeTab === 'trending'" x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 translate-y-2" x-transition:enter-end="opacity-100 translate-y-0">

        <!-- Loading -->
        <div x-show="loadingTrending" class="grid-cards">
            <template x-for="i in 6" :key="'skel-t-'+i">
                <div class="glass-card rounded-2xl p-5">
                    <div class="skeleton h-5 w-3/4 mb-3"></div>
                    <div class="skeleton h-4 w-1/2 mb-4"></div>
                    <div class="flex gap-3">
                        <div class="skeleton h-8 w-20"></div>
                        <div class="skeleton h-8 w-20"></div>
                    </div>
                </div>
            </template>
        </div>

        <!-- Empty State -->
        <div x-show="!loadingTrending && trendingSounds.length === 0" class="flex flex-col items-center justify-center py-20 text-center">
            <div class="w-20 h-20 rounded-2xl glass-light flex items-center justify-center mb-5">
                <i data-lucide="music-2" class="w-10 h-10 text-white/20"></i>
            </div>
            <h3 class="text-lg font-bold text-white/60 mb-2">Nenhum som em alta encontrado</h3>
            <p class="text-sm text-white/30 max-w-md">Os sons em alta aparecerao aqui assim que forem rastreados. Use a aba "Buscar Sons" para encontrar e rastrear novos sons.</p>
        </div>

        <!-- Sound Cards Grid -->
        <div x-show="!loadingTrending && trendingSounds.length > 0" class="grid-cards">
            <template x-for="sound in trendingSounds" :key="sound.id">
                <div class="glass-card rounded-2xl p-5 group">
                    <!-- Header -->
                    <div class="flex items-start justify-between mb-3">
                        <div class="flex-1 min-w-0 mr-3">
                            <h3 class="font-bold text-white/90 text-sm truncate" x-text="sound.title || 'Som sem titulo'"></h3>
                            <p class="text-xs text-white/40 mt-1 truncate" x-text="sound.author ? '@' + sound.author : 'Autor desconhecido'"></p>
                        </div>
                        <span class="flex-shrink-0" x-html="phaseBadge(sound.phase)"></span>
                    </div>

                    <!-- Stats -->
                    <div class="flex items-center gap-4 mb-4">
                        <div>
                            <p class="text-lg font-bold text-white" x-text="formatSoundNumber(sound.video_count)"></p>
                            <p class="text-[10px] text-white/30 uppercase tracking-wide">Videos</p>
                        </div>
                        <div class="h-8 w-px bg-white/5"></div>
                        <div>
                            <p class="text-lg font-bold" :class="(sound.growth_rate || 0) >= 0 ? 'text-accent-green' : 'text-accent-red'"
                               x-text="formatGrowth(sound.growth_rate)"></p>
                            <p class="text-[10px] text-white/30 uppercase tracking-wide">Crescimento</p>
                        </div>
                        <template x-if="sound.prev_video_count">
                            <div class="flex items-center gap-4">
                                <div class="h-8 w-px bg-white/5"></div>
                                <div>
                                    <p class="text-sm font-semibold text-white/50" x-text="formatSoundNumber(sound.prev_video_count)"></p>
                                    <p class="text-[10px] text-white/30 uppercase tracking-wide">Anterior</p>
                                </div>
                            </div>
                        </template>
                    </div>

                    <!-- Footer -->
                    <div class="flex items-center justify-between pt-3 border-t border-white/5">
                        <div class="flex items-center gap-2">
                            <span class="px-2 py-1 rounded-lg text-[10px] font-semibold uppercase tracking-wide"
                                  :class="sound.platform === 'tiktok' ? 'badge-tiktok' : 'badge-instagram'"
                                  x-text="platformLabel(sound.platform)"></span>
                            <span class="text-[10px] text-white/25" x-text="timeAgo(sound.tracked_at)"></span>
                        </div>
                        <a :href="sound.url" target="_blank" rel="noopener"
                           class="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-brand-300 hover:bg-brand-500/10 transition opacity-0 group-hover:opacity-100">
                            <i data-lucide="external-link" class="w-3 h-3"></i> Abrir
                        </a>
                    </div>
                </div>
            </template>
        </div>
    </div>

    <!-- ============================================ -->
    <!-- TAB: Sons Emergentes                         -->
    <!-- ============================================ -->
    <div x-show="activeTab === 'emerging'" x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 translate-y-2" x-transition:enter-end="opacity-100 translate-y-0">

        <!-- Info Banner -->
        <div class="glass-card rounded-2xl p-4 mb-5 border-l-4 border-cyan-500/50">
            <div class="flex items-start gap-3">
                <div class="w-8 h-8 rounded-lg bg-cyan-500/10 flex items-center justify-center flex-shrink-0 mt-0.5">
                    <i data-lucide="lightbulb" class="w-4 h-4 text-cyan-400"></i>
                </div>
                <div>
                    <h4 class="text-sm font-bold text-white/80 mb-1">Oportunidade de Ouro</h4>
                    <p class="text-xs text-white/40 leading-relaxed">Sons emergentes estao no inicio da curva de crescimento. Usar esses sons agora aumenta suas chances de viralizar antes que atinjam o pico. Fique de olho nos que tem maior taxa de crescimento!</p>
                </div>
            </div>
        </div>

        <!-- Loading -->
        <div x-show="loadingEmerging" class="grid-cards">
            <template x-for="i in 6" :key="'skel-e-'+i">
                <div class="glass-card rounded-2xl p-5">
                    <div class="skeleton h-5 w-3/4 mb-3"></div>
                    <div class="skeleton h-4 w-1/2 mb-4"></div>
                    <div class="flex gap-3">
                        <div class="skeleton h-8 w-20"></div>
                        <div class="skeleton h-8 w-20"></div>
                    </div>
                </div>
            </template>
        </div>

        <!-- Empty State -->
        <div x-show="!loadingEmerging && emergingSounds.length === 0" class="flex flex-col items-center justify-center py-20 text-center">
            <div class="w-20 h-20 rounded-2xl glass-light flex items-center justify-center mb-5">
                <i data-lucide="sparkles" class="w-10 h-10 text-white/20"></i>
            </div>
            <h3 class="text-lg font-bold text-white/60 mb-2">Nenhum som emergente no momento</h3>
            <p class="text-sm text-white/30 max-w-md">Quando novos sons comecarem a ganhar tracao, eles aparecerao aqui. Continue rastreando sons para identificar oportunidades.</p>
        </div>

        <!-- Emerging Sound Cards Grid -->
        <div x-show="!loadingEmerging && emergingSounds.length > 0" class="grid-cards">
            <template x-for="sound in emergingSounds" :key="sound.id">
                <div class="glass-card rounded-2xl p-5 group relative overflow-hidden">
                    <!-- Glow accent for emerging -->
                    <div class="absolute top-0 right-0 w-32 h-32 bg-cyan-500/5 rounded-full blur-2xl -translate-y-1/2 translate-x-1/2 pointer-events-none"></div>

                    <!-- Header -->
                    <div class="flex items-start justify-between mb-3 relative">
                        <div class="flex-1 min-w-0 mr-3">
                            <div class="flex items-center gap-2 mb-1">
                                <span class="w-2 h-2 rounded-full bg-cyan-400 animate-pulse flex-shrink-0"></span>
                                <h3 class="font-bold text-white/90 text-sm truncate" x-text="sound.title || 'Som sem titulo'"></h3>
                            </div>
                            <p class="text-xs text-white/40 truncate pl-4" x-text="sound.author ? '@' + sound.author : 'Autor desconhecido'"></p>
                        </div>
                        <span class="flex-shrink-0" x-html="phaseBadge(sound.phase)"></span>
                    </div>

                    <!-- Stats -->
                    <div class="flex items-center gap-4 mb-4 relative">
                        <div>
                            <p class="text-lg font-bold text-white" x-text="formatSoundNumber(sound.video_count)"></p>
                            <p class="text-[10px] text-white/30 uppercase tracking-wide">Videos</p>
                        </div>
                        <div class="h-8 w-px bg-white/5"></div>
                        <div>
                            <p class="text-lg font-bold text-accent-green" x-text="formatGrowth(sound.growth_rate)"></p>
                            <p class="text-[10px] text-white/30 uppercase tracking-wide">Crescimento</p>
                        </div>
                        <template x-if="sound.prev_video_count">
                            <div class="flex items-center gap-4">
                                <div class="h-8 w-px bg-white/5"></div>
                                <div>
                                    <p class="text-sm font-semibold text-white/50" x-text="formatSoundNumber(sound.prev_video_count)"></p>
                                    <p class="text-[10px] text-white/30 uppercase tracking-wide">Anterior</p>
                                </div>
                            </div>
                        </template>
                    </div>

                    <!-- Footer -->
                    <div class="flex items-center justify-between pt-3 border-t border-white/5 relative">
                        <div class="flex items-center gap-2">
                            <span class="px-2 py-1 rounded-lg text-[10px] font-semibold uppercase tracking-wide"
                                  :class="sound.platform === 'tiktok' ? 'badge-tiktok' : 'badge-instagram'"
                                  x-text="platformLabel(sound.platform)"></span>
                            <span class="text-[10px] text-white/25" x-text="timeAgo(sound.tracked_at)"></span>
                        </div>
                        <a :href="sound.url" target="_blank" rel="noopener"
                           class="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-cyan-300 hover:bg-cyan-500/10 transition opacity-0 group-hover:opacity-100">
                            <i data-lucide="external-link" class="w-3 h-3"></i> Usar som
                        </a>
                    </div>
                </div>
            </template>
        </div>
    </div>

    <!-- ============================================ -->
    <!-- TAB: Buscar Sons                             -->
    <!-- ============================================ -->
    <div x-show="activeTab === 'search'" x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 translate-y-2" x-transition:enter-end="opacity-100 translate-y-0">

        <!-- Search Form -->
        <div class="glass-card rounded-2xl p-5 mb-6">
            <h3 class="text-sm font-bold text-white/80 mb-4 flex items-center gap-2">
                <i data-lucide="search" class="w-4 h-4 text-brand-400"></i> Buscar Sons por Palavra-chave
            </h3>
            <div class="flex flex-col sm:flex-row gap-3">
                <div class="flex-1 relative">
                    <i data-lucide="music" class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-white/20"></i>
                    <input type="text" x-model="searchKeyword" @keyup.enter="searchSounds()"
                           placeholder="Ex: funk, beat viral, som original, lo-fi..."
                           class="w-full bg-dark-800/50 border border-white/5 rounded-xl pl-10 pr-4 py-3 text-sm text-white placeholder:text-white/25 outline-none focus:border-brand-500/50 transition">
                </div>
                <select x-model="searchPlatform"
                        class="bg-dark-800/50 border border-white/5 rounded-xl px-4 py-3 text-sm text-white/80 outline-none focus:border-brand-500/50 transition appearance-none cursor-pointer min-w-[160px]">
                    <option value="tiktok">TikTok</option>
                    <option value="instagram">Instagram</option>
                </select>
                <button @click="searchSounds()" :disabled="loadingSearch || !searchKeyword.trim()"
                        class="flex items-center justify-center gap-2 px-6 py-3 rounded-xl gradient-brand text-white font-semibold text-sm hover:opacity-90 transition disabled:opacity-40 disabled:cursor-not-allowed min-w-[120px]">
                    <template x-if="loadingSearch">
                        <svg class="animate-spin w-4 h-4" viewBox="0 0 24 24" fill="none">
                            <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="!loadingSearch">
                        <i data-lucide="search" class="w-4 h-4"></i>
                    </template>
                    <span x-text="loadingSearch ? 'Buscando...' : 'Buscar'"></span>
                </button>
            </div>
        </div>

        <!-- Loading -->
        <div x-show="loadingSearch" class="grid-cards">
            <template x-for="i in 4" :key="'skel-s-'+i">
                <div class="glass-card rounded-2xl p-5">
                    <div class="skeleton h-5 w-3/4 mb-3"></div>
                    <div class="skeleton h-4 w-1/2 mb-4"></div>
                    <div class="flex gap-3">
                        <div class="skeleton h-8 w-20"></div>
                        <div class="skeleton h-8 w-20"></div>
                    </div>
                </div>
            </template>
        </div>

        <!-- Empty State (before search) -->
        <div x-show="!loadingSearch && searchResults.length === 0 && !searchPerformed" class="flex flex-col items-center justify-center py-16 text-center">
            <div class="w-20 h-20 rounded-2xl glass-light flex items-center justify-center mb-5">
                <i data-lucide="disc" class="w-10 h-10 text-white/20"></i>
            </div>
            <h3 class="text-lg font-bold text-white/60 mb-2">Busque sons por palavra-chave</h3>
            <p class="text-sm text-white/30 max-w-md">Digite uma palavra-chave para encontrar sons populares no TikTok ou Instagram. Os sons encontrados serao automaticamente rastreados.</p>
        </div>

        <!-- Empty State (no results) -->
        <div x-show="!loadingSearch && searchResults.length === 0 && searchPerformed" class="flex flex-col items-center justify-center py-16 text-center">
            <div class="w-20 h-20 rounded-2xl glass-light flex items-center justify-center mb-5">
                <i data-lucide="search-x" class="w-10 h-10 text-white/20"></i>
            </div>
            <h3 class="text-lg font-bold text-white/60 mb-2">Nenhum som encontrado</h3>
            <p class="text-sm text-white/30 max-w-md">Tente outras palavras-chave ou mude a plataforma de busca.</p>
        </div>

        <!-- Search Results Grid -->
        <div x-show="!loadingSearch && searchResults.length > 0" class="grid-cards">
            <template x-for="sound in searchResults" :key="sound.id || sound.sound_id">
                <div class="glass-card rounded-2xl p-5 group">
                    <!-- Header -->
                    <div class="flex items-start justify-between mb-3">
                        <div class="flex-1 min-w-0 mr-3">
                            <h3 class="font-bold text-white/90 text-sm truncate" x-text="sound.title || 'Som sem titulo'"></h3>
                            <p class="text-xs text-white/40 mt-1 truncate" x-text="sound.author ? '@' + sound.author : 'Autor desconhecido'"></p>
                        </div>
                        <span class="flex-shrink-0" x-html="phaseBadge(sound.phase)"></span>
                    </div>

                    <!-- Stats -->
                    <div class="flex items-center gap-4 mb-4">
                        <div>
                            <p class="text-lg font-bold text-white" x-text="formatSoundNumber(sound.video_count)"></p>
                            <p class="text-[10px] text-white/30 uppercase tracking-wide">Videos</p>
                        </div>
                        <div class="h-8 w-px bg-white/5"></div>
                        <div>
                            <p class="text-lg font-bold" :class="(sound.growth_rate || 0) >= 0 ? 'text-accent-green' : 'text-accent-red'"
                               x-text="formatGrowth(sound.growth_rate)"></p>
                            <p class="text-[10px] text-white/30 uppercase tracking-wide">Crescimento</p>
                        </div>
                    </div>

                    <!-- Footer -->
                    <div class="flex items-center justify-between pt-3 border-t border-white/5">
                        <div class="flex items-center gap-2">
                            <span class="px-2 py-1 rounded-lg text-[10px] font-semibold uppercase tracking-wide"
                                  :class="sound.platform === 'tiktok' ? 'badge-tiktok' : 'badge-instagram'"
                                  x-text="platformLabel(sound.platform)"></span>
                        </div>
                        <a :href="sound.url" target="_blank" rel="noopener"
                           class="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-brand-300 hover:bg-brand-500/10 transition opacity-0 group-hover:opacity-100">
                            <i data-lucide="external-link" class="w-3 h-3"></i> Abrir
                        </a>
                    </div>
                </div>
            </template>
        </div>
    </div>

</div>
{% endblock %}

{% block scripts %}
<script>
function soundsPage() {
    return {
        activeTab: 'trending',
        trendingSounds: [],
        emergingSounds: [],
        searchResults: [],
        loadingTrending: true,
        loadingEmerging: true,
        loadingSearch: false,
        searchKeyword: '',
        searchPlatform: 'tiktok',
        searchPerformed: false,

        get topGrowth() {
            var all = [].concat(this.trendingSounds, this.emergingSounds);
            if (all.length === 0) return '0%';
            var max = Math.max.apply(null, all.map(function(s) { return s.growth_rate || 0; }));
            return this.formatGrowth(max);
        },

        async init() {
            await Promise.all([
                this.fetchTrending(),
                this.fetchEmerging()
            ]);
            this.$nextTick(function() { if (window.lucide) lucide.createIcons(); });
        },

        async fetchTrending() {
            this.loadingTrending = true;
            try {
                var r = await fetch('/api/sounds/trending');
                if (!r.ok) throw new Error('HTTP ' + r.status);
                var data = await r.json();
                this.trendingSounds = data.sounds || data || [];
            } catch (e) {
                console.error('Erro ao carregar sons em alta:', e);
                showToast('Erro ao carregar sons em alta', 'error');
                this.trendingSounds = [];
            } finally {
                this.loadingTrending = false;
                this.$nextTick(function() { if (window.lucide) lucide.createIcons(); });
            }
        },

        async fetchEmerging() {
            this.loadingEmerging = true;
            try {
                var r = await fetch('/api/sounds/emerging');
                if (!r.ok) throw new Error('HTTP ' + r.status);
                var data = await r.json();
                this.emergingSounds = data.sounds || data || [];
            } catch (e) {
                console.error('Erro ao carregar sons emergentes:', e);
                showToast('Erro ao carregar sons emergentes', 'error');
                this.emergingSounds = [];
            } finally {
                this.loadingEmerging = false;
                this.$nextTick(function() { if (window.lucide) lucide.createIcons(); });
            }
        },

        async searchSounds() {
            if (!this.searchKeyword.trim()) return;
            this.loadingSearch = true;
            this.searchPerformed = true;
            try {
                var params = new URLSearchParams({
                    keyword: this.searchKeyword.trim(),
                    platform: this.searchPlatform
                });
                var r = await fetch('/api/sounds/search?' + params.toString());
                if (!r.ok) throw new Error('HTTP ' + r.status);
                var data = await r.json();
                this.searchResults = data.sounds || data || [];
                if (this.searchResults.length > 0) {
                    showToast(this.searchResults.length + ' sons encontrados!', 'success');
                } else {
                    showToast('Nenhum som encontrado para essa busca', 'warning');
                }
            } catch (e) {
                console.error('Erro na busca de sons:', e);
                showToast('Erro ao buscar sons', 'error');
                this.searchResults = [];
            } finally {
                this.loadingSearch = false;
                this.$nextTick(function() { if (window.lucide) lucide.createIcons(); });
            }
        },

        formatSoundNumber(n) {
            if (n == null) return '0';
            n = parseInt(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 n.toLocaleString('pt-BR');
        },

        formatGrowth(rate) {
            if (rate == null) return '0%';
            var val = parseFloat(rate);
            var prefix = val >= 0 ? '+' : '';
            return prefix + val.toFixed(1) + '%';
        },

        phaseBadge(phase) {
            var phases = {
                emerging: {
                    label: 'Emergente',
                    classes: 'bg-cyan-500/15 text-cyan-400 border border-cyan-500/20',
                    icon: 'trending-up'
                },
                growing: {
                    label: 'Crescendo',
                    classes: 'bg-green-500/15 text-green-400 border border-green-500/20',
                    icon: 'arrow-up'
                },
                peak: {
                    label: 'No Pico',
                    classes: 'bg-yellow-500/15 text-yellow-400 border border-yellow-500/20',
                    icon: 'minus'
                },
                declining: {
                    label: 'Declinando',
                    classes: 'bg-red-500/15 text-red-400 border border-red-500/20',
                    icon: 'trending-down'
                }
            };
            var p = phases[phase] || phases.emerging;
            return '<span class="inline-flex items-center gap-1 px-2 py-1 rounded-lg text-[10px] font-semibold uppercase tracking-wide ' + p.classes + '">' +
                   '<i data-lucide="' + p.icon + '" class="w-3 h-3"></i> ' + p.label +
                   '</span>';
        }
    };
}
</script>
{% endblock %}
