{% extends "base.html" %}
{% block title %}Oportunidades - Viral Social Pro{% endblock %}
{% block nav_opportunities %}active{% endblock %}
{% block page_title %}Oportunidades{% endblock %}
{% block page_subtitle %}Cross-platform replicator, affiliate matcher e trend lifecycle{% endblock %}

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

    <div class="flex gap-2 mb-6 overflow-x-auto pb-1 animate-fade-up">
        <button @click="tab = 'replicator'" :class="tab === 'replicator' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="copy" class="w-4 h-4"></i> Cross-Platform
        </button>
        <button @click="tab = 'affiliate'" :class="tab === 'affiliate' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="link" class="w-4 h-4"></i> Affiliate Matcher
        </button>
        <button @click="tab = 'trends'" :class="tab === 'trends' ? 'active' : ''" class="tab-btn flex items-center gap-2">
            <i data-lucide="trending-up" class="w-4 h-4"></i> Trend Lifecycle
        </button>
    </div>

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

    <!-- CROSS-PLATFORM REPLICATOR -->
    <div x-show="tab === 'replicator' && !loading" x-cloak>
        <div class="glass rounded-2xl p-4 mb-6">
            <h3 class="text-sm font-bold text-white/80 mb-2 flex items-center gap-2">
                <i data-lucide="copy" class="w-4 h-4 text-brand-400"></i> Encontrar conteudo viral para replicar
            </h3>
            <p class="text-xs text-white/40 mb-4">Busca videos virais em uma plataforma que ainda nao existem nas outras</p>
            <div class="flex flex-col sm:flex-row gap-3">
                <input type="text" x-model="repKeyword" @keyup.enter="findOpportunities()" placeholder="Keyword (ex: skincare, moda, gadgets)" class="flex-1 bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 outline-none">
                <select x-model="repSource" class="bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80">
                    <option value="tiktok">TikTok → Outras</option>
                    <option value="instagram">Instagram → Outras</option>
                    <option value="youtube">YouTube → Outras</option>
                </select>
                <button @click="findOpportunities()" :disabled="loading" class="px-5 py-2.5 rounded-xl gradient-brand text-white font-semibold text-sm disabled:opacity-50">Buscar</button>
            </div>
        </div>

        <div x-show="repResults">
            <div class="grid grid-cols-2 sm:grid-cols-3 gap-3 mb-6">
                <div class="glass-card rounded-xl p-4 text-center">
                    <p class="stat-number text-white" x-text="repResults?.source_videos || 0"></p>
                    <p class="text-xs text-white/40">Videos Analisados</p>
                </div>
                <div class="glass-card rounded-xl p-4 text-center">
                    <p class="stat-number text-accent-green" x-text="repResults?.opportunities?.filter(o => o.is_unique_creator).length || 0"></p>
                    <p class="text-xs text-white/40">Criadores Unicos</p>
                </div>
                <div class="glass-card rounded-xl p-4 text-center">
                    <p class="stat-number text-accent-orange" x-text="repResults?.opportunities?.length || 0"></p>
                    <p class="text-xs text-white/40">Oportunidades</p>
                </div>
            </div>
            <div class="space-y-3">
                <template x-for="(opp, i) in repResults?.opportunities || []" :key="i">
                    <div class="glass-card rounded-xl p-4">
                        <div class="flex items-start gap-4">
                            <div class="w-14 h-14 rounded-xl bg-dark-800 overflow-hidden flex-shrink-0">
                                <img :src="opp.thumbnail_url" class="w-full h-full object-cover" onerror="this.style.display='none'">
                            </div>
                            <div class="flex-1 min-w-0">
                                <div class="flex items-center gap-2 mb-1">
                                    <span x-show="opp.is_unique_creator" class="px-2 py-0.5 text-[10px] font-bold rounded-md gradient-success text-white">UNICO</span>
                                    <span class="px-2 py-0.5 text-[10px] font-bold rounded-md glass-light text-brand-300" x-text="'Score: ' + opp.replication_score"></span>
                                </div>
                                <p class="text-sm font-semibold text-white/90 line-clamp-2" x-text="opp.title || opp.description"></p>
                                <div class="flex items-center gap-3 mt-1 text-xs text-white/40">
                                    <span x-text="'@' + (opp.creator_username || '')"></span>
                                    <span class="text-brand-300" x-text="formatNumber(opp.views) + ' views'"></span>
                                </div>
                                <p class="text-xs text-accent-green mt-1" x-text="opp.suggestion"></p>
                            </div>
                            <a :href="opp.url" target="_blank" rel="noopener" class="p-2 rounded-lg glass-light hover:bg-white/10"><i data-lucide="external-link" class="w-4 h-4 text-white/40"></i></a>
                        </div>
                    </div>
                </template>
            </div>
        </div>
    </div>

    <!-- AFFILIATE MATCHER -->
    <div x-show="tab === 'affiliate' && !loading" x-cloak>
        <div class="glass rounded-2xl p-4 mb-6">
            <h3 class="text-sm font-bold text-white/80 mb-2 flex items-center gap-2">
                <i data-lucide="link" class="w-4 h-4 text-accent-green"></i> Produtos para promover como afiliado
            </h3>
            <div class="flex gap-3">
                <input type="text" x-model="affKeywords" placeholder="Nichos (ex: skincare, gadgets, fitness)" class="flex-1 bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 outline-none">
                <button @click="findAffiliates()" :disabled="loading" class="px-5 py-2.5 rounded-xl gradient-success text-white font-semibold text-sm disabled:opacity-50">Buscar</button>
            </div>
        </div>
        <div class="space-y-4">
            <template x-for="(match, i) in affMatches" :key="i">
                <div class="glass-card rounded-2xl p-4">
                    <div class="flex items-start gap-4">
                        <div class="w-16 h-16 rounded-xl bg-dark-800 overflow-hidden flex-shrink-0">
                            <img :src="match.product?.image" class="w-full h-full object-cover" onerror="this.style.display='none'">
                        </div>
                        <div class="flex-1">
                            <span class="px-2 py-0.5 text-[10px] font-bold rounded-md gradient-brand text-white" x-text="'Score: ' + match.opportunity_score"></span>
                            <h4 class="text-sm font-bold text-white/90 line-clamp-1 mt-1" x-text="match.product?.title"></h4>
                            <div class="flex items-center gap-3 mt-1 text-xs">
                                <span class="text-accent-green font-bold" x-text="match.product?.price || 'N/A'"></span>
                                <span class="text-white/40" x-text="formatNumber(match.product?.sold_count || 0) + ' vendidos'"></span>
                                <span class="text-brand-300" x-text="formatNumber(match.estimated_reach) + ' alcance'"></span>
                            </div>
                            <div class="flex flex-wrap gap-2 mt-2">
                                <template x-for="vid in match.related_videos || []" :key="vid.url">
                                    <a :href="vid.url" target="_blank" class="px-2 py-1 rounded-md glass-light text-[10px] text-white/60 hover:text-white">@<span x-text="vid.creator"></span> (<span x-text="formatNumber(vid.views)"></span>)</a>
                                </template>
                            </div>
                        </div>
                    </div>
                </div>
            </template>
        </div>
    </div>

    <!-- TREND LIFECYCLE -->
    <div x-show="tab === 'trends' && !loading" x-cloak>
        <div class="glass rounded-2xl p-4 mb-6">
            <h3 class="text-sm font-bold text-white/80 mb-2 flex items-center gap-2">
                <i data-lucide="trending-up" class="w-4 h-4 text-accent-orange"></i> Analisar fase de uma trend
            </h3>
            <p class="text-xs text-white/40 mb-4">Emergente → Crescendo → Pico → Declinando</p>
            <div class="flex gap-3">
                <input type="text" x-model="trendKeyword" @keyup.enter="analyzeTrend()" placeholder="Keyword ou hashtag" class="flex-1 bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80 outline-none">
                <select x-model="trendPlatform" class="bg-dark-700 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-white/80">
                    <option value="tiktok">TikTok</option>
                    <option value="instagram">Instagram</option>
                    <option value="youtube">YouTube</option>
                </select>
                <button @click="analyzeTrend()" :disabled="loading" class="px-5 py-2.5 rounded-xl gradient-fire text-white font-semibold text-sm disabled:opacity-50">Analisar</button>
            </div>
        </div>

        <div x-show="trendResult" class="glass-card rounded-2xl p-6 mb-6">
            <div class="flex items-center gap-4 mb-4">
                <div class="text-4xl" x-text="trendResult?.phase_emoji || ''"></div>
                <div>
                    <h3 class="text-xl font-bold text-white" x-text="trendResult?.keyword"></h3>
                    <p class="text-sm font-semibold" :class="{'text-accent-green': trendResult?.phase==='emerging', 'text-brand-300': trendResult?.phase==='growing', 'text-accent-orange': trendResult?.phase==='peak', 'text-accent-red': trendResult?.phase==='declining'}" x-text="trendResult?.phase_label + ' - ' + trendResult?.phase_action"></p>
                </div>
            </div>
            <div class="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-4">
                <div class="glass-light rounded-xl p-3 text-center"><p class="text-lg font-bold text-white" x-text="trendResult?.video_count || 0"></p><p class="text-[10px] text-white/40">Videos</p></div>
                <div class="glass-light rounded-xl p-3 text-center"><p class="text-lg font-bold text-brand-300" x-text="formatNumber(trendResult?.avg_views || 0)"></p><p class="text-[10px] text-white/40">Media Views</p></div>
                <div class="glass-light rounded-xl p-3 text-center"><p class="text-lg font-bold text-accent-green" x-text="(trendResult?.avg_engagement || 0).toFixed(2) + '%'"></p><p class="text-[10px] text-white/40">Engajamento</p></div>
                <div class="glass-light rounded-xl p-3 text-center"><p class="text-lg font-bold text-white" x-text="(trendResult?.top_creators || []).length"></p><p class="text-[10px] text-white/40">Top Criadores</p></div>
            </div>
            <div x-show="trendResult?.top_creators?.length" class="flex flex-wrap gap-2 mb-4">
                <template x-for="c in trendResult?.top_creators || []" :key="c.username">
                    <span class="px-3 py-1 rounded-lg glass-light text-xs text-white/70">@<span x-text="c.username"></span></span>
                </template>
            </div>
            <div x-show="trendResult?.sample_videos?.length" class="space-y-2">
                <template x-for="(v, i) in (trendResult?.sample_videos || []).slice(0,5)" :key="i">
                    <a :href="v.url" target="_blank" class="flex items-center gap-3 glass-light rounded-xl p-3 hover:bg-white/10 transition">
                        <div class="flex-1 min-w-0">
                            <p class="text-xs text-white/70 truncate" x-text="v.title || v.description"></p>
                            <p class="text-[10px] text-white/40" x-text="'@' + (v.creator_username||'') + ' • ' + formatNumber(v.views) + ' views'"></p>
                        </div>
                        <i data-lucide="external-link" class="w-4 h-4 text-white/30"></i>
                    </a>
                </template>
            </div>
        </div>

        <div x-show="trackedTrends.length > 0">
            <h3 class="text-sm font-bold text-white/60 mb-3">Trends Rastreadas</h3>
            <div class="grid-cards">
                <template x-for="t in trackedTrends" :key="t.id">
                    <div class="glass-card rounded-xl p-4 cursor-pointer hover:scale-[1.02] transition-transform" @click="trendKeyword = t.keyword; trendPlatform = t.platform; analyzeTrend()">
                        <div class="flex items-center gap-3">
                            <span class="text-2xl" x-text="({'emerging':'🟢','growing':'📈','peak':'🔴','declining':'⬇️'})[t.phase] || '❓'"></span>
                            <div>
                                <p class="text-sm font-bold text-white" x-text="t.keyword"></p>
                                <p class="text-xs text-white/40" x-text="t.platform + ' • ' + formatNumber(t.avg_views) + ' avg views'"></p>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
function opportunitiesApp() {
    return {
        tab: 'replicator', loading: false, loadingMsg: '',
        repKeyword: '', repSource: 'tiktok', repResults: null,
        affKeywords: 'skincare, gadgets, moda feminina', affMatches: [],
        trendKeyword: '', trendPlatform: 'tiktok', trendResult: null, trackedTrends: [],

        async init() {
            this.loadTrackedTrends();
            this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },
        async findOpportunities() {
            if (!this.repKeyword.trim()) return;
            this.loading = true; this.loadingMsg = 'Buscando oportunidades cross-platform...';
            try {
                const r = await fetch(`/api/cross-platform/opportunities?keyword=${encodeURIComponent(this.repKeyword)}&source=${this.repSource}`);
                this.repResults = await r.json();
                showToast(`${this.repResults.opportunities?.length || 0} oportunidades`, 'success');
            } catch(e) { showToast('Erro', 'error'); }
            this.loading = false; this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },
        async findAffiliates() {
            if (!this.affKeywords.trim()) return;
            this.loading = true; this.loadingMsg = 'Buscando produtos para afiliacao...';
            try {
                const r = await fetch(`/api/cross-platform/affiliate-match?keywords=${encodeURIComponent(this.affKeywords)}`);
                const d = await r.json();
                this.affMatches = d.matches || [];
                showToast(`${this.affMatches.length} matches`, 'success');
            } catch(e) { showToast('Erro', 'error'); }
            this.loading = false; this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },
        async analyzeTrend() {
            if (!this.trendKeyword.trim()) return;
            this.loading = true; this.loadingMsg = 'Analisando trend...';
            try {
                const r = await fetch(`/api/trends/lifecycle?keyword=${encodeURIComponent(this.trendKeyword)}&platform=${this.trendPlatform}`);
                this.trendResult = await r.json();
                this.loadTrackedTrends();
            } catch(e) { showToast('Erro', 'error'); }
            this.loading = false; this.$nextTick(() => { if (window.lucide) lucide.createIcons(); });
        },
        async loadTrackedTrends() {
            try { const r = await fetch('/api/trends/tracked'); const d = await r.json(); this.trackedTrends = d.trends || []; } catch(e) {}
        },
    }
}
</script>
{% endblock %}
